<commit_before>/*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2017 New Vector Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

'use strict';

const React = require('react');
const ReactDOM = require("react-dom");
import PropTypes from 'prop-types';
const classNames = require('classnames');
import dis from '../../../dispatcher';
const MatrixClientPeg = require('../../../MatrixClientPeg');
import DMRoomMap from '../../../utils/DMRoomMap';
const sdk = require('../../../index');
const ContextualMenu = require('../../structures/ContextualMenu');
const RoomNotifs = require('../../../RoomNotifs');
const FormattingUtils = require('../../../utils/FormattingUtils');
import AccessibleButton from '../elements/AccessibleButton';
import ActiveRoomObserver from '../../../ActiveRoomObserver';
import RoomViewStore from '../../../stores/RoomViewStore';

module.exports = React.createClass({
    displayName: 'RoomTile',

    propTypes: {
        onClick: PropTypes.func,

        room: PropTypes.object.isRequired,
        collapsed: PropTypes.bool.isRequired,
        unread: PropTypes.bool.isRequired,
        highlight: PropTypes.bool.isRequired,
        // If true, apply mx_RoomTile_transparent class
        transparent: PropTypes.bool,
        isInvite: PropTypes.bool.isRequired,
        incomingCall: PropTypes.object,
    },

    getDefaultProps: function() {
        return {
            isDragging: false,
        };
    },

    getInitialState: function() {
        return ({
            hover: false,
            badgeHover: false,
            menuDisplayed: false,
            roomName: this.props.room.name,
            notifState: RoomNotifs.getRoomNotifsState(this.props.room.roomId),
            notificationCount: this.props.room.getUnreadNotificationCount(),
            selected: this.props.room.roomId === RoomViewStore.getRoomId(),
        });
    },

    _shouldShowNotifBadge: function() {
        const showBadgeInStates = [RoomNotifs.ALL_MESSAGES, RoomNotifs.ALL_MESSAGES_LOUD];
        return showBadgeInStates.indexOf(this.state.notifState) > -1;
    },

    _shouldShowMentionBadge: function() {
        return this.state.notifState != RoomNotifs.MUTE;
    },

    _isDirectMessageRoom: function(roomId) {
        const dmRooms = DMRoomMap.shared().getUserIdForRoomId(roomId);
        if (dmRooms) {
            return true;
        } else {
            return false;
        }
    },

    onRoomTimeline: function(ev, room) {
        if (room !== this.props.room) return;
        this.setState({
            notificationCount: this.props.room.getUnreadNotificationCount(),
        });
    },

    onRoomName: function(room) {
        if (room !== this.props.room) return;
        this.setState({
            roomName: this.props.room.name,
        });
    },

    onAccountData: function(accountDataEvent) {
        if (accountDataEvent.getType() == 'm.push_rules') {
            this.setState({
                notifState: RoomNotifs.getRoomNotifsState(this.props.room.roomId),
            });
        }
    },

    onAction: function(payload) {
        switch (payload.action) {
            // XXX: slight hack in order to zero the notification count when a room
            // is read. Ideally this state would be given to this via props (as we
            // do with `unread`). This is still better than forceUpdating the entire
            // RoomList when a room is read.
            case 'on_room_read':
                if (payload.roomId !== this.props.room.roomId) break;
                this.setState({
                    notificationCount: this.props.room.getUnreadNotificationCount(),
                });
            break;
        }
    },

    _onActiveRoomChange: function() {
        this.setState({
            selected: this.props.room.roomId === RoomViewStore.getRoomId(),
        });
    },

    componentWillMount: function() {
        MatrixClientPeg.get().on("accountData", this.onAccountData);
        MatrixClientPeg.get().on("Room.timeline", this.onRoomTimeline);
        MatrixClientPeg.get().on("Room.name", this.onRoomName);
        ActiveRoomObserver.addListener(this.props.room.roomId, this._onActiveRoomChange);
        this.dispatcherRef = dis.register(this.onAction);
    },

    componentWillUnmount: function() {
        const cli = MatrixClientPeg.get();
        if (cli) {
            MatrixClientPeg.get().removeListener("accountData", this.onAccountData);
            MatrixClientPeg.get().removeListener("Room.timeline", this.onRoomTimeline);
            MatrixClientPeg.get().removeListener("Room.name", this.onRoomName);
        }
        ActiveRoomObserver.removeListener(this.props.room.roomId, this._onActiveRoomChange);
        dis.unregister(this.dispatcherRef);
    },

    componentWillReceiveProps: function(props) {
        // XXX: This could be a lot better - this makes the assumption that
        // the notification count may have changed when the properties of
        // the room tile change.
        this.setState({
            notificationCount: this.props.room.getUnreadNotificationCount(),
        });
    },

    // Do a simple shallow comparison of props and state to avoid unnecessary
    // renders. The assumption made here is that only state and props are used
    // in rendering this component and children.
    //
    // RoomList is frequently made to forceUpdate, so this decreases number of
    // RoomTile renderings.
    shouldComponentUpdate: function(newProps, newState) {
        if (Object.keys(newProps).some((k) => newProps[k] !== this.props[k])) {
            return true;
        }
        if (Object.keys(newState).some((k) => newState[k] !== this.state[k])) {
            return true;
        }
        return false;
    },

    onClick: function(ev) {
        if (this.props.onClick) {
            this.props.onClick(this.props.room.roomId, ev);
        }
    },

    onMouseEnter: function() {
        this.setState( { hover: true });
        this.badgeOnMouseEnter();
    },

    onMouseLeave: function() {
        this.setState( { hover: false });
        this.badgeOnMouseLeave();
    },

    onContextMenu: function(e) {
        this.onBadgeClicked(e);
        e.preventDefault();
    },

    badgeOnMouseEnter: function() {
        // Only allow non-guests to access the context menu
        // and only change it if it needs to change
        if (!MatrixClientPeg.get().isGuest() && !this.state.badgeHover) {
            this.setState( { badgeHover: true } );
        }
    },

    badgeOnMouseLeave: function() {
        this.setState( { badgeHover: false } );
    },

    onBadgeClicked: function(e) {
        // Only allow none guests to access the context menu
        if (!MatrixClientPeg.get().isGuest()) {
            // If the badge is clicked, then no longer show tooltip
            if (this.props.collapsed) {
                this.setState({ hover: false });
            }

            const RoomTileContextMenu = sdk.getComponent('context_menus.RoomTileContextMenu');
            const elementRect = this.refs.badge.getBoundingClientRect();

            // The window X and Y offsets are to adjust position when zoomed in to page
            const x = elementRect.right + window.pageXOffset + 3;
            const chevronOffset = 12;
            let y = (elementRect.top + (elementRect.height / 2) + window.pageYOffset);
            y = y - (chevronOffset + 8); // where 8 is half the height of the chevron

            const self = this;
            ContextualMenu.createMenu(RoomTileContextMenu, {
                chevronOffset: chevronOffset,
                left: x,
                top: y,
                room: this.props.room,
                onFinished: function() {
                    self.setState({ menuDisplayed: false });
                    self.props.refreshSubList();
                },
            });
            this.setState({ menuDisplayed: true });
        }
        // Prevent the RoomTile onClick event firing as well
        e.stopPropagation();
    },

    render: function() {
        const myUserId = MatrixClientPeg.get().credentials.userId;
        const me = this.props.room.currentState.members[myUserId];

        const notificationCount = this.state.notificationCount;
        // var highlightCount = this.props.room.getUnreadNotificationCount("highlight");

        const notifBadges = notificationCount > 0 && this._shouldShowNotifBadge();
        const mentionBadges = this.props.highlight && this._shouldShowMentionBadge();
        const badges = notifBadges || mentionBadges;

        const classes = classNames({
            'mx_RoomTile': true,
            'mx_RoomTile_selected': this.state.selected,
            'mx_RoomTile_unread': this.props.unread,
            'mx_RoomTile_unreadNotify': notifBadges,
            'mx_RoomTile_highlight': mentionBadges,
            'mx_RoomTile_invited': (me && me.membership == 'invite'),
            'mx_RoomTile_menuDisplayed': this.state.menuDisplayed,
            'mx_RoomTile_noBadges': !badges,
            'mx_RoomTile_transparent': this.props.transparent,
        });

        const avatarClasses = classNames({
            'mx_RoomTile_avatar': true,
        });

        const badgeClasses = classNames({
            'mx_RoomTile_badge': true,
            'mx_RoomTile_badgeButton': this.state.badgeHover || this.state.menuDisplayed,
        });

        let name = this.state.roomName;
        name = name.replace(":", ":\u200b"); // add a zero-width space to allow linewrapping after the colon

        let badge;
        let badgeContent;

        if (this.state.badgeHover || this.state.menuDisplayed) {
            badgeContent = "\u00B7\u00B7\u00B7";
        } else if (badges) {
            const limitedCount = FormattingUtils.formatCount(notificationCount);
            badgeContent = notificationCount ? limitedCount : '!';
        } else {
            badgeContent = '\u200B';
        }

        badge =
{ badgeContent }
;

        const EmojiText = sdk.getComponent('elements.EmojiText');
        let label;
        let tooltip;
        if (!this.props.collapsed) {
            const nameClasses = classNames({
                'mx_RoomTile_name': true,
                'mx_RoomTile_invite': this.props.isInvite,
                'mx_RoomTile_badgeShown': badges || this.state.badgeHover || this.state.menuDisplayed,
            });

            if (this.state.selected) {
                const nameSelected = <EmojiText>{ name }</EmojiText>;

                label =
{ nameSelected }
;
            } else {
                label = <EmojiText element="div" title={name} className={nameClasses} dir="auto">{ name }</EmojiText>;
            }
        } else if (this.state.hover) {
            const RoomTooltip = sdk.getComponent("rooms.RoomTooltip");
            tooltip = <RoomTooltip className="mx_RoomTile_tooltip" label={this.props.room.name} dir="auto" />;
        }

        //var incomingCallBox;
        //if (this.props.incomingCall) {
        //    var IncomingCallBox = sdk.getComponent("voip.IncomingCallBox");
        //    incomingCallBox = <IncomingCallBox incomingCall={ this.props.incomingCall }/>;
        //}

        const RoomAvatar = sdk.getComponent('avatars.RoomAvatar');

        let directMessageIndicator;
        if (this._isDirectMessageRoom(this.props.room.roomId)) {
            directMessageIndicator = ;
        }

        return <AccessibleButton tabIndex="0"
                                 className={classes}
                                 onClick={this.onClick}
                                 onMouseEnter={this.onMouseEnter}
                                 onMouseLeave={this.onMouseLeave}
                                 onContextMenu={this.onContextMenu}
        >

                    <RoomAvatar room={this.props.room} width={24} height={24} />
                    { directMessageIndicator }

                { label }
                { badge }

            { /* { incomingCallBox } */ }
            { tooltip }
        </AccessibleButton>;
    },
});
<commit_msg>delint<commit_after>/*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2017 New Vector Ltd
Copyright 2018 Michael Telatynski <7t3chguy@gmail.com>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import dis from '../../../dispatcher';
import MatrixClientPeg from '../../../MatrixClientPeg';
import DMRoomMap from '../../../utils/DMRoomMap';
import sdk from '../../../index';
import ContextualMenu from '../../structures/ContextualMenu';
import * as RoomNotifs from '../../../RoomNotifs';
import * as FormattingUtils from '../../../utils/FormattingUtils';
import AccessibleButton from '../elements/AccessibleButton';
import ActiveRoomObserver from '../../../ActiveRoomObserver';
import RoomViewStore from '../../../stores/RoomViewStore';

module.exports = React.createClass({
    displayName: 'RoomTile',

    propTypes: {
        onClick: PropTypes.func,

        room: PropTypes.object.isRequired,
        collapsed: PropTypes.bool.isRequired,
        unread: PropTypes.bool.isRequired,
        highlight: PropTypes.bool.isRequired,
        // If true, apply mx_RoomTile_transparent class
        transparent: PropTypes.bool,
        isInvite: PropTypes.bool.isRequired,
        incomingCall: PropTypes.object,
    },

    getDefaultProps: function() {
        return {
            isDragging: false,
        };
    },

    getInitialState: function() {
        return ({
            hover: false,
            badgeHover: false,
            menuDisplayed: false,
            roomName: this.props.room.name,
            notifState: RoomNotifs.getRoomNotifsState(this.props.room.roomId),
            notificationCount: this.props.room.getUnreadNotificationCount(),
            selected: this.props.room.roomId === RoomViewStore.getRoomId(),
        });
    },

    _shouldShowNotifBadge: function() {
        const showBadgeInStates = [RoomNotifs.ALL_MESSAGES, RoomNotifs.ALL_MESSAGES_LOUD];
        return showBadgeInStates.indexOf(this.state.notifState) > -1;
    },

    _shouldShowMentionBadge: function() {
        return this.state.notifState !== RoomNotifs.MUTE;
    },

    _isDirectMessageRoom: function(roomId) {
        const dmRooms = DMRoomMap.shared().getUserIdForRoomId(roomId);
        return Boolean(dmRooms);
    },

    onRoomTimeline: function(ev, room) {
        if (room !== this.props.room) return;
        this.setState({
            notificationCount: this.props.room.getUnreadNotificationCount(),
        });
    },

    onRoomName: function(room) {
        if (room !== this.props.room) return;
        this.setState({
            roomName: this.props.room.name,
        });
    },

    onAccountData: function(accountDataEvent) {
        if (accountDataEvent.getType() === 'm.push_rules') {
            this.setState({
                notifState: RoomNotifs.getRoomNotifsState(this.props.room.roomId),
            });
        }
    },

    onAction: function(payload) {
        switch (payload.action) {
            // XXX: slight hack in order to zero the notification count when a room
            // is read. Ideally this state would be given to this via props (as we
            // do with `unread`). This is still better than forceUpdating the entire
            // RoomList when a room is read.
            case 'on_room_read':
                if (payload.roomId !== this.props.room.roomId) break;
                this.setState({
                    notificationCount: this.props.room.getUnreadNotificationCount(),
                });
            break;
        }
    },

    _onActiveRoomChange: function() {
        this.setState({
            selected: this.props.room.roomId === RoomViewStore.getRoomId(),
        });
    },

    componentWillMount: function() {
        MatrixClientPeg.get().on("accountData", this.onAccountData);
        MatrixClientPeg.get().on("Room.timeline", this.onRoomTimeline);
        MatrixClientPeg.get().on("Room.name", this.onRoomName);
        ActiveRoomObserver.addListener(this.props.room.roomId, this._onActiveRoomChange);
        this.dispatcherRef = dis.register(this.onAction);
    },

    componentWillUnmount: function() {
        const cli = MatrixClientPeg.get();
        if (cli) {
            MatrixClientPeg.get().removeListener("accountData", this.onAccountData);
            MatrixClientPeg.get().removeListener("Room.timeline", this.onRoomTimeline);
            MatrixClientPeg.get().removeListener("Room.name", this.onRoomName);
        }
        ActiveRoomObserver.removeListener(this.props.room.roomId, this._onActiveRoomChange);
        dis.unregister(this.dispatcherRef);
    },

    componentWillReceiveProps: function(props) {
        // XXX: This could be a lot better - this makes the assumption that
        // the notification count may have changed when the properties of
        // the room tile change.
        this.setState({
            notificationCount: this.props.room.getUnreadNotificationCount(),
        });
    },

    // Do a simple shallow comparison of props and state to avoid unnecessary
    // renders. The assumption made here is that only state and props are used
    // in rendering this component and children.
    //
    // RoomList is frequently made to forceUpdate, so this decreases number of
    // RoomTile renderings.
    shouldComponentUpdate: function(newProps, newState) {
        if (Object.keys(newProps).some((k) => newProps[k] !== this.props[k])) {
            return true;
        }
        if (Object.keys(newState).some((k) => newState[k] !== this.state[k])) {
            return true;
        }
        return false;
    },

    onClick: function(ev) {
        if (this.props.onClick) {
            this.props.onClick(this.props.room.roomId, ev);
        }
    },

    onMouseEnter: function() {
        this.setState( { hover: true });
        this.badgeOnMouseEnter();
    },

    onMouseLeave: function() {
        this.setState( { hover: false });
        this.badgeOnMouseLeave();
    },

    onContextMenu: function(e) {
        this.onBadgeClicked(e);
        e.preventDefault();
    },

    badgeOnMouseEnter: function() {
        // Only allow non-guests to access the context menu
        // and only change it if it needs to change
        if (!MatrixClientPeg.get().isGuest() && !this.state.badgeHover) {
            this.setState( { badgeHover: true } );
        }
    },

    badgeOnMouseLeave: function() {
        this.setState( { badgeHover: false } );
    },

    onBadgeClicked: function(e) {
        // Only allow none guests to access the context menu
        if (!MatrixClientPeg.get().isGuest()) {
            // If the badge is clicked, then no longer show tooltip
            if (this.props.collapsed) {
                this.setState({ hover: false });
            }

            const RoomTileContextMenu = sdk.getComponent('context_menus.RoomTileContextMenu');
            const elementRect = this.refs.badge.getBoundingClientRect();

            // The window X and Y offsets are to adjust position when zoomed in to page
            const x = elementRect.right + window.pageXOffset + 3;
            const chevronOffset = 12;
            let y = (elementRect.top + (elementRect.height / 2) + window.pageYOffset);
            y = y - (chevronOffset + 8); // where 8 is half the height of the chevron

            const self = this;
            ContextualMenu.createMenu(RoomTileContextMenu, {
                chevronOffset: chevronOffset,
                left: x,
                top: y,
                room: this.props.room,
                onFinished: function() {
                    self.setState({ menuDisplayed: false });
                    self.props.refreshSubList();
                },
            });
            this.setState({ menuDisplayed: true });
        }
        // Prevent the RoomTile onClick event firing as well
        e.stopPropagation();
    },

    render: function() {
        const myUserId = MatrixClientPeg.get().credentials.userId;
        const me = this.props.room.currentState.members[myUserId];

        const notificationCount = this.state.notificationCount;
        // var highlightCount = this.props.room.getUnreadNotificationCount("highlight");

        const notifBadges = notificationCount > 0 && this._shouldShowNotifBadge();
        const mentionBadges = this.props.highlight && this._shouldShowMentionBadge();
        const badges = notifBadges || mentionBadges;

        const classes = classNames({
            'mx_RoomTile': true,
            'mx_RoomTile_selected': this.state.selected,
            'mx_RoomTile_unread': this.props.unread,
            'mx_RoomTile_unreadNotify': notifBadges,
            'mx_RoomTile_highlight': mentionBadges,
            'mx_RoomTile_invited': (me && me.membership === 'invite'),
            'mx_RoomTile_menuDisplayed': this.state.menuDisplayed,
            'mx_RoomTile_noBadges': !badges,
            'mx_RoomTile_transparent': this.props.transparent,
        });

        const avatarClasses = classNames({
            'mx_RoomTile_avatar': true,
        });

        const badgeClasses = classNames({
            'mx_RoomTile_badge': true,
            'mx_RoomTile_badgeButton': this.state.badgeHover || this.state.menuDisplayed,
        });

        let name = this.state.roomName;
        name = name.replace(":", ":\u200b"); // add a zero-width space to allow linewrapping after the colon

        let badgeContent;

        if (this.state.badgeHover || this.state.menuDisplayed) {
            badgeContent = "\u00B7\u00B7\u00B7";
        } else if (badges) {
            const limitedCount = FormattingUtils.formatCount(notificationCount);
            badgeContent = notificationCount ? limitedCount : '!';
        } else {
            badgeContent = '\u200B';
        }

        const badge =
{ badgeContent }
;

        const EmojiText = sdk.getComponent('elements.EmojiText');
        let label;
        let tooltip;
        if (!this.props.collapsed) {
            const nameClasses = classNames({
                'mx_RoomTile_name': true,
                'mx_RoomTile_invite': this.props.isInvite,
                'mx_RoomTile_badgeShown': badges || this.state.badgeHover || this.state.menuDisplayed,
            });

            if (this.state.selected) {
                const nameSelected = <EmojiText>{ name }</EmojiText>;

                label =
{ nameSelected }
;
            } else {
                label = <EmojiText element="div" title={name} className={nameClasses} dir="auto">{ name }</EmojiText>;
            }
        } else if (this.state.hover) {
            const RoomTooltip = sdk.getComponent("rooms.RoomTooltip");
            tooltip = <RoomTooltip className="mx_RoomTile_tooltip" label={this.props.room.name} dir="auto" />;
        }

        //var incomingCallBox;
        //if (this.props.incomingCall) {
        //    var IncomingCallBox = sdk.getComponent("voip.IncomingCallBox");
        //    incomingCallBox = <IncomingCallBox incomingCall={ this.props.incomingCall }/>;
        //}

        const RoomAvatar = sdk.getComponent('avatars.RoomAvatar');

        let dmIndicator;
        if (this._isDirectMessageRoom(this.props.room.roomId)) {
            dmIndicator = ;
        }

        return <AccessibleButton tabIndex="0"
                                 className={classes}
                                 onClick={this.onClick}
                                 onMouseEnter={this.onMouseEnter}
                                 onMouseLeave={this.onMouseLeave}
                                 onContextMenu={this.onContextMenu}
        >

                    <RoomAvatar room={this.props.room} width={24} height={24} />
                    { dmIndicator }

                { label }
                { badge }

            { /* { incomingCallBox } */ }
            { tooltip }
        </AccessibleButton>;
    },
});
<|endoftext|>


