<commit_before>'use strict';

let db = require('../db');
let shortid = require('shortid');
let util = require('util');

let geoip = require('geoip-ultralight');
let campaigns = require('./campaigns');
let subscriptions = require('./subscriptions');
let lists = require('./lists');

let log = require('npmlog');
let urllib = require('url');
let he = require('he');

module.exports.resolve = (linkCid, callback) => {
    db.getConnection((err, connection) => {
        if (err) {
            return callback(err);
        }
        let query = 'SELECT id, url FROM links WHERE `cid`=? LIMIT 1';
        connection.query(query, [linkCid], (err, rows) => {
            connection.release();
            if (err) {
                return callback(err);
            }

            if (rows && rows.length) {
                return callback(null, rows[0].id, rows[0].url);
            }

            return callback(null, false);
        });
    });
};

module.exports.countClick = (remoteIp, campaignCid, listCid, subscriptionCid, linkId, callback) => {
    getSubscriptionData(campaignCid, listCid, subscriptionCid, (err, data) => {
        if (err) {
            return callback(err);
        }
        if(!data){
            return callback(null, false);
        }
        db.getConnection((err, connection) => {
            if (err) {
                return callback(err);
            }

            connection.beginTransaction(err => {
                if (err) {
                    connection.release();
                    return callback(err);
                }

                let country = geoip.lookupCountry(remoteIp) || null;

                let query = 'INSERT INTO `campaign_tracker__' + data.campaign.id + '` (`list`, `subscriber`, `link`, `ip`, `country`) VALUES (?,?,?,?,?) ON DUPLICATE KEY UPDATE `count`=`count`+1';
                connection.query(query, [data.list.id, data.subscription.id, linkId, remoteIp, country], (err, result) => {
                    if (err && err.code !== 'ER_DUP_ENTRY') {
                        return connection.rollback(() => {
                            connection.release();
                            return callback(err);
                        });
                    }

                    if (err && err.code === 'ER_DUP_ENTRY' || result.affectedRows > 1) {
                        return connection.commit(err => {
                            if (err) {
                                return connection.rollback(() => {
                                    connection.release();
                                    return callback(err);
                                });
                            }
                            connection.release();
                            return callback(null, false);
                        });
                    }

                    let query = 'UPDATE `subscription__' + data.list.id + '` SET `latest_click`=NOW(), `latest_open`=NOW() WHERE id=?';
                    connection.query(query, [data.subscription.id], err => {
                        if (err) {
                            return connection.rollback(() => {
                                connection.release();
                                return callback(err);
                            });
                        }

                        let query = 'UPDATE links SET clicks = clicks + 1 WHERE id=?';
                        connection.query(query, [linkId], err => {
                            if (err) {
                                return connection.rollback(() => {
                                    connection.release();
                                    return callback(err);
                                });
                            }

                            let query = 'INSERT INTO `campaign_tracker__' + data.campaign.id + '` (`list`, `subscriber`, `link`, `ip`, `country`) VALUES (?,?,?,?,?)';
                            connection.query(query, [data.list.id, data.subscription.id, 0, remoteIp, country], err => {
                                if (err && err.code !== 'ER_DUP_ENTRY') {
                                    return connection.rollback(() => {
                                        connection.release();
                                        return callback(err);
                                    });
                                }

                                if (err && err.code === 'ER_DUP_ENTRY') {
                                    return connection.commit(err => {
                                        if (err) {
                                            return connection.rollback(() => {
                                                connection.release();
                                                return callback(err);
                                            });
                                        }
                                        connection.release();
                                        return callback(null, false);
                                    });
                                }

                                let query = 'UPDATE campaigns SET clicks = clicks + 1 WHERE id=?';
                                connection.query(query, [data.campaign.id], err => {
                                    if (err) {
                                        return connection.rollback(() => {
                                            connection.release();
                                            return callback(err);
                                        });
                                    }
                                    connection.commit(err => {
                                        if (err) {
                                            return connection.rollback(() => {
                                                connection.release();
                                                return callback(err);
                                            });
                                        }
                                        connection.release();
                                        return callback(null, false);
                                    });
                                });

                                // also count clicks as open events in case beacon image was blocked
                                module.exports.countOpen(remoteIp, campaignCid, listCid, subscriptionCid, () => false);
                            });
                        });
                    });
                });
            });
        });
    });
};

module.exports.countOpen = (remoteIp, campaignCid, listCid, subscriptionCid, callback) => {
    getSubscriptionData(campaignCid, listCid, subscriptionCid, (err, data) => {
        if (err) {
            return callback(err);
        }

        db.getConnection((err, connection) => {
            if (err) {
                return callback(err);
            }

            connection.beginTransaction(err => {
                if (err) {
                    connection.release();
                    return callback(err);
                }

                let country = geoip.lookupCountry(remoteIp) || null;

                let query = 'INSERT INTO `campaign_tracker__' + data.campaign.id + '` (`list`, `subscriber`, `link`, `ip`, `country`) VALUES (?,?,?,?,?) ON DUPLICATE KEY UPDATE `count`=`count`+1';
                connection.query(query, [data.list.id, data.subscription.id, -1, remoteIp, country], (err, result) => {
                    if (err && err.code !== 'ER_DUP_ENTRY') {
                        return connection.rollback(() => {
                            connection.release();
                            return callback(err);
                        });
                    }
                    if (err && err.code === 'ER_DUP_ENTRY' || result.affectedRows > 1) {
                        return connection.commit(err => {
                            if (err) {
                                return connection.rollback(() => {
                                    connection.release();
                                    return callback(err);
                                });
                            }
                            connection.release();
                            return callback(null, false);
                        });
                    }

                    let query = 'UPDATE `subscription__' + data.list.id + '` SET `latest_open`=NOW() WHERE id=?';
                    connection.query(query, [data.subscription.id], err => {
                        if (err) {
                            return connection.rollback(() => {
                                connection.release();
                                return callback(err);
                            });
                        }

                        let query = 'UPDATE campaigns SET opened = opened + 1 WHERE id=?';
                        connection.query(query, [data.campaign.id], err => {
                            if (err) {
                                return connection.rollback(() => {
                                    connection.release();
                                    return callback(err);
                                });
                            }
                            connection.commit(err => {
                                if (err) {
                                    return connection.rollback(() => {
                                        connection.release();
                                        return callback(err);
                                    });
                                }
                                connection.release();
                                return callback(null, false);
                            });
                        });
                    });
                });
            });
        });
    });
};

module.exports.add = (url, campaignId, callback) => {
    db.getConnection((err, connection) => {
        if (err) {
            return callback(err);
        }

        let cid = shortid.generate();
        let query = 'INSERT INTO links (`cid`, `campaign`, `url`) VALUES (?,?,?)';
        connection.query(query, [cid, campaignId, url], (err, result) => {
            if (err && err.code !== 'ER_DUP_ENTRY') {
                connection.release();
                return callback(err);
            }

            if (!err && result && result.insertId) {
                connection.release();
                return callback(null, result.insertId, cid);
            }

            let query = 'SELECT id, cid FROM links WHERE `campaign`=? AND `url`=? LIMIT 1';
            connection.query(query, [campaignId, url], (err, rows) => {
                connection.release();
                if (err) {
                    return callback(err);
                }

                if (rows && rows.length) {
                    return callback(null, rows[0].id, rows[0].cid);
                }

                return callback(null, false);
            });
        });
    });
};