<commit_before>BlogListController.$inject = [
    '$scope',
    '$location',
    '$http',
    'api',
    'gettext',
    'upload',
    'isArchivedFilterSelected',
    '$q',
    'blogSecurityService',
    'notify',
    'config',
    'urls',
    'moment',
    'modal',
    'blogService',
];

export default function BlogListController(
    $scope,
    $location,
    $http,
    api,
    gettext,
    upload,
    isArchivedFilterSelected,
    $q,
    blogSecurityService,
    notify,
    config,
    urls,
    moment,
    modal,
    blogService
) {
    $scope.maxResults = 25;
    $scope.states = [
        {name: 'active', code: 'open', text: gettext('Active blogs')},
        {name: 'archived', code: 'closed', text: gettext('Archived blogs')},
    ];
    $scope.activeState = isArchivedFilterSelected ? $scope.states[1] : $scope.states[0];
    $scope.creationStep = 'Details';
    $scope.requestAccessMessage = gettext('Click to request access');
    $scope.blogMembers = [];
    $scope.changeState = function(state) {
        $scope.activeState = state;
        $location.path('/liveblog/' + state.name);
        fetchBlogs();
    };
    $scope.modalActive = false;
    $scope.bulkActions = 0;

    $scope.mailto = 'mailto:upgrade@liveblog.pro?subject=' +
        encodeURIComponent(location.hostname) +
        ' ' +
        config.subscriptionLevel;

    function clearCreateBlogForm() {
        $scope.preview = {};
        $scope.progress = {width: 0};
        $scope.newBlog = {
            title: '',
            description: '',
        };
        $scope.newBlogError = '';
        $scope.creationStep = 'Details';
        $scope.blogMembers = [];
    }
    clearCreateBlogForm();
    $scope.isAdmin = blogSecurityService.isAdmin;
    $scope.isUserAllowedToCreateABlog = blogSecurityService.canCreateABlog;
    $scope.isUserAllowedToOpenBlog = blogSecurityService.canAccessBlog;
    // blog list embed code.
    function fetchBloglistEmbed() {
        const criteria = {source: {
            query: {filtered: {filter: {term: {key: 'blogslist'}}}},
        }};

        api.blogslist.query(criteria, false).then((embed) => {
            let url;

            if (embed._items.length) {
                url = embed._items[0].value;
            } else if (config.debug) {
                url = 'http://localhost:5000/blogslist_embed';
            }
            if (url) {
                $scope.bloglistEmbed = '';
            }
        });
    }

    function bulkDelete(blog) {
        api.blogs.remove(angular.copy(blog)).then((message) => {
            notify.pop();
            notify.info(gettext('Blog removed'));
        }, () => {
            notify.pop();
            notify.error(gettext('Something went wrong'));
        });
    }

    $scope.askRemoveBlog = function() {
        modal.confirm(gettext('Are you sure you want to delete the blog(s)?'))
            .then(() => {
                var selectedBlogs = [];

                angular.forEach($scope.blogs._items, (blog) => {
                    if (blog.selected) {
                        bulkDelete(blog);
                    }
                });

                $scope.blogs._items = $scope.blogs._items.filter((el) => selectedBlogs.indexOf(el) < 0);
            });
    };

    $scope.cancelEmbed = function() {
        $scope.embedModal = false;
    };
    $scope.openEmbed = function() {
        fetchBloglistEmbed();
        $scope.embedModal = true;
    };

    $scope.blogSelect = function($event, isSelected) {
        $event.stopPropagation();
        if (isSelected) {
            $scope.bulkActions += 1;
        } else {
            $scope.bulkActions -= 1;
        }
    };

    $scope.bulkActionCancel = () => {
        angular.forEach($scope.blogs._items, (blog) => {
            blog.selected = false;
        });
        $scope.bulkActions = 0;
    };

    $scope.bulkAction = function(activeState) {
        let selectedBlogs = [];

        angular.forEach($scope.blogs._items, (blog) => {
            if (blog.selected) {
                selectedBlogs.push(blog);
                const deferred = $q.defer();

                const changedBlog = {
                    blog_status: activeState.name == 'active' ? 'closed' : 'open',
                };

                let newBlog = angular.copy(blog);

                angular.extend(newBlog, changedBlog);
                delete newBlog._latest_version;
                delete newBlog._current_version;
                delete newBlog._version;
                delete newBlog.marked_for_not_publication;
                delete newBlog._type;
                delete newBlog.selected;
                delete newBlog.firstcreated;
                newBlog.original_creator = blog.original_creator._id;
                blogService.update(blog, newBlog).then((blog) => {
                    notify.pop();
                    if (blog.blog_status == 'closed') {
                        notify.info(gettext('Blog(s) moved to archived'));
                    } else {
                        notify.info(gettext('Blog(s) is actived now'));
                    }
                    deferred.resolve();
                    $scope.bulkActions = 0;
                });
                return deferred.promise;
            }
        });

        $scope.blogs._items = $scope.blogs._items.filter((el) => selectedBlogs.indexOf(el) < 0);
    };

    $scope.cancelCreate = function() {
        clearCreateBlogForm();
        $scope.newBlogModalActive = false;
    };

    $scope.cancelUpgrade = function() {
        $scope.embedUpgrade = false;
    };

    $scope.openNewBlog = function() {
        blogSecurityService
            .showUpgradeModal()
            .then((showUpgradeModal) => {
                if (showUpgradeModal) {
                    $scope.embedUpgrade = true;
                } else {
                    $scope.newBlogModalActive = true;
                }
            });
    };

    $scope.creationInProcess = false;

    $scope.createBlog = function() {
        $scope.creationInProcess = true;

        const members = _.map($scope.blogMembers, (obj) => ({user: obj._id}));

        // Upload image only if we have a valid one chosen
        const promise = $scope.preview.url ? $scope.upload($scope.preview) : $q.when();

        return promise.then(() => api.blogs
            .save({
                title: $scope.newBlog.title,
                description: $scope.newBlog.description,
                picture_url: $scope.newBlog.picture_url,
                picture: $scope.newBlog.picture,
                picture_renditions: $scope.newBlog.picture_renditions,
                members: members,
            })
            .then((blog) => {
                $scope.creationInProcess = false;
                $scope.edit(blog);
            }, (error) => {
                $scope.creationInProcess = false;
                // Error handler
                $scope.newBlogError = gettext('Something went wrong. Please try again later');
            }));
    };

    $scope.upload = function(config) {
        const form = {};

        if (config.img) {
            form.media = config.img;
        } else if (config.url) {
            form.URL = config.url;
        }

        if (form.hasOwnProperty('media') || form.hasOwnProperty('url')) {
            // return a promise of upload which will call the success/error callback
            return urls.resource('archive').then((uploadUrl) => upload.start({
                method: 'POST',
                url: uploadUrl,
                data: form,
            })
                .then((response) => {
                    if (response.data._status === 'ERR') {
                        return;
                    }
                    var pictureUrl = response.data.renditions.viewImage.href;

                    $scope.newBlog.picture_url = pictureUrl;
                    $scope.newBlog.picture = response.data._id;
                    $scope.newBlog.picture_renditions = response.data.renditions;
                }, (error) => {
                    notify.error(
                        error.statusText !== '' ? error.statusText : gettext('There was a problem with your upload')
                    );
                }, (progress) => {
                    $scope.progress.width = Math.round(progress.loaded / progress.total * 100.0);
                }));
        }
    };

    $scope.remove = function(blog) {
        _.remove($scope.blogs._items, blog);
    };

    $scope.edit = function(blog) {
        $location.path('/liveblog/edit/' + blog._id);
    };

    $scope.openAccessRequest = function(blog) {
        $scope.accessRequestedTo = blog;
        $scope.showBlogAccessModal = true;

        if (config.subscriptionLevel
        && ['solo', 'team'].indexOf(config.subscriptionLevel) !== -1) {
            $scope.checkAccessRequestLimit(blog);
        } else {
            $scope.allowAccessRequest = true;
        }
    };

    $scope.closeAccessRequest = function() {
        $scope.accessRequestedTo = false;
        $scope.showBlogAccessModal = false;
    };

    $scope.checkAccessRequestLimit = function(blog) {
        $scope.allowAccessRequest = false;

        const theoricalMembers = [];

        if (blog.members) {
            blog.members.forEach((member) => {
                if (theoricalMembers.indexOf(member.user) === -1) {
                    theoricalMembers.push(member.user);
                }
            });
        }

        $http({
            url: config.server.url + '/blogs/' + blog._id + '/request_membership',
            method: 'GET',
            headers: {
                'Content-Type': 'application/json;charset=utf-8',
            },
        })
            .then((response) => {
                if (response.data._items.length > 0) {
                    response.data._items.forEach((item) => {
                        if (theoricalMembers.indexOf(item._id) === -1) {
                            theoricalMembers.push(item._id);
                        }
                    });
                }

                if (theoricalMembers.length < config.assignableUsers[config.subscriptionLevel]) {
                    $scope.allowAccessRequest = true;
                }
            });
    };

    $scope.requestAccess = function(blog) {
        let showRequestDialog = true;

        // Check to see if the current user hasn't been accepted during this session (before refreshing)
        if (blog.members) {
            _.each(blog.members, (member) => {
                if (member.user === $scope.$root.currentUser._id) {
                    showRequestDialog = false;
                }
            });
        }

        if (showRequestDialog) {
            notify.info(gettext('Sending request'));
            api('request_membership')
                .save({blog: blog._id})
                .then(
                    (data) => {
                        notify.pop();
                        notify.info(gettext('Request sent'));
                    },
                    (data) => {
                        notify.pop();
                        let message = gettext('Something went wrong, plase try again later!');

                        if (data.data._message === 'A request has already been sent') {
                            message = gettext('A request has already been sent');
                        }
                        notify.error(message, 5000);
                    }
                );
            $scope.closeAccessRequest();
        } else {
            notify.pop();
            notify.error(gettext('You are already member of this blog\'s team'));
        }
    };

    $scope.switchTab = function(newTab) {
        $scope.creationStep = newTab;
    };

    $scope.handleKeyDown = function(event, action) {
        // prevent form submission and editor 'artifact'
        if (event.keyCode === 13) {
            event.preventDefault();
            switch (action) {
            case 'goToTeamTab':
                // We need at least a valid title from the first tab
                if ($scope.newBlog.title) {
                    $scope.switchTab('Team');
                }
                break;
            }
        }
    };

    $scope.addMember = function(user) {
        $scope.blogMembers.push(user);
    };

    $scope.removeMember = function(user) {
        $scope.blogMembers.splice($scope.blogMembers.indexOf(user), 1);
    };

    $scope.removeImage = function() {
        modal.confirm(gettext('Are you sure you want to remove the blog image?')).then(() => {
            $scope.preview.url = '';
            $scope.progress.width = 0;
        });
    };

    $scope.hasReachedMembersLimit = function() {
        if (!config.assignableUsers.hasOwnProperty(config.subscriptionLevel)) {
            return false;
        }

        return $scope.blogMembers.length >= config.assignableUsers[config.subscriptionLevel];
    };

    // Set grid or list view
    $scope.setBlogsView = function(blogsView) {
        if (typeof blogsView !== 'undefined') {
            $scope.blogsView = blogsView;
            localStorage.setItem('blogsView', blogsView);
        } else if (typeof localStorage.getItem('blogsView') === 'undefined'
            || localStorage.getItem('blogsView') === null) {
            $scope.blogsView = 'grid';
        } else {
            $scope.blogsView = localStorage.getItem('blogsView');
        }
    };
    $scope.setBlogsView();

    function getCriteria() {
        const params = $location.search();
        const criteria = {
            max_results: $scope.maxResults,
            embedded: {original_creator: 1},
            sort: '[("versioncreated", -1)]',
            source: {
                query: {filtered: {filter: {term: {blog_status: $scope.activeState.code}}}},
            },
        };

        if (params.q) {
            criteria.source.query.filtered.query = {
                query_string: {
                    query: '*' + params.q + '*',
                    fields: ['title', 'description'],
                },
            };
        }
        if (params.page) {
            criteria.page = parseInt(params.page, 10);
        }
        return criteria;
    }

    function fetchBlogs() {
        $scope.blogsLoading = true;
        api.blogs.query(getCriteria(), false).then((blogs) => {
            $scope.blogs = blogs;
            $scope.blogsLoading = false;
        });
    }
    // initialize bloglist embed code.
    fetchBloglistEmbed();
    // initialize blogs list
    fetchBlogs();
    // fetch when maxResults is updated from the searchbar-directive
    $scope.$watch('maxResults', fetchBlogs);
    // fetch when criteria are updated from url (searchbar-directive)
    $scope.$on('$routeUpdate', fetchBlogs);
    // Reload bloglist on membership's approval
    $scope.$on('blogs', fetchBlogs);
}
<commit_msg>LBSD-2266 - Merge pull request #1230 from liveblog/fix/dashboard-paging<commit_after>BlogListController.$inject = [
    '$scope',
    '$location',
    '$http',
    'api',
    'gettext',
    'upload',
    'isArchivedFilterSelected',
    '$q',
    'blogSecurityService',
    'notify',
    'config',
    'urls',
    'moment',
    'modal',
    'blogService',
];

export default function BlogListController(
    $scope,
    $location,
    $http,
    api,
    gettext,
    upload,
    isArchivedFilterSelected,
    $q,
    blogSecurityService,
    notify,
    config,
    urls,
    moment,
    modal,
    blogService
) {
    $scope.maxResults = 25;
    $scope.states = [
        {name: 'active', code: 'open', text: gettext('Active blogs')},
        {name: 'archived', code: 'closed', text: gettext('Archived blogs')},
    ];
    $scope.activeState = isArchivedFilterSelected ? $scope.states[1] : $scope.states[0];
    $scope.creationStep = 'Details';
    $scope.requestAccessMessage = gettext('Click to request access');
    $scope.blogMembers = [];
    $scope.changeState = function(state) {
        $scope.activeState = state;
        $location.path('/liveblog/' + state.name);
        fetchBlogs();
    };
    $scope.modalActive = false;
    $scope.bulkActions = 0;

    $scope.mailto = 'mailto:upgrade@liveblog.pro?subject=' +
        encodeURIComponent(location.hostname) +
        ' ' +
        config.subscriptionLevel;

    function clearCreateBlogForm() {
        $scope.preview = {};
        $scope.progress = {width: 0};
        $scope.newBlog = {
            title: '',
            description: '',
        };
        $scope.newBlogError = '';
        $scope.creationStep = 'Details';
        $scope.blogMembers = [];
    }
    clearCreateBlogForm();
    $scope.isAdmin = blogSecurityService.isAdmin;
    $scope.isUserAllowedToCreateABlog = blogSecurityService.canCreateABlog;
    $scope.isUserAllowedToOpenBlog = blogSecurityService.canAccessBlog;
    // blog list embed code.
    function fetchBloglistEmbed() {
        const criteria = {source: {
            query: {filtered: {filter: {term: {key: 'blogslist'}}}},
        }};

        api.blogslist.query(criteria, false).then((embed) => {
            let url;

            if (embed._items.length) {
                url = embed._items[0].value;
            } else if (config.debug) {
                url = 'http://localhost:5000/blogslist_embed';
            }
            if (url) {
                $scope.bloglistEmbed = '';
            }
        });
    }

    function bulkDelete(blog) {
        api.blogs.remove(angular.copy(blog)).then((message) => {
            notify.pop();
            notify.info(gettext('Blog removed'));
        }, () => {
            notify.pop();
            notify.error(gettext('Something went wrong'));
        });
    }

    $scope.askRemoveBlog = function() {
        modal.confirm(gettext('Are you sure you want to delete the blog(s)?'))
            .then(() => {
                var selectedBlogs = [];

                angular.forEach($scope.blogs._items, (blog) => {
                    if (blog.selected) {
                        bulkDelete(blog);
                    }
                });

                $scope.blogs._items = $scope.blogs._items.filter((el) => selectedBlogs.indexOf(el) < 0);
            });
    };

    $scope.cancelEmbed = function() {
        $scope.embedModal = false;
    };
    $scope.openEmbed = function() {
        fetchBloglistEmbed();
        $scope.embedModal = true;
    };

    $scope.blogSelect = function($event, isSelected) {
        $event.stopPropagation();
        if (isSelected) {
            $scope.bulkActions += 1;
        } else {
            $scope.bulkActions -= 1;
        }
    };

    $scope.bulkActionCancel = () => {
        angular.forEach($scope.blogs._items, (blog) => {
            blog.selected = false;
        });
        $scope.bulkActions = 0;
    };

    $scope.bulkAction = function(activeState) {
        let selectedBlogs = [];

        angular.forEach($scope.blogs._items, (blog) => {
            if (blog.selected) {
                selectedBlogs.push(blog);
                const deferred = $q.defer();

                const changedBlog = {
                    blog_status: activeState.name == 'active' ? 'closed' : 'open',
                };

                let newBlog = angular.copy(blog);

                angular.extend(newBlog, changedBlog);
                delete newBlog._latest_version;
                delete newBlog._current_version;
                delete newBlog._version;
                delete newBlog.marked_for_not_publication;
                delete newBlog._type;
                delete newBlog.selected;
                delete newBlog.firstcreated;
                newBlog.original_creator = blog.original_creator._id;
                blogService.update(blog, newBlog).then((blog) => {
                    notify.pop();
                    if (blog.blog_status == 'closed') {
                        notify.info(gettext('Blog(s) moved to archived'));
                    } else {
                        notify.info(gettext('Blog(s) is actived now'));
                    }
                    deferred.resolve();
                    $scope.bulkActions = 0;
                });
                return deferred.promise;
            }
        });

        $scope.blogs._items = $scope.blogs._items.filter((el) => selectedBlogs.indexOf(el) < 0);
    };

    $scope.cancelCreate = function() {
        clearCreateBlogForm();
        $scope.newBlogModalActive = false;
    };

    $scope.cancelUpgrade = function() {
        $scope.embedUpgrade = false;
    };

    $scope.openNewBlog = function() {
        blogSecurityService
            .showUpgradeModal()
            .then((showUpgradeModal) => {
                if (showUpgradeModal) {
                    $scope.embedUpgrade = true;
                } else {
                    $scope.newBlogModalActive = true;
                }
            });
    };

    $scope.creationInProcess = false;

    $scope.createBlog = function() {
        $scope.creationInProcess = true;

        const members = _.map($scope.blogMembers, (obj) => ({user: obj._id}));

        // Upload image only if we have a valid one chosen
        const promise = $scope.preview.url ? $scope.upload($scope.preview) : $q.when();

        return promise.then(() => api.blogs
            .save({
                title: $scope.newBlog.title,
                description: $scope.newBlog.description,
                picture_url: $scope.newBlog.picture_url,
                picture: $scope.newBlog.picture,
                picture_renditions: $scope.newBlog.picture_renditions,
                members: members,
            })
            .then((blog) => {
                $scope.creationInProcess = false;
                $scope.edit(blog);
            }, (error) => {
                $scope.creationInProcess = false;
                // Error handler
                $scope.newBlogError = gettext('Something went wrong. Please try again later');
            }));
    };

    $scope.upload = function(config) {
        const form = {};

        if (config.img) {
            form.media = config.img;
        } else if (config.url) {
            form.URL = config.url;
        }

        if (form.hasOwnProperty('media') || form.hasOwnProperty('url')) {
            // return a promise of upload which will call the success/error callback
            return urls.resource('archive').then((uploadUrl) => upload.start({
                method: 'POST',
                url: uploadUrl,
                data: form,
            })
                .then((response) => {
                    if (response.data._status === 'ERR') {
                        return;
                    }
                    var pictureUrl = response.data.renditions.viewImage.href;

                    $scope.newBlog.picture_url = pictureUrl;
                    $scope.newBlog.picture = response.data._id;
                    $scope.newBlog.picture_renditions = response.data.renditions;
                }, (error) => {
                    notify.error(
                        error.statusText !== '' ? error.statusText : gettext('There was a problem with your upload')
                    );
                }, (progress) => {
                    $scope.progress.width = Math.round(progress.loaded / progress.total * 100.0);
                }));
        }
    };

    $scope.remove = function(blog) {
        _.remove($scope.blogs._items, blog);
    };

    $scope.edit = function(blog) {
        $location.path('/liveblog/edit/' + blog._id);
    };

    $scope.openAccessRequest = function(blog) {
        $scope.accessRequestedTo = blog;
        $scope.showBlogAccessModal = true;

        if (config.subscriptionLevel
        && ['solo', 'team'].indexOf(config.subscriptionLevel) !== -1) {
            $scope.checkAccessRequestLimit(blog);
        } else {
            $scope.allowAccessRequest = true;
        }
    };

    $scope.closeAccessRequest = function() {
        $scope.accessRequestedTo = false;
        $scope.showBlogAccessModal = false;
    };

    $scope.checkAccessRequestLimit = function(blog) {
        $scope.allowAccessRequest = false;

        const theoricalMembers = [];

        if (blog.members) {
            blog.members.forEach((member) => {
                if (theoricalMembers.indexOf(member.user) === -1) {
                    theoricalMembers.push(member.user);
                }
            });
        }

        $http({
            url: config.server.url + '/blogs/' + blog._id + '/request_membership',
            method: 'GET',
            headers: {
                'Content-Type': 'application/json;charset=utf-8',
            },
        })
            .then((response) => {
                if (response.data._items.length > 0) {
                    response.data._items.forEach((item) => {
                        if (theoricalMembers.indexOf(item._id) === -1) {
                            theoricalMembers.push(item._id);
                        }
                    });
                }

                if (theoricalMembers.length < config.assignableUsers[config.subscriptionLevel]) {
                    $scope.allowAccessRequest = true;
                }
            });
    };

    $scope.requestAccess = function(blog) {
        let showRequestDialog = true;

        // Check to see if the current user hasn't been accepted during this session (before refreshing)
        if (blog.members) {
            _.each(blog.members, (member) => {
                if (member.user === $scope.$root.currentUser._id) {
                    showRequestDialog = false;
                }
            });
        }

        if (showRequestDialog) {
            notify.info(gettext('Sending request'));
            api('request_membership')
                .save({blog: blog._id})
                .then(
                    (data) => {
                        notify.pop();
                        notify.info(gettext('Request sent'));
                    },
                    (data) => {
                        notify.pop();
                        let message = gettext('Something went wrong, plase try again later!');

                        if (data.data._message === 'A request has already been sent') {
                            message = gettext('A request has already been sent');
                        }
                        notify.error(message, 5000);
                    }
                );
            $scope.closeAccessRequest();
        } else {
            notify.pop();
            notify.error(gettext('You are already member of this blog\'s team'));
        }
    };

    $scope.switchTab = function(newTab) {
        $scope.creationStep = newTab;
    };

    $scope.handleKeyDown = function(event, action) {
        // prevent form submission and editor 'artifact'
        if (event.keyCode === 13) {
            event.preventDefault();
            switch (action) {
            case 'goToTeamTab':
                // We need at least a valid title from the first tab
                if ($scope.newBlog.title) {
                    $scope.switchTab('Team');
                }
                break;
            }
        }
    };

    $scope.addMember = function(user) {
        $scope.blogMembers.push(user);
    };

    $scope.removeMember = function(user) {
        $scope.blogMembers.splice($scope.blogMembers.indexOf(user), 1);
    };

    $scope.removeImage = function() {
        modal.confirm(gettext('Are you sure you want to remove the blog image?')).then(() => {
            $scope.preview.url = '';
            $scope.progress.width = 0;
        });
    };

    $scope.hasReachedMembersLimit = function() {
        if (!config.assignableUsers.hasOwnProperty(config.subscriptionLevel)) {
            return false;
        }

        return $scope.blogMembers.length >= config.assignableUsers[config.subscriptionLevel];
    };

    // Set grid or list view
    $scope.setBlogsView = function(blogsView) {
        if (typeof blogsView !== 'undefined') {
            $scope.blogsView = blogsView;
            localStorage.setItem('blogsView', blogsView);
        } else if (typeof localStorage.getItem('blogsView') === 'undefined'
            || localStorage.getItem('blogsView') === null) {
            $scope.blogsView = 'grid';
        } else {
            $scope.blogsView = localStorage.getItem('blogsView');
        }
    };
    $scope.setBlogsView();

    function getCriteria() {
        const params = $location.search();
        const criteria = {
            max_results: params.max_results,
            embedded: {original_creator: 1},
            sort: '[("versioncreated", -1)]',
            source: {
                query: {filtered: {filter: {term: {blog_status: $scope.activeState.code}}}},
            },
        };

        if (params.q) {
            criteria.source.query.filtered.query = {
                query_string: {
                    query: '*' + params.q + '*',
                    fields: ['title', 'description'],
                },
            };
        }
        if (params.page) {
            criteria.page = parseInt(params.page, 10);
        }
        return criteria;
    }

    function fetchBlogs() {
        $scope.blogsLoading = true;
        api.blogs.query(getCriteria(), false).then((blogs) => {
            $scope.blogs = blogs;
            $scope.blogsLoading = false;
        });
    }
    // initialize bloglist embed code.
    fetchBloglistEmbed();
    // initialize blogs list
    fetchBlogs();
    // fetch when maxResults is updated from the searchbar-directive
    $scope.$watch('maxResults', fetchBlogs);
    // fetch when criteria are updated from url (searchbar-directive)
    $scope.$on('$routeUpdate', fetchBlogs);
    // Reload bloglist on membership's approval
    $scope.$on('blogs', fetchBlogs);
}
<|endoftext|>