module.exports.updateLinks = (campaign, list, subscription, serviceUrl, message, callback) => {
    let re = /(<a[^>]* href\s*=[\s"']*)(http[^"'>\s]+)/gi;
    let urls = new Set();
    message.replace(re, (match, prefix, url) => {
        urls.add(url);
    });

    let map = new Map();
    let vals = urls.values();

    // insert tracking image
    let inserted = false;
    let imgUrl = urllib.resolve(serviceUrl, util.format('/links/%s/%s/%s', campaign.cid, list.cid, encodeURIComponent(subscription.cid)));
    let img = '<img src="' + imgUrl + '" width="1" height="1">';
    message = message.replace(/<\/body\b/i, match => {
        inserted = true;
        return img + match;
    });
    if (!inserted) {
        message = message + img;
    }

    let replaceUrls = () => {
        callback(null,
            message.replace(re, (match, prefix, url) =>
                prefix + (map.has(url) ? urllib.resolve(serviceUrl, util.format('/links/%s/%s/%s/%s', campaign.cid, list.cid, encodeURIComponent(subscription.cid), encodeURIComponent(map.get(url)))) : url)));
    };

    let storeNext = () => {
        let urlItem = vals.next();
        if (urlItem.done) {
            return replaceUrls();
        }

        module.exports.add(he.decode(urlItem.value, {
            isAttributeValue: true
        }), campaign.id, (err, linkId, cid) => {
            if (err) {
                log.error('Link', err.stack);
                return storeNext();
            }
            map.set(urlItem.value, cid);
            return storeNext();
        });
    };

    storeNext();
};

function getSubscriptionData(campaignCid, listCid, subscriptionCid, callback) {
    campaigns.getByCid(campaignCid, (err, campaign) => {
        if (err) {
            return callback(err);
        }
        if (!campaign) {
            return callback(new Error('Campaign not found'));
        }

        lists.getByCid(listCid, (err, list) => {
            if (err) {
                return callback(err);
            }
            if (!list) {
                return callback(new Error('Campaign not found'));
            }

            subscriptions.get(list.id, subscriptionCid, (err, subscription) => {
                if (err) {
                    return callback(err);
                }
                if (!subscription) {
                    return callback(new Error('Subscription not found'));
                }

                return callback(null, {
                    campaign,
                    list,
                    subscription
                });
            });
        });
    });
}
<commit_msg>add tracking image<commit_after>'use strict';

let db = require('../db');
let shortid = require('shortid');
let util = require('util');

let geoip = require('geoip-ultralight');
let campaigns = require('./campaigns');
let subscriptions = require('./subscriptions');
let lists = require('./lists');

let log = require('npmlog');
let urllib = require('url');
let he = require('he');

module.exports.resolve = (linkCid, callback) => {
    db.getConnection((err, connection) => {
        if (err) {
            return callback(err);
        }
        let query = 'SELECT id, url FROM links WHERE `cid`=? LIMIT 1';
        connection.query(query, [linkCid], (err, rows) => {
            connection.release();
            if (err) {
                return callback(err);
            }

            if (rows && rows.length) {
                return callback(null, rows[0].id, rows[0].url);
            }

            return callback(null, false);
        });
    });
};

module.exports.countClick = (remoteIp, campaignCid, listCid, subscriptionCid, linkId, callback) => {
    getSubscriptionData(campaignCid, listCid, subscriptionCid, (err, data) => {
        if (err) {
            return callback(err);
        }
        if(!data){
            return callback(null, false);
        }
        db.getConnection((err, connection) => {
            if (err) {
                return callback(err);
            }

            connection.beginTransaction(err => {
                if (err) {
                    connection.release();
                    return callback(err);
                }

                let country = geoip.lookupCountry(remoteIp) || null;

                let query = 'INSERT INTO `campaign_tracker__' + data.campaign.id + '` (`list`, `subscriber`, `link`, `ip`, `country`) VALUES (?,?,?,?,?) ON DUPLICATE KEY UPDATE `count`=`count`+1';
                connection.query(query, [data.list.id, data.subscription.id, linkId, remoteIp, country], (err, result) => {
                    if (err && err.code !== 'ER_DUP_ENTRY') {
                        return connection.rollback(() => {
                            connection.release();
                            return callback(err);
                        });
                    }

                    if (err && err.code === 'ER_DUP_ENTRY' || result.affectedRows > 1) {
                        return connection.commit(err => {
                            if (err) {
                                return connection.rollback(() => {
                                    connection.release();
                                    return callback(err);
                                });
                            }
                            connection.release();
                            return callback(null, false);
                        });
                    }

                    let query = 'UPDATE `subscription__' + data.list.id + '` SET `latest_click`=NOW(), `latest_open`=NOW() WHERE id=?';
                    connection.query(query, [data.subscription.id], err => {
                        if (err) {
                            return connection.rollback(() => {
                                connection.release();
                                return callback(err);
                            });
                        }

                        let query = 'UPDATE links SET clicks = clicks + 1 WHERE id=?';
                        connection.query(query, [linkId], err => {
                            if (err) {
                                return connection.rollback(() => {
                                    connection.release();
                                    return callback(err);
                                });
                            }

                            let query = 'INSERT INTO `campaign_tracker__' + data.campaign.id + '` (`list`, `subscriber`, `link`, `ip`, `country`) VALUES (?,?,?,?,?)';
                            connection.query(query, [data.list.id, data.subscription.id, 0, remoteIp, country], err => {
                                if (err && err.code !== 'ER_DUP_ENTRY') {
                                    return connection.rollback(() => {
                                        connection.release();
                                        return callback(err);
                                    });
                                }

                                if (err && err.code === 'ER_DUP_ENTRY') {
                                    return connection.commit(err => {
                                        if (err) {
                                            return connection.rollback(() => {
                                                connection.release();
                                                return callback(err);
                                            });
                                        }
                                        connection.release();
                                        return callback(null, false);
                                    });
                                }

                                let query = 'UPDATE campaigns SET clicks = clicks + 1 WHERE id=?';
                                connection.query(query, [data.campaign.id], err => {
                                    if (err) {
                                        return connection.rollback(() => {
                                            connection.release();
                                            return callback(err);
                                        });
                                    }
                                    connection.commit(err => {
                                        if (err) {
                                            return connection.rollback(() => {
                                                connection.release();
                                                return callback(err);
                                            });
                                        }
                                        connection.release();
                                        return callback(null, false);
                                    });
                                });

                                // also count clicks as open events in case beacon image was blocked
                                module.exports.countOpen(remoteIp, campaignCid, listCid, subscriptionCid, () => false);
                            });
                        });
                    });
                });
            });
        });
    });
};

module.exports.countOpen = (remoteIp, campaignCid, listCid, subscriptionCid, callback) => {
    getSubscriptionData(campaignCid, listCid, subscriptionCid, (err, data) => {
        if (err) {
            return callback(err);
        }

        db.getConnection((err, connection) => {
            if (err) {
                return callback(err);
            }

            connection.beginTransaction(err => {
                if (err) {
                    connection.release();
                    return callback(err);
                }

                let country = geoip.lookupCountry(remoteIp) || null;

                let query = 'INSERT INTO `campaign_tracker__' + data.campaign.id + '` (`list`, `subscriber`, `link`, `ip`, `country`) VALUES (?,?,?,?,?) ON DUPLICATE KEY UPDATE `count`=`count`+1';
                connection.query(query, [data.list.id, data.subscription.id, -1, remoteIp, country], (err, result) => {
                    if (err && err.code !== 'ER_DUP_ENTRY') {
                        return connection.rollback(() => {
                            connection.release();
                            return callback(err);
                        });
                    }
                    if (err && err.code === 'ER_DUP_ENTRY' || result.affectedRows > 1) {
                        return connection.commit(err => {
                            if (err) {
                                return connection.rollback(() => {
                                    connection.release();
                                    return callback(err);
                                });
                            }
                            connection.release();
                            return callback(null, false);
                        });
                    }

                    let query = 'UPDATE `subscription__' + data.list.id + '` SET `latest_open`=NOW() WHERE id=?';
                    connection.query(query, [data.subscription.id], err => {
                        if (err) {
                            return connection.rollback(() => {
                                connection.release();
                                return callback(err);
                            });
                        }

                        let query = 'UPDATE campaigns SET opened = opened + 1 WHERE id=?';
                        connection.query(query, [data.campaign.id], err => {
                            if (err) {
                                return connection.rollback(() => {
                                    connection.release();
                                    return callback(err);
                                });
                            }
                            connection.commit(err => {
                                if (err) {
                                    return connection.rollback(() => {
                                        connection.release();
                                        return callback(err);
                                    });
                                }
                                connection.release();
                                return callback(null, false);
                            });
                        });
                    });
                });
            });
        });
    });
};

module.exports.add = (url, campaignId, callback) => {
    db.getConnection((err, connection) => {
        if (err) {
            return callback(err);
        }

        let cid = shortid.generate();
        let query = 'INSERT INTO links (`cid`, `campaign`, `url`) VALUES (?,?,?)';
        connection.query(query, [cid, campaignId, url], (err, result) => {
            if (err && err.code !== 'ER_DUP_ENTRY') {
                connection.release();
                return callback(err);
            }

            if (!err && result && result.insertId) {
                connection.release();
                return callback(null, result.insertId, cid);
            }

            let query = 'SELECT id, cid FROM links WHERE `campaign`=? AND `url`=? LIMIT 1';
            connection.query(query, [campaignId, url], (err, rows) => {
                connection.release();
                if (err) {
                    return callback(err);
                }

                if (rows && rows.length) {
                    return callback(null, rows[0].id, rows[0].cid);
                }

                return callback(null, false);
            });
        });
    });
};

module.exports.updateLinks = (campaign, list, subscription, serviceUrl, message, callback) => {
    let re = /(<a[^>]* href\s*=[\s"']*)(http[^"'>\s]+)/gi;
    let urls = new Set();
    message.replace(re, (match, prefix, url) => {
        urls.add(url);
    });

    let map = new Map();
    let vals = urls.values();

    // insert tracking image
    let inserted = false;
    let imgUrl = urllib.resolve(serviceUrl, util.format('/links/%s/%s/%s', campaign.cid, list.cid, encodeURIComponent(subscription.cid)));
    let img = '<img src="' + imgUrl + '" width="1" height="1" alt="Tracking Image">';
    message = message.replace(/<\/body\b/i, match => {
        inserted = true;
        return img + match;
    });
    if (!inserted) {
        message = message + img;
    }

    let replaceUrls = () => {
        callback(null,
            message.replace(re, (match, prefix, url) =>
                prefix + (map.has(url) ? urllib.resolve(serviceUrl, util.format('/links/%s/%s/%s/%s', campaign.cid, list.cid, encodeURIComponent(subscription.cid), encodeURIComponent(map.get(url)))) : url)));
    };

    let storeNext = () => {
        let urlItem = vals.next();
        if (urlItem.done) {
            return replaceUrls();
        }

        module.exports.add(he.decode(urlItem.value, {
            isAttributeValue: true
        }), campaign.id, (err, linkId, cid) => {
            if (err) {
                log.error('Link', err.stack);
                return storeNext();
            }
            map.set(urlItem.value, cid);
            return storeNext();
        });
    };

    storeNext();
};

function getSubscriptionData(campaignCid, listCid, subscriptionCid, callback) {
    campaigns.getByCid(campaignCid, (err, campaign) => {
        if (err) {
            return callback(err);
        }
        if (!campaign) {
            return callback(new Error('Campaign not found'));
        }

        lists.getByCid(listCid, (err, list) => {
            if (err) {
                return callback(err);
            }
            if (!list) {
                return callback(new Error('Campaign not found'));
            }

            subscriptions.get(list.id, subscriptionCid, (err, subscription) => {
                if (err) {
                    return callback(err);
                }
                if (!subscription) {
                    return callback(new Error('Subscription not found'));
                }

                return callback(null, {
                    campaign,
                    list,
                    subscription
                });
            });
        });
    });
}
<|endoftext|>


<commit_before>import { NativeModules, NativeEventEmitter } from 'react-native';

import { Base } from './base';
import { default as User } from './user';
import promisify from '../utils/promisify';

const FirestackAuth = NativeModules.FirestackAuth;
const FirestackAuthEvt = new NativeEventEmitter(FirestackAuth);

export default class Auth extends Base {
  constructor(firestack, options = {}) {
    super(firestack, options);
    this._authResult = null;
    this.authenticated = false;
    this._user = null;

    // start listening straight away
    // generally though the initial event fired will get ignored
    // but this is ok as we fake it with the getCurrentUser below
    FirestackAuth.listenForAuth();

    this.getCurrentUser().then((u) => {
      const authResult = { authenticated: !!u };
      if (u) authResult.user = u;
      this._onAuthStateChanged(authResult);
      this._startListening();
    }).catch(() => {
      // todo check if error contains user disabled message maybe and add a disabled flag?
      this._onAuthStateChanged({ authenticated: false });
      this._startListening();
    });
  }

  /**
   * Internal function begin listening for auth changes
   * only called after getting current user.
   * @private
   */
  _startListening() {
    FirestackAuthEvt.addListener('listenForAuth', this._onAuthStateChanged.bind(this));
  }

  /**
   * Internal auth changed listener
   * @param auth
   * @private
   */
  _onAuthStateChanged(auth) {
    this._authResult = auth;
    this.emit('onAuthStateChanged', this._authResult.user || null);
    this.authenticated = auth ? auth.authenticated || false : false;
    if (auth && auth.user && !this._user) this._user = new User(this, auth);
    else if ((!auth || !auth.user) && this._user) this._user = null;
    else this._user ? this._user._updateValues(auth) : null;
  }

  /*
   * WEB API
   */

  /**
   * Listen for auth changes.
   * @param listener
   */
  onAuthStateChanged(listener) {
    this.log.info('Creating onAuthStateChanged listener');
    this.on('onAuthStateChanged', listener);
    if (this._authResult) listener(this._authResult);
  }

  /**
   * Remove auth change listener
   * @param listener
   */
  offAuthStateChanged(listener) {
    this.log.info('Removing onAuthStateChanged listener');
    this.removeListener('onAuthStateChanged', listener);
  }

  /**
   * Create a user with the email/password functionality
   * @param  {string} email    The user's email
   * @param  {string} password The user's password
   * @return {Promise}         A promise indicating the completion
   */
  createUserWithEmailAndPassword(email, password) {
    this.log.info('Creating user with email and password', email);
    return promisify('createUserWithEmail', FirestackAuth)(email, password);
  }

  /**
   * Sign a user in with email/password
   * @param  {string} email    The user's email
   * @param  {string} password The user's password
   * @return {Promise}         A promise that is resolved upon completion
   */
  signInWithEmailAndPassword(email, password) {
    this.log.info('Signing in user with email and password', email);
    return promisify('signInWithEmail', FirestackAuth)(email, password)
  }

  /**
   * Update the current user's email
   * @param  {string} email The user's _new_ email
   * @return {Promise}       A promise resolved upon completion
   */
  updateEmail(email) {
    return promisify('updateUserEmail', FirestackAuth)(email);
  }

  /**
   * Send verification email to current user.
   */
  sendEmailVerification() {
    return promisify('sendEmailVerification', FirestackAuth)();
  }

  /**
   * Update the current user's password
   * @param  {string} password the new password
   * @return {Promise}
   */
  updatePassword(password) {
    return promisify('updateUserPassword', FirestackAuth)(password);
  }

  /**
   * Update the current user's profile
   * @param  {Object} updates An object containing the keys listed [here](https://firebase.google.com/docs/auth/ios/manage-users#update_a_users_profile)
   * @return {Promise}
   */
  updateProfile(updates) {
    return promisify('updateUserProfile', FirestackAuth)(updates);
  }

  /**
   * Sign the user in with a custom auth token
   * @param  {string} customToken  A self-signed custom auth token.
   * @return {Promise}             A promise resolved upon completion
   */
  signInWithCustomToken(customToken) {
    return promisify('signInWithCustomToken', FirestackAuth)(customToken)
  }

  /**
   * Sign the user in with a third-party authentication provider
   * @param  {string} provider   The name of the provider to use for login
   * @param  {string} authToken  The authToken granted by the provider
   * @param  {string} authSecret The authToken secret granted by the provider
   * @return {Promise}           A promise resolved upon completion
   */
  signInWithProvider(provider, authToken, authSecret) {
    return promisify('signInWithProvider', FirestackAuth)(provider, authToken, authSecret)
  }

  /**
   * Reauthenticate a user with a third-party authentication provider
   * @param  {string} provider The provider name
   * @param  {string} token    The authToken granted by the provider
   * @param  {string} secret   The authTokenSecret granted by the provider
   * @return {Promise}         A promise resolved upon completion
   */
  reauthenticateWithCredentialForProvider(provider, token, secret) {
    return promisify('reauthenticateWithCredentialForProvider', FirestackAuth)(provider, token, secret)
  }

  /**
   * Sign a user in anonymously
   * @return {Promise}            A promise resolved upon completion
   */
  signInAnonymously() {
    return promisify('signInAnonymously', FirestackAuth)();
  }

  /**
   * Send reset password instructions via email
   * @param {string} email The email to send password reset instructions
   */
  sendPasswordResetWithEmail(email) {
    return promisify('sendPasswordResetWithEmail', FirestackAuth)(email);
  }

  /**
   * Delete the current user
   * @return {Promise}
   */
  deleteUser() {
    return promisify('deleteUser', FirestackAuth)();
  }

  /**
   * get the token of current user
   * @return {Promise}
   */
  getToken() {
    return promisify('getToken', FirestackAuth)();
  }

  /**
   * Sign the current user out
   * @return {Promise}
   */
  signOut() {
    return promisify('signOut', FirestackAuth)();
  }

  /**
   * Get the currently signed in user
   * @return {Promise}
   */
  getCurrentUser() {
    return promisify('getCurrentUser', FirestackAuth)();
  }

  /**
   * Get the currently signed in user
   * @return {Promise}
   */
  get currentUser() {
    return this._user;
  }

  get namespace() {
    return 'firestack:auth';
  }
}
<commit_msg>initial onAuthChanged event now returns null or user when beginning listening - re #2<commit_after>import { NativeModules, NativeEventEmitter } from 'react-native';

import { Base } from './base';
import { default as User } from './user';
import promisify from '../utils/promisify';

const FirestackAuth = NativeModules.FirestackAuth;
const FirestackAuthEvt = new NativeEventEmitter(FirestackAuth);

export default class Auth extends Base {
  constructor(firestack, options = {}) {
    super(firestack, options);
    this._authResult = null;
    this.authenticated = false;
    this._user = null;

    // start listening straight away
    // generally though the initial event fired will get ignored
    // but this is ok as we fake it with the getCurrentUser below
    FirestackAuth.listenForAuth();

    this.getCurrentUser().then((u) => {
      const authResult = { authenticated: !!u };
      if (u) authResult.user = u;
      this._onAuthStateChanged(authResult);
      this._startListening();
    }).catch(() => {
      // todo check if error contains user disabled message maybe and add a disabled flag?
      this._onAuthStateChanged({ authenticated: false });
      this._startListening();
    });
  }

  /**
   * Internal function begin listening for auth changes
   * only called after getting current user.
   * @private
   */
  _startListening() {
    FirestackAuthEvt.addListener('listenForAuth', this._onAuthStateChanged.bind(this));
  }

  /**
   * Internal auth changed listener
   * @param auth
   * @private
   */
  _onAuthStateChanged(auth) {
    this._authResult = auth;
    this.emit('onAuthStateChanged', this._authResult.user || null);
    this.authenticated = auth ? auth.authenticated || false : false;
    if (auth && auth.user && !this._user) this._user = new User(this, auth);
    else if ((!auth || !auth.user) && this._user) this._user = null;
    else this._user ? this._user._updateValues(auth) : null;
  }

  /*
   * WEB API
   */

  /**
   * Listen for auth changes.
   * @param listener
   */
  onAuthStateChanged(listener) {
    this.log.info('Creating onAuthStateChanged listener');
    this.on('onAuthStateChanged', listener);
    if (this._authResult) listener(this._authResult.user || null);
  }

  /**
   * Remove auth change listener
   * @param listener
   */
  offAuthStateChanged(listener) {
    this.log.info('Removing onAuthStateChanged listener');
    this.removeListener('onAuthStateChanged', listener);
  }

  /**
   * Create a user with the email/password functionality
   * @param  {string} email    The user's email
   * @param  {string} password The user's password
   * @return {Promise}         A promise indicating the completion
   */
  createUserWithEmailAndPassword(email, password) {
    this.log.info('Creating user with email and password', email);
    return promisify('createUserWithEmail', FirestackAuth)(email, password);
  }

  /**
   * Sign a user in with email/password
   * @param  {string} email    The user's email
   * @param  {string} password The user's password
   * @return {Promise}         A promise that is resolved upon completion
   */
  signInWithEmailAndPassword(email, password) {
    this.log.info('Signing in user with email and password', email);
    return promisify('signInWithEmail', FirestackAuth)(email, password)
  }

  /**
   * Update the current user's email
   * @param  {string} email The user's _new_ email
   * @return {Promise}       A promise resolved upon completion
   */
  updateEmail(email) {
    return promisify('updateUserEmail', FirestackAuth)(email);
  }

  /**
   * Send verification email to current user.
   */
  sendEmailVerification() {
    return promisify('sendEmailVerification', FirestackAuth)();
  }

  /**
   * Update the current user's password
   * @param  {string} password the new password
   * @return {Promise}
   */
  updatePassword(password) {
    return promisify('updateUserPassword', FirestackAuth)(password);
  }

  /**
   * Update the current user's profile
   * @param  {Object} updates An object containing the keys listed [here](https://firebase.google.com/docs/auth/ios/manage-users#update_a_users_profile)
   * @return {Promise}
   */
  updateProfile(updates) {
    return promisify('updateUserProfile', FirestackAuth)(updates);
  }

  /**
   * Sign the user in with a custom auth token
   * @param  {string} customToken  A self-signed custom auth token.
   * @return {Promise}             A promise resolved upon completion
   */
  signInWithCustomToken(customToken) {
    return promisify('signInWithCustomToken', FirestackAuth)(customToken)
  }

  /**
   * Sign the user in with a third-party authentication provider
   * @param  {string} provider   The name of the provider to use for login
   * @param  {string} authToken  The authToken granted by the provider
   * @param  {string} authSecret The authToken secret granted by the provider
   * @return {Promise}           A promise resolved upon completion
   */
  signInWithProvider(provider, authToken, authSecret) {
    return promisify('signInWithProvider', FirestackAuth)(provider, authToken, authSecret)
  }

  /**
   * Reauthenticate a user with a third-party authentication provider
   * @param  {string} provider The provider name
   * @param  {string} token    The authToken granted by the provider
   * @param  {string} secret   The authTokenSecret granted by the provider
   * @return {Promise}         A promise resolved upon completion
   */
  reauthenticateWithCredentialForProvider(provider, token, secret) {
    return promisify('reauthenticateWithCredentialForProvider', FirestackAuth)(provider, token, secret)
  }

  /**
   * Sign a user in anonymously
   * @return {Promise}            A promise resolved upon completion
   */
  signInAnonymously() {
    return promisify('signInAnonymously', FirestackAuth)();
  }

  /**
   * Send reset password instructions via email
   * @param {string} email The email to send password reset instructions
   */
  sendPasswordResetWithEmail(email) {
    return promisify('sendPasswordResetWithEmail', FirestackAuth)(email);
  }

  /**
   * Delete the current user
   * @return {Promise}
   */
  deleteUser() {
    return promisify('deleteUser', FirestackAuth)();
  }

  /**
   * get the token of current user
   * @return {Promise}
   */
  getToken() {
    return promisify('getToken', FirestackAuth)();
  }

  /**
   * Sign the current user out
   * @return {Promise}
   */
  signOut() {
    return promisify('signOut', FirestackAuth)();
  }

  /**
   * Get the currently signed in user
   * @return {Promise}
   */
  getCurrentUser() {
    return promisify('getCurrentUser', FirestackAuth)();
  }

  /**
   * Get the currently signed in user
   * @return {Promise}
   */
  get currentUser() {
    return this._user;
  }

  get namespace() {
    return 'firestack:auth';
  }
}
<|endoftext|>


<commit_before>import { css } from "../../src/literals.js";

export default css`
:host {
    position: absolute;
    display: block;

    top: 0; right: 0; left: 0;

    min-height: 100vh;

    font-family: var(--magnon-font);

    --magnon-header-height: 125px;
}

#header-container {
    position: absolute;
    top: 0; right: 0; bottom: 0; left: 0;
    display: flex;
    width: 100%;
    height: var(--magnon-header-height);
    z-index: 100;

    justify-content: center;
    flex-direction: column;

    padding: 5px;
    box-sizing: border-box;

    background: var(--magnon-shell-header-background, var(--magnon-highlight-color));
    --magnon-logo-color: var(--magnon-shell-header-color, var(--magnon-highlight-contrast-color));

    box-shadow: var(--magnon-shadow-1);
}

#header-container > * {
    flex-grow: 1;
}

#navigation-button {
    position: absolute;
    top: 5px;
    left: 5px;

    --magnon-icon-button-padding: 5px;
    --magnon-icon-color: white;
    --magnon-icon-size: 30px;

    display: none;
}

#logo-container {
    display: flex;
    align-items: center;
    justify-content: center;
    pointer-events: none;
}

#header-container nav {
    display: flex;
    justify-content: center;
    align-items: center;
}

#header-container nav ::slotted(a) {
    color: white !important;
    text-decoration: none;
    font-size: 18px;
    font-family: var(--magnon-header-font);
    color: var(--magnon-shell-header-color, var(--magnon-highlight-contrast-color));
    cursor: pointer;

    margin: 0 10px;
}

#logo-link {
    height: 40px;
    pointer-events: all;
    font-family: var(--magnon-header-font);
    text-decoration: none;
    color: white;
    display: flex;
    justify-content: center;
    align-items: center;
}

#logo-link > magnon-logo {
    height: 100%;
}

#site-title:not(:empty) {
    margin-left: 0.5ch;
}

#main-container {
    position: absolute;
    top: var(--magnon-header-height);
    left: 0;
    right: 0;

    width: 100%;
    min-height: calc(100% - var(--magnon-header-height));
    display: flex;
    flex-direction: column;
    overflow: hidden;

    background: var(--magnon-shell-background, var(--magnon-background));
}

#content-container {
    position: relative;

    margin: 20px auto 0 auto;
    width: 100vw;

    box-sizing: border-box;
    min-height: 100%;
    flex-grow: 1;

    z-index: 2;
}

#content-container.expand-content {
    width: 100%;
    max-width: 100%;
    min-height: calc(100vh - var(--magnon-header-height) + 300px);
    margin: 0;
}

#footer {
    display: inline-block;
    width: 100%;
    min-height: 300px;
    transform: translate3d(0, 0, 0);

    background: var(--magnon-black);
    color: white;

    --magnon-outline-color: white;

    width: 100%;
    z-index: 100;
}

#footer-container * {
    outline-color: var(--magnon-outline-color);
}

#footer-container {
    width: 100%;
    min-height: 300px;
    max-width: 1000px;

    position: relative;
    margin: auto;

    font-family: var(--magnon-font);
}

.side {
    width: 100%;
    height: auto;
    position: relative;
    text-align: center;
}

#right * {
    color: white !important;
}

#footer-navigation {
    flex-grow: 1;
    margin: 20px 0 0 0;
}

#footer-navigation ::slotted(a) {
    color: white !important;
    text-decoration: none;
    font-size: 20px;
    display: block;
    margin-bottom: 15px;
}

#social-buttons {
    --magnon-social-icon-button-color: white;
}

#announcement {
    flex-grow: 1;
    margin: 20px;
}

#announcement-title {
    margin-bottom: 10px;
    font-size: 20px;
    font-weight: bold;
    font-family: var(--magnon-header-font);
}

#license {
    margin: 20px;
    font-size: 13px;
}

@media(min-width: 580px) {
    #content-container {
        width: 85vw;
    }

    #footer {
        display: block;
    }

    #footer-container {
        flex-direction: row;
        display: flex;
    }

    .side {
        width: 50%;
        height: 100%;
        position: absolute;
        top: 0; bottom: 0;
        text-align: left;
        display: flex;
        flex-direction: column;
    }

    #left {
        left: 0;
    }

    #right {
        right: 0;
        text-align: right;
    }

    #footer-navigation {
        margin: 20px 0 0 20px;
    }

    #social-buttons {
        margin: 0 0 20px 10px;
    }
}

@media(min-width: 1200px) {
    #content-container {
        width: 70vw;
    }
}
`;

export const globalStyle = css`
html, body {
    padding: 0;
    margin: 0;
    overflow-y: scroll;
    font-size: 18px;
    font-family: var(--magnon-font)
    outline-color: white;
}

a {
    color: var(--magnon-highlight-color);
    transition: color 0.2s;
}

a:hover, a:focus {
    color: var(--magnon-black);
}

h1, h2, h3, h4, h5, h6 {
    font-family: var(--magnon-header-font);
    font-weight: bold;
}

h1 {
    font-size: 40px;
}

h2 {
    font-size: 30px;
}

h3 {
    font-size: 28px;
}

h4 {
    font-size: 25px;
}

h5 {
    font-size: 22px;
}

h6 {
    font-size: 20px;
}
`;
<commit_msg>Add hr styling<commit_after>import { css } from "../../src/literals.js";

export default css`
:host {
    position: absolute;
    display: block;

    top: 0; right: 0; left: 0;

    min-height: 100vh;

    font-family: var(--magnon-font);

    --magnon-header-height: 125px;
}

#header-container {
    position: absolute;
    top: 0; right: 0; bottom: 0; left: 0;
    display: flex;
    width: 100%;
    height: var(--magnon-header-height);
    z-index: 100;

    justify-content: center;
    flex-direction: column;

    padding: 5px;
    box-sizing: border-box;

    background: var(--magnon-shell-header-background, var(--magnon-highlight-color));
    --magnon-logo-color: var(--magnon-shell-header-color, var(--magnon-highlight-contrast-color));

    box-shadow: var(--magnon-shadow-1);
}

#header-container > * {
    flex-grow: 1;
}

#navigation-button {
    position: absolute;
    top: 5px;
    left: 5px;

    --magnon-icon-button-padding: 5px;
    --magnon-icon-color: white;
    --magnon-icon-size: 30px;

    display: none;
}

#logo-container {
    display: flex;
    align-items: center;
    justify-content: center;
    pointer-events: none;
}

#header-container nav {
    display: flex;
    justify-content: center;
    align-items: center;
}

#header-container nav ::slotted(a) {
    color: white !important;
    text-decoration: none;
    font-size: 18px;
    font-family: var(--magnon-header-font);
    color: var(--magnon-shell-header-color, var(--magnon-highlight-contrast-color));
    cursor: pointer;

    margin: 0 10px;
}

#logo-link {
    height: 40px;
    pointer-events: all;
    font-family: var(--magnon-header-font);
    text-decoration: none;
    color: white;
    display: flex;
    justify-content: center;
    align-items: center;
}

#logo-link > magnon-logo {
    height: 100%;
}

#site-title:not(:empty) {
    margin-left: 0.5ch;
}

#main-container {
    position: absolute;
    top: var(--magnon-header-height);
    left: 0;
    right: 0;

    width: 100%;
    min-height: calc(100% - var(--magnon-header-height));
    display: flex;
    flex-direction: column;
    overflow: hidden;

    background: var(--magnon-shell-background, var(--magnon-background));
}

#content-container {
    position: relative;

    margin: 20px auto 0 auto;
    width: 100vw;

    box-sizing: border-box;
    min-height: 100%;
    flex-grow: 1;

    z-index: 2;
}

#content-container.expand-content {
    width: 100%;
    max-width: 100%;
    min-height: calc(100vh - var(--magnon-header-height) + 300px);
    margin: 0;
}

#footer {
    display: inline-block;
    width: 100%;
    min-height: 300px;
    transform: translate3d(0, 0, 0);

    background: var(--magnon-black);
    color: white;

    --magnon-outline-color: white;

    width: 100%;
    z-index: 100;
}

#footer-container * {
    outline-color: var(--magnon-outline-color);
}

#footer-container {
    width: 100%;
    min-height: 300px;
    max-width: 1000px;

    position: relative;
    margin: auto;

    font-family: var(--magnon-font);
}

.side {
    width: 100%;
    height: auto;
    position: relative;
    text-align: center;
}

#right * {
    color: white !important;
}

#footer-navigation {
    flex-grow: 1;
    margin: 20px 0 0 0;
}

#footer-navigation ::slotted(a) {
    color: white !important;
    text-decoration: none;
    font-size: 20px;
    display: block;
    margin-bottom: 15px;
}

#social-buttons {
    --magnon-social-icon-button-color: white;
}

#announcement {
    flex-grow: 1;
    margin: 20px;
}

#announcement-title {
    margin-bottom: 10px;
    font-size: 20px;
    font-weight: bold;
    font-family: var(--magnon-header-font);
}

#license {
    margin: 20px;
    font-size: 13px;
}

@media(min-width: 580px) {
    #content-container {
        width: 85vw;
    }

    #footer {
        display: block;
    }

    #footer-container {
        flex-direction: row;
        display: flex;
    }

    .side {
        width: 50%;
        height: 100%;
        position: absolute;
        top: 0; bottom: 0;
        text-align: left;
        display: flex;
        flex-direction: column;
    }

    #left {
        left: 0;
    }

    #right {
        right: 0;
        text-align: right;
    }

    #footer-navigation {
        margin: 20px 0 0 20px;
    }

    #social-buttons {
        margin: 0 0 20px 10px;
    }
}

@media(min-width: 1200px) {
    #content-container {
        width: 70vw;
    }
}
`;

export const globalStyle = css`
html, body {
    padding: 0;
    margin: 0;
    overflow-y: scroll;
    font-size: 18px;
    font-family: var(--magnon-font)
    outline-color: white;
}

a {
    color: var(--magnon-highlight-color);
    transition: color 0.2s;
}

a:hover, a:focus {
    color: var(--magnon-black);
}

h1, h2, h3, h4, h5, h6 {
    font-family: var(--magnon-header-font);
    font-weight: bold;
}

h1 {
    font-size: 40px;
}

h2 {
    font-size: 30px;
}

h3 {
    font-size: 28px;
}

h4 {
    font-size: 25px;
}

h5 {
    font-size: 22px;
}

h6 {
    font-size: 20px;
}

hr {
    margin: 40px 15%;
    height: 0px;
    border: 0;
    border-top: 1px solid rgba(0, 0, 0, 0.2);
}
`;
<|endoftext|>


<commit_before>import Feature from 'ol/Feature';
import VectorLayer from 'ol/layer/Vector';
import {Circle, Fill, Stroke, Style} from 'ol/style';
import {Point} from 'ol/geom';
import {Vector} from 'ol/source';
import {createStringXY, toStringHDMS} from 'ol/coordinate';
import {transform} from 'ol/proj';

/**
 * @param $rootScope
 * @param HsMapService
 * @param HsCore
 * @param $sce
 * @param HsConfig
 * @param HsLayoutService
 * @param HsUtilsService
 * @param $timeout
 * @param gettext
 */
export default function (
  $rootScope,
  HsMapService,
  HsCore,
  $sce,
  HsConfig,
  HsLayoutService,
  HsUtilsService,
  $timeout,
  gettext
) {
  'ngInject';
  const me = this;

  let map;

  this.queryPoint = new Point([0, 0]);
  this.queryLayer = new VectorLayer({
    title: 'Point clicked',
    queryable: false,
    source: new Vector({
      features: [
        new Feature({
          geometry: me.queryPoint,
        }),
      ],
    }),
    show_in_manager: false,
    removable: false,
    style: pointClickedStyle,
  });

  this.data = {};
  this.data.attributes = [];
  this.data.features = [];
  this.data.featureInfoHtmls = [];
  this.data.customFeatures = [];
  this.data.coordinates = [];
  this.queryActive = false;
  this.popupClassname = '';
  this.selector = null;
  this.currentQuery = null;
  this.featuresUnderMouse = [];
  this.featureLayersUnderMouse = [];
  this.dataCleared = true;

  /**
   *
   */
  function init() {
    map = HsMapService.map;
    me.activateQueries();
    map.on('singleclick', (evt) => {
      $rootScope.$broadcast(
        'mapClicked',
        angular.extend(evt, {
          coordinates: getCoordinate(evt.coordinate),
        })
      );
      if (!me.queryActive) {
        return;
      }
      me.popupClassname = '';
      if (!me.dataCleared) {
        me.clearData();
      }
      me.dataCleared = false;
      me.currentQuery = (Math.random() + 1).toString(36).substring(7);
      me.setData(getCoordinate(evt.coordinate), 'coordinates', true);
      me.last_coordinate_clicked = evt.coordinate; //It is used in some examples and apps
      $rootScope.$broadcast('mapQueryStarted', evt);
    });

    if (
      angular.isDefined(HsConfig.popUpDisplay) &&
      HsConfig.popUpDisplay === 'hover'
    ) {
      map.on(
        'pointermove',
        HsUtilsService.debounce(me.showPopUp, 500, false, me)
      );
    } else if (
      angular.isDefined(HsConfig.popUpDisplay) &&
      HsConfig.popUpDisplay === 'click'
    ) {
      map.on(
        'singleclick',
        HsUtilsService.debounce(me.showPopUp, 500, false, me)
      );
    } /* else none */
  }

  /**
   * @param e Event, which triggered this function
   */
  this.showPopUp = function (e) {
    if (e.dragging) {
      return;
    }
    const map = e.map;
    $timeout((_) => {
      me.featuresUnderMouse = map.getFeaturesAtPixel(e.pixel);
      if (me.featuresUnderMouse !== null) {
        me.featuresUnderMouse = me.featuresUnderMouse.filter((feature) => {
          return (
            feature.getLayer &&
            feature.getLayer(map) &&
            feature.getLayer(map).get('title').length > 0 &&
            feature.getLayer(map).get('title') !== 'Point clicked'
          );
        });
        me.featureLayersUnderMouse = me.featuresUnderMouse.map((f) =>
          f.getLayer(HsMapService.map)
        );
        me.featureLayersUnderMouse = HsUtilsService.removeDuplicates(
          me.featureLayersUnderMouse,
          'title'
        );
        me.featureLayersUnderMouse = me.featureLayersUnderMouse.map((l) => {
          return {
            layer: l.get('title'),
            features: me.featuresUnderMouse.filter(
              (f) => f.getLayer(HsMapService.map) == l
            ),
          };
        });
        me.featuresUnderMouse.forEach((feature) => {
          me.serializeFeatureAttributes(feature);
          if (feature.get('features')) {
            feature
              .get('features')
              .forEach((subfeature) =>
                me.serializeFeatureAttributes(subfeature)
              );
          }
        });
        const pixel = e.pixel;
        pixel[0] += 2;
        pixel[1] += 4;
        me.hoverPopup.setPosition(map.getCoordinateFromPixel(pixel));
      } else {
        me.featuresUnderMouse = [];
      }
    }, 0);
  };

  /**
   * @param feature
   */
  this.serializeFeatureAttributes = function (feature) {
    if (angular.isUndefined(feature.getLayer)) {
      return;
    }
    const layer = feature.getLayer(HsMapService.map);
    let attrsConfig = [];
    if (
      angular.isDefined(layer.get('popUp')) &&
      angular.isDefined(layer.get('popUp').attributes)
    ) {
      //must be an array
      attrsConfig = layer.get('popUp').attributes;
    } else if (angular.isDefined(layer.get('hoveredKeys'))) {
      //only for backwards-compatibility with HSLayers 1.10 .. 1.22
      //should be dropped in future releases
      //expected to be an array
      attrsConfig = layer.get('hoveredKeys');
      if (angular.isDefined(layer.get('hoveredKeysTranslations'))) {
        //expected to be an object
        for (const [key, val] of Object.entries(
          layer.get('hoveredKeysTranslations')
        )) {
          const index = attrsConfig.indexOf(key);
          if (index > -1) {
            attrsConfig[index] = {
              'attribute': key,
              'label': val,
            };
          }
        }
      }
    } else {
      // Layer is not configured to show pop-ups
      return;
    }
    feature.attributesForHover = [];
    for (const attr of attrsConfig) {
      let attrName, attrLabel;
      let attrFunction = (x) => x;
      if (typeof attr === 'string' || attr instanceof String) {
        //simple case when only attribute name is provided in the layer config
        attrName = attr;
        attrLabel = attr;
      } else {
        if (angular.isUndefined(attr.attribute)) {
          //implies malformed layer config - 'attribute' is obligatory in this case
          continue;
        }
        attrName = attr.attribute;
        attrLabel = angular.isDefined(attr.label) ? attr.label : attr.attribute;
        if (angular.isDefined(attr.displayFunction)) {
          attrFunction = attr.displayFunction;
        }
      }
      if (angular.isDefined(feature.get(attrName))) {
        feature.attributesForHover.push({
          key: attrLabel,
          value: feature.get(attrName),
          displayFunction: attrFunction,
        });
      }
    }
  };

  HsMapService.loaded().then(init);

  this.setData = function (data, type, overwrite) {
    if (angular.isDefined(type)) {
      if (angular.isDefined(overwrite) && overwrite) {
        me.data[type].length = 0;
      }
      if (angular.isArray(data)) {
        me.data[type] = me.data[type].concat(data);
      } else {
        me.data[type].push(data);
      }
      $rootScope.$broadcast('infopanel.updated'); //Compatibility, deprecated
      $rootScope.$broadcast('query.dataUpdated', me.data);
    } else if (console) {
      console.log('Query.BaseService.setData type not passed');
    }
  };

  this.clearData = function (type) {
    if (type) {
      me.data[type].length = 0;
    } else {
      me.data.attributes.length = 0;
      me.data.features = [];
      me.data.coordinates.length = 0;
      me.data.featureInfoHtmls = [];
      me.data.customFeatures = [];
    }
    const invisiblePopup = me.getInvisiblePopup();
    if (invisiblePopup) {
      invisiblePopup.contentDocument.body.innerHTML = '';
      invisiblePopup.style.height = 0;
      invisiblePopup.style.width = 0;
    }
    me.dataCleared = true;
  };

  this.getInvisiblePopup = function () {
    return document.getElementById('invisible_popup');
  };

  this.pushFeatureInfoHtml = (html) => {
    me.data.featureInfoHtmls.push($sce.trustAsHtml(html));
    me.dataCleared = false;
  };

  this.fillIframeAndResize = function (iframe, response, append) {
    var iframe = me.getInvisiblePopup();
    if (append) {
      iframe.contentDocument.body.innerHTML += response;
    } else {
      iframe.contentDocument.body.innerHTML = response;
    }
    let tmp_width = iframe.contentDocument.innerWidth;
    if (
      tmp_width >
      HsLayoutService.contentWrapper.querySelector('.hs-ol-map').clientWidth -
        60
    ) {
      tmp_width =
        HsLayoutService.contentWrapper.querySelector('.hs-ol-map').clientWidth -
        60;
    }
    iframe.style.width = tmp_width + 'px';
    let tmp_height = iframe.contentDocument.innerHeight;
    if (tmp_height > 700) {
      tmp_height = 700;
    }
    iframe.style.height = tmp_height + 'px';
  };

  /**
   * @param coordinate
   */
  function getCoordinate(coordinate) {
    me.queryPoint.setCoordinates(coordinate, 'XY');
    const epsg4326Coordinate = transform(
      coordinate,
      map.getView().getProjection(),
      'EPSG:4326'
    );
    const coords = {
      name: gettext('Coordinates'),
      mapProjCoordinate: coordinate,
      epsg4326Coordinate,
      projections: [
        {
          'name': 'EPSG:4326',
          'value': toStringHDMS(epsg4326Coordinate),
        },
        {
          'name': 'EPSG:4326',
          'value': createStringXY(7)(epsg4326Coordinate),
        },
        {
          'name': map.getView().getProjection().getCode(),
          'value': createStringXY(7)(coordinate),
        },
      ],
    };
    return coords;
  }

  this.activateQueries = function () {
    if (me.queryActive) {
      return;
    }
    me.queryActive = true;
    HsMapService.loaded().then((map) => {
      map.addLayer(me.queryLayer);
      $rootScope.$broadcast('queryStatusChanged', true);
    });
  };

  this.deactivateQueries = function () {
    if (!me.queryActive) {
      return;
    }
    me.queryActive = false;
    HsMapService.loaded().then((map) => {
      map.removeLayer(me.queryLayer);
      $rootScope.$broadcast('queryStatusChanged', false);
    });
  };

  me.nonQueryablePanels = [
    'measure',
    'composition_browser',
    'analysis',
    'sensors',
  ];

  this.currentPanelQueryable = function () {
    return (
      me.nonQueryablePanels.indexOf(HsLayoutService.mainpanel) == -1 &&
      me.nonQueryablePanels.indexOf('*') == -1
    );
  };

  /**
   * @param feature
   */
  function pointClickedStyle(feature) {
    const defaultStyle = new Style({
      image: new Circle({
        fill: new Fill({
          color: 'rgba(255, 156, 156, 0.4)',
        }),
        stroke: new Stroke({
          color: '#cc3333',
          width: 1,
        }),
        radius: 5,
      }),
    });
    if (angular.isDefined(HsConfig.queryPoint)) {
      if (HsConfig.queryPoint == 'hidden') {
        defaultStyle.getImage().setRadius(0);
      } else if (HsConfig.queryPoint == 'notWithin') {
        if (me.selector.getFeatures().getLength() > 0) {
          defaultStyle.getImage().setRadius(0);
        }
      }
    }
    return defaultStyle;
  }

  if (me.deregisterVectorSelectorCreated) {
    me.deregisterVectorSelectorCreated();
  }
  me.deregisterVectorSelectorCreated = $rootScope.$on(
    'vectorSelectorCreated',
    (e, selector) => {
      me.selector = selector;
    }
  );
  return me;
}
<commit_msg>Make draw panel non queriable<commit_after>import Feature from 'ol/Feature';
import VectorLayer from 'ol/layer/Vector';
import {Circle, Fill, Stroke, Style} from 'ol/style';
import {Point} from 'ol/geom';
import {Vector} from 'ol/source';
import {createStringXY, toStringHDMS} from 'ol/coordinate';
import {transform} from 'ol/proj';

/**
 * @param $rootScope
 * @param HsMapService
 * @param HsCore
 * @param $sce
 * @param HsConfig
 * @param HsLayoutService
 * @param HsUtilsService
 * @param $timeout
 * @param gettext
 */
export default function (
  $rootScope,
  HsMapService,
  HsCore,
  $sce,
  HsConfig,
  HsLayoutService,
  HsUtilsService,
  $timeout,
  gettext
) {
  'ngInject';
  const me = this;

  let map;

  this.queryPoint = new Point([0, 0]);
  this.queryLayer = new VectorLayer({
    title: 'Point clicked',
    queryable: false,
    source: new Vector({
      features: [
        new Feature({
          geometry: me.queryPoint,
        }),
      ],
    }),
    show_in_manager: false,
    removable: false,
    style: pointClickedStyle,
  });

  this.data = {};
  this.data.attributes = [];
  this.data.features = [];
  this.data.featureInfoHtmls = [];
  this.data.customFeatures = [];
  this.data.coordinates = [];
  this.queryActive = false;
  this.popupClassname = '';
  this.selector = null;
  this.currentQuery = null;
  this.featuresUnderMouse = [];
  this.featureLayersUnderMouse = [];
  this.dataCleared = true;

  /**
   *
   */
  function init() {
    map = HsMapService.map;
    me.activateQueries();
    map.on('singleclick', (evt) => {
      $rootScope.$broadcast(
        'mapClicked',
        angular.extend(evt, {
          coordinates: getCoordinate(evt.coordinate),
        })
      );
      if (!me.queryActive) {
        return;
      }
      me.popupClassname = '';
      if (!me.dataCleared) {
        me.clearData();
      }
      me.dataCleared = false;
      me.currentQuery = (Math.random() + 1).toString(36).substring(7);
      me.setData(getCoordinate(evt.coordinate), 'coordinates', true);
      me.last_coordinate_clicked = evt.coordinate; //It is used in some examples and apps
      $rootScope.$broadcast('mapQueryStarted', evt);
    });

    if (
      angular.isDefined(HsConfig.popUpDisplay) &&
      HsConfig.popUpDisplay === 'hover'
    ) {
      map.on(
        'pointermove',
        HsUtilsService.debounce(me.showPopUp, 500, false, me)
      );
    } else if (
      angular.isDefined(HsConfig.popUpDisplay) &&
      HsConfig.popUpDisplay === 'click'
    ) {
      map.on(
        'singleclick',
        HsUtilsService.debounce(me.showPopUp, 500, false, me)
      );
    } /* else none */
  }

  /**
   * @param e Event, which triggered this function
   */
  this.showPopUp = function (e) {
    if (e.dragging) {
      return;
    }
    const map = e.map;
    $timeout((_) => {
      me.featuresUnderMouse = map.getFeaturesAtPixel(e.pixel);
      if (me.featuresUnderMouse !== null) {
        me.featuresUnderMouse = me.featuresUnderMouse.filter((feature) => {
          return (
            feature.getLayer &&
            feature.getLayer(map) &&
            feature.getLayer(map).get('title').length > 0 &&
            feature.getLayer(map).get('title') !== 'Point clicked'
          );
        });
        me.featureLayersUnderMouse = me.featuresUnderMouse.map((f) =>
          f.getLayer(HsMapService.map)
        );
        me.featureLayersUnderMouse = HsUtilsService.removeDuplicates(
          me.featureLayersUnderMouse,
          'title'
        );
        me.featureLayersUnderMouse = me.featureLayersUnderMouse.map((l) => {
          return {
            layer: l.get('title'),
            features: me.featuresUnderMouse.filter(
              (f) => f.getLayer(HsMapService.map) == l
            ),
          };
        });
        me.featuresUnderMouse.forEach((feature) => {
          me.serializeFeatureAttributes(feature);
          if (feature.get('features')) {
            feature
              .get('features')
              .forEach((subfeature) =>
                me.serializeFeatureAttributes(subfeature)
              );
          }
        });
        const pixel = e.pixel;
        pixel[0] += 2;
        pixel[1] += 4;
        me.hoverPopup.setPosition(map.getCoordinateFromPixel(pixel));
      } else {
        me.featuresUnderMouse = [];
      }
    }, 0);
  };

  /**
   * @param feature
   */
  this.serializeFeatureAttributes = function (feature) {
    if (angular.isUndefined(feature.getLayer)) {
      return;
    }
    const layer = feature.getLayer(HsMapService.map);
    let attrsConfig = [];
    if (
      angular.isDefined(layer.get('popUp')) &&
      angular.isDefined(layer.get('popUp').attributes)
    ) {
      //must be an array
      attrsConfig = layer.get('popUp').attributes;
    } else if (angular.isDefined(layer.get('hoveredKeys'))) {
      //only for backwards-compatibility with HSLayers 1.10 .. 1.22
      //should be dropped in future releases
      //expected to be an array
      attrsConfig = layer.get('hoveredKeys');
      if (angular.isDefined(layer.get('hoveredKeysTranslations'))) {
        //expected to be an object
        for (const [key, val] of Object.entries(
          layer.get('hoveredKeysTranslations')
        )) {
          const index = attrsConfig.indexOf(key);
          if (index > -1) {
            attrsConfig[index] = {
              'attribute': key,
              'label': val,
            };
          }
        }
      }
    } else {
      // Layer is not configured to show pop-ups
      return;
    }
    feature.attributesForHover = [];
    for (const attr of attrsConfig) {
      let attrName, attrLabel;
      let attrFunction = (x) => x;
      if (typeof attr === 'string' || attr instanceof String) {
        //simple case when only attribute name is provided in the layer config
        attrName = attr;
        attrLabel = attr;
      } else {
        if (angular.isUndefined(attr.attribute)) {
          //implies malformed layer config - 'attribute' is obligatory in this case
          continue;
        }
        attrName = attr.attribute;
        attrLabel = angular.isDefined(attr.label) ? attr.label : attr.attribute;
        if (angular.isDefined(attr.displayFunction)) {
          attrFunction = attr.displayFunction;
        }
      }
      if (angular.isDefined(feature.get(attrName))) {
        feature.attributesForHover.push({
          key: attrLabel,
          value: feature.get(attrName),
          displayFunction: attrFunction,
        });
      }
    }
  };

  HsMapService.loaded().then(init);

  this.setData = function (data, type, overwrite) {
    if (angular.isDefined(type)) {
      if (angular.isDefined(overwrite) && overwrite) {
        me.data[type].length = 0;
      }
      if (angular.isArray(data)) {
        me.data[type] = me.data[type].concat(data);
      } else {
        me.data[type].push(data);
      }
      $rootScope.$broadcast('infopanel.updated'); //Compatibility, deprecated
      $rootScope.$broadcast('query.dataUpdated', me.data);
    } else if (console) {
      console.log('Query.BaseService.setData type not passed');
    }
  };

  this.clearData = function (type) {
    if (type) {
      me.data[type].length = 0;
    } else {
      me.data.attributes.length = 0;
      me.data.features = [];
      me.data.coordinates.length = 0;
      me.data.featureInfoHtmls = [];
      me.data.customFeatures = [];
    }
    const invisiblePopup = me.getInvisiblePopup();
    if (invisiblePopup) {
      invisiblePopup.contentDocument.body.innerHTML = '';
      invisiblePopup.style.height = 0;
      invisiblePopup.style.width = 0;
    }
    me.dataCleared = true;
  };

  this.getInvisiblePopup = function () {
    return document.getElementById('invisible_popup');
  };

  this.pushFeatureInfoHtml = (html) => {
    me.data.featureInfoHtmls.push($sce.trustAsHtml(html));
    me.dataCleared = false;
  };

  this.fillIframeAndResize = function (iframe, response, append) {
    var iframe = me.getInvisiblePopup();
    if (append) {
      iframe.contentDocument.body.innerHTML += response;
    } else {
      iframe.contentDocument.body.innerHTML = response;
    }
    let tmp_width = iframe.contentDocument.innerWidth;
    if (
      tmp_width >
      HsLayoutService.contentWrapper.querySelector('.hs-ol-map').clientWidth -
        60
    ) {
      tmp_width =
        HsLayoutService.contentWrapper.querySelector('.hs-ol-map').clientWidth -
        60;
    }
    iframe.style.width = tmp_width + 'px';
    let tmp_height = iframe.contentDocument.innerHeight;
    if (tmp_height > 700) {
      tmp_height = 700;
    }
    iframe.style.height = tmp_height + 'px';
  };

  /**
   * @param coordinate
   */
  function getCoordinate(coordinate) {
    me.queryPoint.setCoordinates(coordinate, 'XY');
    const epsg4326Coordinate = transform(
      coordinate,
      map.getView().getProjection(),
      'EPSG:4326'
    );
    const coords = {
      name: gettext('Coordinates'),
      mapProjCoordinate: coordinate,
      epsg4326Coordinate,
      projections: [
        {
          'name': 'EPSG:4326',
          'value': toStringHDMS(epsg4326Coordinate),
        },
        {
          'name': 'EPSG:4326',
          'value': createStringXY(7)(epsg4326Coordinate),
        },
        {
          'name': map.getView().getProjection().getCode(),
          'value': createStringXY(7)(coordinate),
        },
      ],
    };
    return coords;
  }

  this.activateQueries = function () {
    if (me.queryActive) {
      return;
    }
    me.queryActive = true;
    HsMapService.loaded().then((map) => {
      map.addLayer(me.queryLayer);
      $rootScope.$broadcast('queryStatusChanged', true);
    });
  };

  this.deactivateQueries = function () {
    if (!me.queryActive) {
      return;
    }
    me.queryActive = false;
    HsMapService.loaded().then((map) => {
      map.removeLayer(me.queryLayer);
      $rootScope.$broadcast('queryStatusChanged', false);
    });
  };

  me.nonQueryablePanels = [
    'measure',
    'composition_browser',
    'analysis',
    'sensors',
    'draw'
  ];

  this.currentPanelQueryable = function () {
    return (
      me.nonQueryablePanels.indexOf(HsLayoutService.mainpanel) == -1 &&
      me.nonQueryablePanels.indexOf('*') == -1
    );
  };

  /**
   * @param feature
   */
  function pointClickedStyle(feature) {
    const defaultStyle = new Style({
      image: new Circle({
        fill: new Fill({
          color: 'rgba(255, 156, 156, 0.4)',
        }),
        stroke: new Stroke({
          color: '#cc3333',
          width: 1,
        }),
        radius: 5,
      }),
    });
    if (angular.isDefined(HsConfig.queryPoint)) {
      if (HsConfig.queryPoint == 'hidden') {
        defaultStyle.getImage().setRadius(0);
      } else if (HsConfig.queryPoint == 'notWithin') {
        if (me.selector.getFeatures().getLength() > 0) {
          defaultStyle.getImage().setRadius(0);
        }
      }
    }
    return defaultStyle;
  }

  if (me.deregisterVectorSelectorCreated) {
    me.deregisterVectorSelectorCreated();
  }
  me.deregisterVectorSelectorCreated = $rootScope.$on(
    'vectorSelectorCreated',
    (e, selector) => {
      me.selector = selector;
    }
  );
  return me;
}
<|endoftext|>


<commit_before>/*jshint node:true*/

'use strict';

module.exports = {
  normalizeEntityName: function() {
    // this prevents an error when the entityName is
    // not specified (since that doesn't actually matter
    // to us
  },

  afterInstall: function() {
    this.insertIntoFile('.jshintrc', '    "server",', {
      after: '"predef": [\n'
    });

    this.insertIntoFile('tests/.jshintrc', '    "server",', {
      after: '"predef": [\n'
    });

    return this.addBowerPackagesToProject([
      {name: 'pretender', target: '~0.7.0'},
      {name: 'lodash', target: '~3.7.0'},
      {name: 'Faker', target: '~3.0.0'}
    ]);
  }
};
<commit_msg>Ensure consuming apps depend on pretender 0.9<commit_after>/*jshint node:true*/

'use strict';

module.exports = {
  normalizeEntityName: function() {
    // this prevents an error when the entityName is
    // not specified (since that doesn't actually matter
    // to us
  },

  afterInstall: function() {
    this.insertIntoFile('.jshintrc', '    "server",', {
      after: '"predef": [\n'
    });

    this.insertIntoFile('tests/.jshintrc', '    "server",', {
      after: '"predef": [\n'
    });

    return this.addBowerPackagesToProject([
      {name: 'pretender', target: '~0.9.0'},
      {name: 'lodash', target: '~3.7.0'},
      {name: 'Faker', target: '~3.0.0'}
    ]);
  }
};
<|endoftext|>


<commit_before>module.exports = {
  normalizeEntityName: function() {
  },

  afterInstall: function() {
    return this.addBowerPackageToProject('ember-pusher', '0.1.0');
  }
};
<commit_msg>Update bower package version to 0.1.1<commit_after>module.exports = {
  normalizeEntityName: function() {
  },

  afterInstall: function() {
    return this.addBowerPackageToProject('ember-pusher', '0.1.1');
  }
};
<|endoftext|>