<commit_before>BlogListController.$inject = [
    '$scope',
    '$location',
    '$http',
    'api',
    'gettext',
    'upload',
    'isArchivedFilterSelected',
    '$q',
    'blogSecurityService',
    'notify',
    'config',
    'urls',
    'moment',
    'modal',
    'blogService',
];

export default function BlogListController(
    $scope,
    $location,
    $http,
    api,
    gettext,
    upload,
    isArchivedFilterSelected,
    $q,
    blogSecurityService,
    notify,
    config,
    urls,
    moment,
    modal,
    blogService
) {
    $scope.maxResults = 25;
    $scope.states = [
        {name: 'active', code: 'open', text: gettext('Active blogs')},
        {name: 'archived', code: 'closed', text: gettext('Archived blogs')},
    ];
    $scope.activeState = isArchivedFilterSelected ? $scope.states[1] : $scope.states[0];
    $scope.creationStep = 'Details';
    $scope.requestAccessMessage = gettext('Click to request access');
    $scope.blogMembers = [];
    $scope.changeState = function(state) {
        $scope.activeState = state;
        $location.path('/liveblog/' + state.name);
        fetchBlogs();
    };
    $scope.modalActive = false;
    $scope.bulkActions = 0;

    $scope.mailto = 'mailto:upgrade@liveblog.pro?subject=' +
        encodeURIComponent(location.hostname) +
        ' ' +
        config.subscriptionLevel;

    function clearCreateBlogForm() {
        $scope.preview = {};
        $scope.progress = {width: 0};
        $scope.newBlog = {
            title: '',
            description: '',
        };
        $scope.newBlogError = '';
        $scope.creationStep = 'Details';
        $scope.blogMembers = [];
    }
    clearCreateBlogForm();
    $scope.isAdmin = blogSecurityService.isAdmin;
    $scope.isUserAllowedToCreateABlog = blogSecurityService.canCreateABlog;
    $scope.isUserAllowedToOpenBlog = blogSecurityService.canAccessBlog;
    // blog list embed code.
    function fetchBloglistEmbed() {
        const criteria = {source: {
            query: {filtered: {filter: {term: {key: 'blogslist'}}}},
        }};

        api.blogslist.query(criteria, false).then((embed) => {
            let url;

            if (embed._items.length) {
                url = embed._items[0].value;
            } else if (config.debug) {
                url = 'http://localhost:5000/blogslist_embed';
            }
            if (url) {
                $scope.bloglistEmbed = '';
            }
        });
    }

    function bulkDelete(blog) {
        api.blogs.remove(angular.copy(blog)).then((message) => {
            notify.pop();
            notify.info(gettext('Blog removed'));
        }, () => {
            notify.pop();
            notify.error(gettext('Something went wrong'));
        });
    }

    $scope.askRemoveBlog = function() {
        modal.confirm(gettext('Are you sure you want to delete the blog(s)?'))
            .then(() => {
                var selectedBlogs = [];

                angular.forEach($scope.blogs._items, (blog) => {
                    if (blog.selected) {
                        bulkDelete(blog);
                    }
                });

                $scope.blogs._items = $scope.blogs._items.filter((el) => selectedBlogs.indexOf(el) < 0);
            });
    };

    $scope.cancelEmbed = function() {
        $scope.embedModal = false;
    };
    $scope.openEmbed = function() {
        fetchBloglistEmbed();
        $scope.embedModal = true;
    };

    $scope.blogSelect = function($event, isSelected) {
        $event.stopPropagation();
        if (isSelected) {
            $scope.bulkActions += 1;
        } else {
            $scope.bulkActions -= 1;
        }
    };

    $scope.bulkActionCancel = () => {
        angular.forEach($scope.blogs._items, (blog) => {
            blog.selected = false;
        });
        $scope.bulkActions = 0;
    };

    $scope.bulkAction = function(activeState) {
        let selectedBlogs = [];

        angular.forEach($scope.blogs._items, (blog) => {
            if (blog.selected) {
                selectedBlogs.push(blog);
                const deferred = $q.defer();

                const changedBlog = {
                    blog_status: activeState.name == 'active' ? 'closed' : 'open',
                };

                let newBlog = angular.copy(blog);

                angular.extend(newBlog, changedBlog);
                delete newBlog._latest_version;
                delete newBlog._current_version;
                delete newBlog._version;
                delete newBlog.marked_for_not_publication;
                delete newBlog._type;
                delete newBlog.selected;
                delete newBlog.firstcreated;
                newBlog.original_creator = blog.original_creator._id;
                blogService.update(blog, newBlog).then((blog) => {
                    notify.pop();
                    if (blog.blog_status == 'closed') {
                        notify.info(gettext('Blog(s) moved to archived'));
                    } else {
                        notify.info(gettext('Blog(s) is actived now'));
                    }
                    deferred.resolve();
                    $scope.bulkActions = 0;
                });
                return deferred.promise;
            }
        });

        $scope.blogs._items = $scope.blogs._items.filter((el) => selectedBlogs.indexOf(el) < 0);
    };

    $scope.cancelCreate = function() {
        clearCreateBlogForm();
        $scope.newBlogModalActive = false;
    };

    $scope.cancelUpgrade = function() {
        $scope.embedUpgrade = false;
    };

    $scope.openNewBlog = function() {
        blogSecurityService
            .showUpgradeModal()
            .then((showUpgradeModal) => {
                if (showUpgradeModal) {
                    $scope.embedUpgrade = true;
                } else {
                    $scope.newBlogModalActive = true;
                }
            });
    };

    $scope.creationInProcess = false;

    $scope.createBlog = function() {
        $scope.creationInProcess = true;

        const members = _.map($scope.blogMembers, (obj) => ({user: obj._id}));

        // Upload image only if we have a valid one chosen
        const promise = $scope.preview.url ? $scope.upload($scope.preview) : $q.when();

        return promise.then(() => api.blogs
            .save({
                title: $scope.newBlog.title,
                description: $scope.newBlog.description,
                picture_url: $scope.newBlog.picture_url,
                picture: $scope.newBlog.picture,
                picture_renditions: $scope.newBlog.picture_renditions,
                members: members,
            })
            .then((blog) => {
                $scope.creationInProcess = false;
                $scope.edit(blog);
            }, (error) => {
                $scope.creationInProcess = false;
                // Error handler
                $scope.newBlogError = gettext('Something went wrong. Please try again later');
            }));
    };

    $scope.upload = function(config) {
        const form = {};

        if (config.img) {
            form.media = config.img;
        } else if (config.url) {
            form.URL = config.url;
        }

        if (form.hasOwnProperty('media') || form.hasOwnProperty('url')) {
            // return a promise of upload which will call the success/error callback
            return urls.resource('archive').then((uploadUrl) => upload.start({
                method: 'POST',
                url: uploadUrl,
                data: form,
            })
                .then((response) => {
                    if (response.data._status === 'ERR') {
                        return;
                    }
                    var pictureUrl = response.data.renditions.viewImage.href;

                    $scope.newBlog.picture_url = pictureUrl;
                    $scope.newBlog.picture = response.data._id;
                    $scope.newBlog.picture_renditions = response.data.renditions;
                }, (error) => {
                    notify.error(
                        error.statusText !== '' ? error.statusText : gettext('There was a problem with your upload')
                    );
                }, (progress) => {
                    $scope.progress.width = Math.round(progress.loaded / progress.total * 100.0);
                }));
        }
    };

    $scope.remove = function(blog) {
        _.remove($scope.blogs._items, blog);
    };

    $scope.edit = function(blog) {
        $location.path('/liveblog/edit/' + blog._id);
    };

    $scope.openAccessRequest = function(blog) {
        $scope.accessRequestedTo = blog;
        $scope.showBlogAccessModal = true;

        if (config.subscriptionLevel
        && ['solo', 'team'].indexOf(config.subscriptionLevel) !== -1) {
            $scope.checkAccessRequestLimit(blog);
        } else {
            $scope.allowAccessRequest = true;
        }
    };

    $scope.closeAccessRequest = function() {
        $scope.accessRequestedTo = false;
        $scope.showBlogAccessModal = false;
    };

    $scope.checkAccessRequestLimit = function(blog) {
        $scope.allowAccessRequest = false;

        const theoricalMembers = [];

        if (blog.members) {
            blog.members.forEach((member) => {
                if (theoricalMembers.indexOf(member.user) === -1) {
                    theoricalMembers.push(member.user);
                }
            });
        }

        $http({
            url: config.server.url + '/blogs/' + blog._id + '/request_membership',
            method: 'GET',
            headers: {
                'Content-Type': 'application/json;charset=utf-8',
            },
        })
            .then((response) => {
                if (response.data._items.length > 0) {
                    response.data._items.forEach((item) => {
                        if (theoricalMembers.indexOf(item._id) === -1) {
                            theoricalMembers.push(item._id);
                        }
                    });
                }

                if (theoricalMembers.length < config.assignableUsers[config.subscriptionLevel]) {
                    $scope.allowAccessRequest = true;
                }
            });
    };

    $scope.requestAccess = function(blog) {
        let showRequestDialog = true;

        // Check to see if the current user hasn't been accepted during this session (before refreshing)
        if (blog.members) {
            _.each(blog.members, (member) => {
                if (member.user === $scope.$root.currentUser._id) {
                    showRequestDialog = false;
                }
            });
        }

        if (showRequestDialog) {
            notify.info(gettext('Sending request'));
            api('request_membership')
                .save({blog: blog._id})
                .then(
                    (data) => {
                        notify.pop();
                        notify.info(gettext('Request sent'));
                    },
                    (data) => {
                        notify.pop();
                        let message = gettext('Something went wrong, plase try again later!');

                        if (data.data._message === 'A request has already been sent') {
                            message = gettext('A request has already been sent');
                        }
                        notify.error(message, 5000);
                    }
                );
            $scope.closeAccessRequest();
        } else {
            notify.pop();
            notify.error(gettext('You are already member of this blog\'s team'));
        }
    };

    $scope.switchTab = function(newTab) {
        $scope.creationStep = newTab;
    };

    $scope.handleKeyDown = function(event, action) {
        // prevent form submission and editor 'artifact'
        if (event.keyCode === 13) {
            event.preventDefault();
            switch (action) {
            case 'goToTeamTab':
                // We need at least a valid title from the first tab
                if ($scope.newBlog.title) {
                    $scope.switchTab('Team');
                }
                break;
            }
        }
    };

    $scope.addMember = function(user) {
        $scope.blogMembers.push(user);
    };

    $scope.removeMember = function(user) {
        $scope.blogMembers.splice($scope.blogMembers.indexOf(user), 1);
    };

    $scope.removeImage = function() {
        modal.confirm(gettext('Are you sure you want to remove the blog image?')).then(() => {
            $scope.preview.url = '';
            $scope.progress.width = 0;
        });
    };

    $scope.hasReachedMembersLimit = function() {
        if (!config.assignableUsers.hasOwnProperty(config.subscriptionLevel)) {
            return false;
        }

        return $scope.blogMembers.length >= config.assignableUsers[config.subscriptionLevel];
    };

    // Set grid or list view
    $scope.setBlogsView = function(blogsView) {
        if (typeof blogsView !== 'undefined') {
            $scope.blogsView = blogsView;
            localStorage.setItem('blogsView', blogsView);
        } else if (typeof localStorage.getItem('blogsView') === 'undefined'
            || localStorage.getItem('blogsView') === null) {
            $scope.blogsView = 'grid';
        } else {
            $scope.blogsView = localStorage.getItem('blogsView');
        }
    };
    $scope.setBlogsView();

    function getCriteria() {
        const params = $location.search();
        const criteria = {
            max_results: $scope.maxResults,
            embedded: {original_creator: 1},
            sort: '[("versioncreated", -1)]',
            source: {
                query: {filtered: {filter: {term: {blog_status: $scope.activeState.code}}}},
            },
        };

        if (params.q) {
            criteria.source.query.filtered.query = {
                query_string: {
                    query: '*' + params.q + '*',
                    fields: ['title', 'description'],
                },
            };
        }
        if (params.page) {
            criteria.page = parseInt(params.page, 10);
        }
        return criteria;
    }

    function fetchBlogs() {
        $scope.blogsLoading = true;
        api.blogs.query(getCriteria(), false).then((blogs) => {
            $scope.blogs = blogs;
            $scope.blogsLoading = false;
        });
    }
    // initialize bloglist embed code.
    fetchBloglistEmbed();
    // initialize blogs list
    fetchBlogs();
    // fetch when maxResults is updated from the searchbar-directive
    $scope.$watch('maxResults', fetchBlogs);
    // fetch when criteria are updated from url (searchbar-directive)
    $scope.$on('$routeUpdate', fetchBlogs);
    // Reload bloglist on membership's approval
    $scope.$on('blogs', fetchBlogs);
}
<commit_msg>fixed: the paging on the dashboard (active/archived blogs)<commit_after>BlogListController.$inject = [
    '$scope',
    '$location',
    '$http',
    'api',
    'gettext',
    'upload',
    'isArchivedFilterSelected',
    '$q',
    'blogSecurityService',
    'notify',
    'config',
    'urls',
    'moment',
    'modal',
    'blogService',
];

export default function BlogListController(
    $scope,
    $location,
    $http,
    api,
    gettext,
    upload,
    isArchivedFilterSelected,
    $q,
    blogSecurityService,
    notify,
    config,
    urls,
    moment,
    modal,
    blogService
) {
    $scope.maxResults = 25;
    $scope.states = [
        {name: 'active', code: 'open', text: gettext('Active blogs')},
        {name: 'archived', code: 'closed', text: gettext('Archived blogs')},
    ];
    $scope.activeState = isArchivedFilterSelected ? $scope.states[1] : $scope.states[0];
    $scope.creationStep = 'Details';
    $scope.requestAccessMessage = gettext('Click to request access');
    $scope.blogMembers = [];
    $scope.changeState = function(state) {
        $scope.activeState = state;
        $location.path('/liveblog/' + state.name);
        fetchBlogs();
    };
    $scope.modalActive = false;
    $scope.bulkActions = 0;

    $scope.mailto = 'mailto:upgrade@liveblog.pro?subject=' +
        encodeURIComponent(location.hostname) +
        ' ' +
        config.subscriptionLevel;

    function clearCreateBlogForm() {
        $scope.preview = {};
        $scope.progress = {width: 0};
        $scope.newBlog = {
            title: '',
            description: '',
        };
        $scope.newBlogError = '';
        $scope.creationStep = 'Details';
        $scope.blogMembers = [];
    }
    clearCreateBlogForm();
    $scope.isAdmin = blogSecurityService.isAdmin;
    $scope.isUserAllowedToCreateABlog = blogSecurityService.canCreateABlog;
    $scope.isUserAllowedToOpenBlog = blogSecurityService.canAccessBlog;
    // blog list embed code.
    function fetchBloglistEmbed() {
        const criteria = {source: {
            query: {filtered: {filter: {term: {key: 'blogslist'}}}},
        }};

        api.blogslist.query(criteria, false).then((embed) => {
            let url;

            if (embed._items.length) {
                url = embed._items[0].value;
            } else if (config.debug) {
                url = 'http://localhost:5000/blogslist_embed';
            }
            if (url) {
                $scope.bloglistEmbed = '';
            }
        });
    }

    function bulkDelete(blog) {
        api.blogs.remove(angular.copy(blog)).then((message) => {
            notify.pop();
            notify.info(gettext('Blog removed'));
        }, () => {
            notify.pop();
            notify.error(gettext('Something went wrong'));
        });
    }

    $scope.askRemoveBlog = function() {
        modal.confirm(gettext('Are you sure you want to delete the blog(s)?'))
            .then(() => {
                var selectedBlogs = [];

                angular.forEach($scope.blogs._items, (blog) => {
                    if (blog.selected) {
                        bulkDelete(blog);
                    }
                });

                $scope.blogs._items = $scope.blogs._items.filter((el) => selectedBlogs.indexOf(el) < 0);
            });
    };

    $scope.cancelEmbed = function() {
        $scope.embedModal = false;
    };
    $scope.openEmbed = function() {
        fetchBloglistEmbed();
        $scope.embedModal = true;
    };

    $scope.blogSelect = function($event, isSelected) {
        $event.stopPropagation();
        if (isSelected) {
            $scope.bulkActions += 1;
        } else {
            $scope.bulkActions -= 1;
        }
    };

    $scope.bulkActionCancel = () => {
        angular.forEach($scope.blogs._items, (blog) => {
            blog.selected = false;
        });
        $scope.bulkActions = 0;
    };

    $scope.bulkAction = function(activeState) {
        let selectedBlogs = [];

        angular.forEach($scope.blogs._items, (blog) => {
            if (blog.selected) {
                selectedBlogs.push(blog);
                const deferred = $q.defer();

                const changedBlog = {
                    blog_status: activeState.name == 'active' ? 'closed' : 'open',
                };

                let newBlog = angular.copy(blog);

                angular.extend(newBlog, changedBlog);
                delete newBlog._latest_version;
                delete newBlog._current_version;
                delete newBlog._version;
                delete newBlog.marked_for_not_publication;
                delete newBlog._type;
                delete newBlog.selected;
                delete newBlog.firstcreated;
                newBlog.original_creator = blog.original_creator._id;
                blogService.update(blog, newBlog).then((blog) => {
                    notify.pop();
                    if (blog.blog_status == 'closed') {
                        notify.info(gettext('Blog(s) moved to archived'));
                    } else {
                        notify.info(gettext('Blog(s) is actived now'));
                    }
                    deferred.resolve();
                    $scope.bulkActions = 0;
                });
                return deferred.promise;
            }
        });

        $scope.blogs._items = $scope.blogs._items.filter((el) => selectedBlogs.indexOf(el) < 0);
    };

    $scope.cancelCreate = function() {
        clearCreateBlogForm();
        $scope.newBlogModalActive = false;
    };

    $scope.cancelUpgrade = function() {
        $scope.embedUpgrade = false;
    };

    $scope.openNewBlog = function() {
        blogSecurityService
            .showUpgradeModal()
            .then((showUpgradeModal) => {
                if (showUpgradeModal) {
                    $scope.embedUpgrade = true;
                } else {
                    $scope.newBlogModalActive = true;
                }
            });
    };

    $scope.creationInProcess = false;

    $scope.createBlog = function() {
        $scope.creationInProcess = true;

        const members = _.map($scope.blogMembers, (obj) => ({user: obj._id}));

        // Upload image only if we have a valid one chosen
        const promise = $scope.preview.url ? $scope.upload($scope.preview) : $q.when();

        return promise.then(() => api.blogs
            .save({
                title: $scope.newBlog.title,
                description: $scope.newBlog.description,
                picture_url: $scope.newBlog.picture_url,
                picture: $scope.newBlog.picture,
                picture_renditions: $scope.newBlog.picture_renditions,
                members: members,
            })
            .then((blog) => {
                $scope.creationInProcess = false;
                $scope.edit(blog);
            }, (error) => {
                $scope.creationInProcess = false;
                // Error handler
                $scope.newBlogError = gettext('Something went wrong. Please try again later');
            }));
    };

    $scope.upload = function(config) {
        const form = {};

        if (config.img) {
            form.media = config.img;
        } else if (config.url) {
            form.URL = config.url;
        }

        if (form.hasOwnProperty('media') || form.hasOwnProperty('url')) {
            // return a promise of upload which will call the success/error callback
            return urls.resource('archive').then((uploadUrl) => upload.start({
                method: 'POST',
                url: uploadUrl,
                data: form,
            })
                .then((response) => {
                    if (response.data._status === 'ERR') {
                        return;
                    }
                    var pictureUrl = response.data.renditions.viewImage.href;

                    $scope.newBlog.picture_url = pictureUrl;
                    $scope.newBlog.picture = response.data._id;
                    $scope.newBlog.picture_renditions = response.data.renditions;
                }, (error) => {
                    notify.error(
                        error.statusText !== '' ? error.statusText : gettext('There was a problem with your upload')
                    );
                }, (progress) => {
                    $scope.progress.width = Math.round(progress.loaded / progress.total * 100.0);
                }));
        }
    };

    $scope.remove = function(blog) {
        _.remove($scope.blogs._items, blog);
    };

    $scope.edit = function(blog) {
        $location.path('/liveblog/edit/' + blog._id);
    };

    $scope.openAccessRequest = function(blog) {
        $scope.accessRequestedTo = blog;
        $scope.showBlogAccessModal = true;

        if (config.subscriptionLevel
        && ['solo', 'team'].indexOf(config.subscriptionLevel) !== -1) {
            $scope.checkAccessRequestLimit(blog);
        } else {
            $scope.allowAccessRequest = true;
        }
    };

    $scope.closeAccessRequest = function() {
        $scope.accessRequestedTo = false;
        $scope.showBlogAccessModal = false;
    };

    $scope.checkAccessRequestLimit = function(blog) {
        $scope.allowAccessRequest = false;

        const theoricalMembers = [];

        if (blog.members) {
            blog.members.forEach((member) => {
                if (theoricalMembers.indexOf(member.user) === -1) {
                    theoricalMembers.push(member.user);
                }
            });
        }

        $http({
            url: config.server.url + '/blogs/' + blog._id + '/request_membership',
            method: 'GET',
            headers: {
                'Content-Type': 'application/json;charset=utf-8',
            },
        })
            .then((response) => {
                if (response.data._items.length > 0) {
                    response.data._items.forEach((item) => {
                        if (theoricalMembers.indexOf(item._id) === -1) {
                            theoricalMembers.push(item._id);
                        }
                    });
                }

                if (theoricalMembers.length < config.assignableUsers[config.subscriptionLevel]) {
                    $scope.allowAccessRequest = true;
                }
            });
    };

    $scope.requestAccess = function(blog) {
        let showRequestDialog = true;

        // Check to see if the current user hasn't been accepted during this session (before refreshing)
        if (blog.members) {
            _.each(blog.members, (member) => {
                if (member.user === $scope.$root.currentUser._id) {
                    showRequestDialog = false;
                }
            });
        }

        if (showRequestDialog) {
            notify.info(gettext('Sending request'));
            api('request_membership')
                .save({blog: blog._id})
                .then(
                    (data) => {
                        notify.pop();
                        notify.info(gettext('Request sent'));
                    },
                    (data) => {
                        notify.pop();
                        let message = gettext('Something went wrong, plase try again later!');

                        if (data.data._message === 'A request has already been sent') {
                            message = gettext('A request has already been sent');
                        }
                        notify.error(message, 5000);
                    }
                );
            $scope.closeAccessRequest();
        } else {
            notify.pop();
            notify.error(gettext('You are already member of this blog\'s team'));
        }
    };

    $scope.switchTab = function(newTab) {
        $scope.creationStep = newTab;
    };

    $scope.handleKeyDown = function(event, action) {
        // prevent form submission and editor 'artifact'
        if (event.keyCode === 13) {
            event.preventDefault();
            switch (action) {
            case 'goToTeamTab':
                // We need at least a valid title from the first tab
                if ($scope.newBlog.title) {
                    $scope.switchTab('Team');
                }
                break;
            }
        }
    };

    $scope.addMember = function(user) {
        $scope.blogMembers.push(user);
    };

    $scope.removeMember = function(user) {
        $scope.blogMembers.splice($scope.blogMembers.indexOf(user), 1);
    };

    $scope.removeImage = function() {
        modal.confirm(gettext('Are you sure you want to remove the blog image?')).then(() => {
            $scope.preview.url = '';
            $scope.progress.width = 0;
        });
    };

    $scope.hasReachedMembersLimit = function() {
        if (!config.assignableUsers.hasOwnProperty(config.subscriptionLevel)) {
            return false;
        }

        return $scope.blogMembers.length >= config.assignableUsers[config.subscriptionLevel];
    };

    // Set grid or list view
    $scope.setBlogsView = function(blogsView) {
        if (typeof blogsView !== 'undefined') {
            $scope.blogsView = blogsView;
            localStorage.setItem('blogsView', blogsView);
        } else if (typeof localStorage.getItem('blogsView') === 'undefined'
            || localStorage.getItem('blogsView') === null) {
            $scope.blogsView = 'grid';
        } else {
            $scope.blogsView = localStorage.getItem('blogsView');
        }
    };
    $scope.setBlogsView();

    function getCriteria() {
        const params = $location.search();
        const criteria = {
            max_results: params.max_results,
            embedded: {original_creator: 1},
            sort: '[("versioncreated", -1)]',
            source: {
                query: {filtered: {filter: {term: {blog_status: $scope.activeState.code}}}},
            },
        };

        if (params.q) {
            criteria.source.query.filtered.query = {
                query_string: {
                    query: '*' + params.q + '*',
                    fields: ['title', 'description'],
                },
            };
        }
        if (params.page) {
            criteria.page = parseInt(params.page, 10);
        }
        return criteria;
    }

    function fetchBlogs() {
        $scope.blogsLoading = true;
        api.blogs.query(getCriteria(), false).then((blogs) => {
            $scope.blogs = blogs;
            $scope.blogsLoading = false;
        });
    }
    // initialize bloglist embed code.
    fetchBloglistEmbed();
    // initialize blogs list
    fetchBlogs();
    // fetch when maxResults is updated from the searchbar-directive
    $scope.$watch('maxResults', fetchBlogs);
    // fetch when criteria are updated from url (searchbar-directive)
    $scope.$on('$routeUpdate', fetchBlogs);
    // Reload bloglist on membership's approval
    $scope.$on('blogs', fetchBlogs);
}
<|endoftext|>


<commit_before>(function() {

    // Percentage of users to display the survey for
    var percentage = 0.6,
        cookie_time = null,
        cookie_array = document.cookie.split(';'),
        i, cookie, time, site_time, link, data, query_string;

    for(i=0;i < cookie_array.length;i++) {
        cookie = cookie_array[i];
        cookie = cookie.replace(/^\s+/, '')
        if (cookie.indexOf('ms_srv_t=') == 0) {
            // Cookie for time...
            cookie_time = cookie.substring('ms_srv_t='.length,cookie.length);
        }
        if (cookie.indexOf('ms_srv_r=') == 0) {
            // Cookie for referrer...
            cookie_referrer = cookie.substring('ms_srv_r='.length,cookie.length);
        }
    }

    if (cookie_time == null) {
        // No cookie!
        if (Math.random() < percentage) {
            // Chosen to survey
            // Set the cookie to current timestamp
            time = Math.round(new Date().getTime() / 1000);
            document.cookie = 'ms_srv_t='+time+'; path=/';
            document.cookie = 'ms_srv_r='+document.referrer+'; path=/';
            cookie_time = time;
            cookie_referrer = document.referrer;

        } else {
            // Not chosen to survey
            // Set cookie to X
            document.cookie = 'ms_srv_t=X; path=/';
            cookie_time = 'X'
        }
    }

    // Only bother to do this if the cookie is set and the link exists
    if (cookie_time != 'X' && document.getElementById('ms_srv_wrapper')) {

        // Find the time on site thus far
        site_time = Math.round(new Date().getTime() / 1000) - cookie_time;

        // Find the URL on the page
        link = document.getElementById('ms_srv_link');

        data = {
            'ms_time': site_time,
            'ms_referrer': cookie_referrer || null
        }

        // Assemble the query string
        query_string = [];
        for (d in data) {
           query_string.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
        }

        // Append query string to the URL
        link.href = link.href + '?' + query_string.join('&');

        // Show the survey link element
        document.getElementById('ms_srv_wrapper').style.display = '';

        // Bind a click event to the link so we can de-survey the user
        link.onclick = function() { document.cookie = 'ms_srv_t=X; path=/'; }

    }

})();
<commit_msg>Change Mzalendo surveyed users percentage to 100%<commit_after>(function() {

    // Percentage of users to display the survey for
    var percentage = 1,
        cookie_time = null,
        cookie_array = document.cookie.split(';'),
        i, cookie, time, site_time, link, data, query_string;

    for(i=0;i < cookie_array.length;i++) {
        cookie = cookie_array[i];
        cookie = cookie.replace(/^\s+/, '')
        if (cookie.indexOf('ms_srv_t=') == 0) {
            // Cookie for time...
            cookie_time = cookie.substring('ms_srv_t='.length,cookie.length);
        }
        if (cookie.indexOf('ms_srv_r=') == 0) {
            // Cookie for referrer...
            cookie_referrer = cookie.substring('ms_srv_r='.length,cookie.length);
        }
    }

    if (cookie_time == null) {
        // No cookie!
        if (Math.random() < percentage) {
            // Chosen to survey
            // Set the cookie to current timestamp
            time = Math.round(new Date().getTime() / 1000);
            document.cookie = 'ms_srv_t='+time+'; path=/';
            document.cookie = 'ms_srv_r='+document.referrer+'; path=/';
            cookie_time = time;
            cookie_referrer = document.referrer;

        } else {
            // Not chosen to survey
            // Set cookie to X
            document.cookie = 'ms_srv_t=X; path=/';
            cookie_time = 'X'
        }
    }

    // Only bother to do this if the cookie is set and the link exists
    if (cookie_time != 'X' && document.getElementById('ms_srv_wrapper')) {

        // Find the time on site thus far
        site_time = Math.round(new Date().getTime() / 1000) - cookie_time;

        // Find the URL on the page
        link = document.getElementById('ms_srv_link');

        data = {
            'ms_time': site_time,
            'ms_referrer': cookie_referrer || null
        }

        // Assemble the query string
        query_string = [];
        for (d in data) {
           query_string.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
        }

        // Append query string to the URL
        link.href = link.href + '?' + query_string.join('&');

        // Show the survey link element
        document.getElementById('ms_srv_wrapper').style.display = '';

        // Bind a click event to the link so we can de-survey the user
        link.onclick = function() { document.cookie = 'ms_srv_t=X; path=/'; }

    }

})();
<|endoftext|>