<commit_before>'use strict';

(() => {
  const DEFAULT_FETCH_INTERVAL_SEC = 600;
  const NOTIE_DISPLAY_SEC = 1.5;
  const COLOR_ICON_FILENAME_64 = 'redmine_icon_color_64.png';
  const BLACK_ICON_FILENAME_24 = 'redmine_icon_black_24.png';
  const BLACK_ICON_FILENAME_24_NOTIFICATION = 'redmine_icon_black_24_notification.png';
  const COLOR_ICON_FILENAME_24 = 'redmine_icon_color_24.png';
  const COLOR_ICON_FILENAME_24_NOTIFICATION = 'redmine_icon_color_24_notification.png';

  const electron = require('electron');
  const remote = electron.remote;
  const shell = remote.shell;
  const Menu = remote.Menu;
  const Tray = remote.Tray;
  const fs = require('fs');
  const notie = require('notie');
  const nodeNotifier = require('node-notifier');

  const FETCH_MODE = Object.freeze({ TIME: 'TIME', DATE: 'DATE' });

  let notifierScreen = null;

  /**
   * Class to handle settings screen.
   */
  class RedmineNotifierScreen {
    /**
     * Initialize the RedmineNotifierScreen object.
     * @constructor
     */
    constructor() {
      this._notifiers = null;
      this._currentNotifierIndex = null;
      this._tray = null;
      this._contextMenu = null;
      this._mostRecentNotifierIndex = null;

      if (process.platform === 'darwin') {
        this._iconFilePath             = `${__dirname}/images/${BLACK_ICON_FILENAME_24}`;
        this._notificationIconFilePath = `${__dirname}/images/${BLACK_ICON_FILENAME_24_NOTIFICATION}`;
      } else {
        this._iconFilePath             = `${__dirname}/images/${COLOR_ICON_FILENAME_24}`;
        this._notificationIconFilePath = `${__dirname}/images/${COLOR_ICON_FILENAME_24_NOTIFICATION}`;
      }
    }

    /**
     * Initialize the RedmineNotifier objects.
     * @param {RedmineNotifier[]} notifiers - RedmineNotifier objects.
     * @return {Object} Current object.
     */
    initNotifiers(notifiers) {
      this._notifiers = notifiers;
      this._currentNotifierIndex = 0;
      return this;
    }

    /**
     * Initialize the application menu and context menu.
     * @return {Object} Current object.
     */
    initMenu() {
      const appMenu = Menu.buildFromTemplate([
        {
          label: 'Edit',
          submenu: [
            { role: 'undo' },
            { role: 'redo' },
            { role: 'cut' },
            { role: 'copy' },
            { role: 'paste' },
            { role: 'selectall' }
          ]
        }
      ]);

      this._contextMenu = Menu.buildFromTemplate([
        {
          label: 'Open Most Recent Issue in Browser',
          click: () => {
            const notifier = this._notifiers[this._mostRecentNotifierIndex];
            shell.openExternal(`${notifier._settings.url}/issues/${notifier._mostRecentIssueId}`);
            notifierScreen.setNormalIcon();
          },
          enabled: false
        },
        {
          label: 'Preferences',
          click: () => {
            remote.getCurrentWindow().show();
          }
        },
        {
          label: 'Quit',
          click: () => {
            remote.app.quit();
          }
        }
      ]);

      Menu.setApplicationMenu(appMenu);

      this._tray = new Tray(this._iconFilePath);
      this._tray.setContextMenu(this._contextMenu);

      return this;
    }

    /**
     * Initialize the event listeners.
     * @return {Object} Current object.
     */
    initEventListener() {
      document.getElementById('save-button').addEventListener('click', () => {
        const notifier = this._notifiers[this._currentNotifierIndex];
        notifier.readScreenSettings();

        if (notifier.validateSettings()) {
          notifier.initFetch()
            .updateSettings();
          notie.alert('success', 'Settings have been saved.', NOTIE_DISPLAY_SEC);
        } else {
          notifier.readStoredSettings();
        }
      });

      document.getElementById('close-button').addEventListener('click', () => {
        const notifier = this._notifiers[this._currentNotifierIndex];
        notifier.readStoredSettings()
          .displaySettings();
        remote.getCurrentWindow().hide();
      });

      document.getElementById('test-connection-button').addEventListener('click', () => {
        const notifier = this._notifiers[this._currentNotifierIndex];
        notifier.testConnection(FETCH_MODE.TIME);
      });

      document.getElementById('other-urls-button').addEventListener('click', () => {
        this.openURLMenu();
      });

      document.getElementById('delete-link').addEventListener('click', () => {
        notie.confirm('Are you sure you want to delete this setting?', 'Yes', 'No', () => {
          const notifier = this._notifiers[this._currentNotifierIndex];
          notifier.deleteStoredSettings()
            .readStoredSettings()
            .displaySettings();
          notie.alert('success', 'Settings have been deleted.', NOTIE_DISPLAY_SEC);
        });
      });

      return this;
    }

    /**
     * Display the default settings on the screen.
     * @return {Object} Current object.
     */
    displayDefaultSettings() {
      document.getElementById('default-fetch-interval-sec').innerHTML = DEFAULT_FETCH_INTERVAL_SEC;
      return this;
    }

    /**
     * Open the URL menu.
     * @return {Object} Current object.
     */
    openURLMenu() {
      notie.select('Stored URLs', 'Cancel',
        [
          {
            title: this._notifiers[0].getStoredSetting('url'),
            color: '#628db6',
            handler: () => {
              this._currentNotifierIndex = 0;
              const notifier = this._notifiers[this._currentNotifierIndex];
              notifier.readStoredSettings()
                .displaySettings();
            }
          },
          {
            title: this._notifiers[1].getStoredSetting('url'),
            color: '#628db6',
            handler: () => {
              this._currentNotifierIndex = 1;
              const notifier = this._notifiers[this._currentNotifierIndex];
              notifier.readStoredSettings()
                .displaySettings();
            }
          }
        ]
      );

      return this;
    }

    /**
     * Set normal icon and disable "Open Most Recent Issue in Browser" in context menu.
     * @return {Object} Current object.
     */
    setNormalIcon() {
      this._tray.setImage(this._iconFilePath);
      this._contextMenu.items[0].enabled = false;
      this._mostRecentNotifierIndex = null;
      return this;
    }

    /**
     * Set notification icon and enable "Open Most Recent Issue in Browser" in context menu.
     * @param {number} index - Index of the most recent RedmineNotifier object.
     * @return {Object} Current object.
     */
    setNotificationIcon(index) {
      this._tray.setImage(this._notificationIconFilePath);
      this._contextMenu.items[0].enabled = true;
      this._mostRecentNotifierIndex = index;
      return this;
    }
  }

  /**
   * Class to check updated issues.
   */
  class RedmineNotifier {
    /**
     * Initialize the RedmineNotifier object.
     * @constructor
     * @param {number} index - Index of the object.
     */
    constructor(index) {
      this._index = index;
      this._lastExecutionTime = null;
      this._settings = null;
      this._fetchTimer = null;
      this._fetchMode = null;
      this._mostRecentIssueId = null;
    }

    /**
     * Display the settings on the screen.
     * @return {Object} Current object.
     */
    displaySettings() {
      document.getElementById('url').value = this._settings.url;
      document.getElementById('api-key').value = this._settings.apiKey;
      document.getElementById('project-id').value = this._settings.projectId;
      document.getElementById('fetch-interval-sec').value = this._settings.fetchIntervalSec;
      return this;
    }

    /**
     * Get the settings from the screen.
     * @return {Object} Settings.
     */
    getPageSettings() {
      return {
        url: document.getElementById('url').value,
        apiKey: document.getElementById('api-key').value,
        projectId: document.getElementById('project-id').value,
        fetchIntervalSec: document.getElementById('fetch-interval-sec').value
      };
    }

    /**
     * Read the settings from the screen.
     * @return {Object} Current object.
     */
    readScreenSettings() {
      this._settings = this.getPageSettings();
      return this;
    }

    /**
     * Read the settings from the localStorage.
     * @return {Object} Current object.
     */
    readStoredSettings() {
      this._settings = {
        url: localStorage.getItem(`url${this._index}`),
        apiKey: localStorage.getItem(`apiKey${this._index}`),
        projectId: localStorage.getItem(`projectId${this._index}`),
        fetchIntervalSec: localStorage.getItem(`fetchIntervalSec${this._index}`)
      };

      return this;
    }

    /**
     * Get the setting from the localStorage.
     * @param {string} key - Setting key.
     * @return {string} Setting value.
     */
    getStoredSetting(key) {
      return localStorage.getItem(`${key}${this._index}`);
    }

    /**
     * Update the stored last execution time.
     * @return {Object} Current object.
     */
    updateLastExecutionTime() {
      this._lastExecutionTime = (new Date()).toISOString().replace(/\.\d+Z$/, 'Z');
      localStorage.setItem(`lastExecutionTime${this._index}`, this._lastExecutionTime);
      return this;
    }

    /**
     * Update the stored settings.
     * @return {Object} Current object.
     */
    updateSettings() {
      localStorage.setItem(`url${this._index}`, this._settings.url);
      localStorage.setItem(`apiKey${this._index}`, this._settings.apiKey);
      localStorage.setItem(`projectId${this._index}`, this._settings.projectId);
      localStorage.setItem(`fetchIntervalSec${this._index}`, this._settings.fetchIntervalSec);
      return this;
    }

    /**
     * Delete the settings.
     * @return {Object} Current object.
     */
    deleteStoredSettings() {
      localStorage.removeItem(`url${this._index}`);
      localStorage.removeItem(`apiKey${this._index}`);
      localStorage.removeItem(`projectId${this._index}`);
      localStorage.removeItem(`fetchIntervalSec${this._index}`);
      return this;
    }

    /**
     * Validate the settings.
     * @return {boolean} true if valid.
     */
    validateSettings() {
      if (this._settings.url && this._settings.apiKey) {
        return true;
      } else {
        notie.alert('error', 'Please enter required fields.', NOTIE_DISPLAY_SEC);
        return false;
      }
    }

    /**
     * Initialize the fetch function.
     * @return {Object} Current object.
     */
    initFetch() {
      const intervalMsec = 1000 * (this._settings.fetchIntervalSec || DEFAULT_FETCH_INTERVAL_SEC);

      clearInterval(this._fetchTimer);

      this._fetchTimer = setInterval(() => {
        this.fetch(this._fetchMode || FETCH_MODE.TIME);
      }, intervalMsec);

      return this;
    }

    /**
     * Fetch updated issues by using Redmine REST API.
     * @param {string} mode - Time or date.
     * @return {Object} Current object.
     */
    fetch(mode) {
      const xhr = new XMLHttpRequest();

      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4) {
          this.handleResponseFetch(mode, xhr.status, xhr.responseText);
        }
      };

      xhr.open('GET', `${this._settings.url}/issues.json${this.getRequestParams(mode, this._settings.projectId)}`);
      xhr.setRequestHeader('X-Redmine-API-Key', this._settings.apiKey);
      xhr.send();

      return this;
    }

    /**
     * Handle the response for the fetch.
     * @param {string} mode - Time or date.
     * @param {number} status - Response status.
     * @param {string} responseText - Response text.
     * @return {Object} Current object.
     */
    handleResponseFetch(mode, status, responseText) {
      if (mode === FETCH_MODE.TIME) {
        if (status === 200) {
          this.notify(JSON.parse(responseText).issues)
            .updateLastExecutionTime();
        } else if (status === 422) {
          // Retry with date mode if Redmine API doesn't accept time format
          this._fetchMode = FETCH_MODE.DATE;
          this.fetch(FETCH_MODE.DATE);
        }
      } else {
        if (status === 200) {
          this.notify(this.pickIssues(JSON.parse(responseText).issues));
        }

        this.updateLastExecutionTime();
      }

      return this;
    }

    /**
     * Get issues which were updated after last execution time.
     * @param {string} responseIssues - Response issues.
     * @return {Object[]} Processed issues.
     */
    pickIssues(responseIssues) {
      const lastExecutionTime = new Date(this._lastExecutionTime).getTime();

      const issues = responseIssues.filter((issue) => {
        const updatedTime = new Date(issue.updated_on).getTime();
        return updatedTime >= lastExecutionTime;
      });

      return issues;
    }

    /**
     * Test the connection to the Redmine.
     * @param {string} mode - Time or date.
     * @return {Object} Current object.
     */
    testConnection(mode) {
      const xhr = new XMLHttpRequest();
      const pageSettings = this.getPageSettings();

      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4) {
          this.handleResponseTestConnection(mode, xhr.status);
        }
      };

      xhr.open('GET', `${pageSettings.url}/issues.json${this.getRequestParams(mode, pageSettings.projectId)}`);
      xhr.setRequestHeader('X-Redmine-API-Key', pageSettings.apiKey);
      xhr.send();

      return this;
    }

    /**
     * Handle the response for the test connection.
     * @param {string} mode - Time or date.
     * @param {number} status - Response status.
     * @return {Object} Current object.
     */
    handleResponseTestConnection(mode, status) {
      if (status === 200) {
        notie.alert('success', 'Connection succeeded.', NOTIE_DISPLAY_SEC);
        return this;
      }

      // Retry with date mode if Redmine API doesn't accept time format
      if (mode === FETCH_MODE.TIME && status === 422) {
        this.testConnection(FETCH_MODE.DATE);
        return this;
      }

      notie.alert('error', 'Connection failed.', NOTIE_DISPLAY_SEC);

      return this;
    }

    /**
     * Get the request parameters.
     * @param {string} mode - Time or date.
     * @param {string} projectId - Project ID (a numeric value, not a project identifier).
     * @return {string} Request parameters.
     */
    getRequestParams(mode, projectId) {
      const params = [
        `updated_on=%3E%3D${this.getLastExecutionTime(mode)}`,
        'sort=updated_on:desc'
      ];

      if (typeof projectId === 'string' && projectId !== '') {
        params.unshift(`project_id=${projectId}`);
      }

      return `?${params.join('&')}`;
    }

    /**
     * Get last execution time by mode.
     * @param {string} mode - Time or date.
     * @return {string} Last execution time.
     */
    getLastExecutionTime(mode) {
      if (mode === FETCH_MODE.TIME) {
        return this._lastExecutionTime;
      } else {
        return this._lastExecutionTime.replace(/T.*/, ''); // Date
      }
    }

    /**
     * Send the desktop notification.
     * @param {Object} issues - All of updated issues.
     * @return {Object} Current object.
     */
    notify(issues) {
      const issueCount = issues.length;

      if (issueCount === 0) return this;

      let appDir = `${__dirname}.unpacked`; // Production
      try {
        fs.statSync(appDir);
      } catch(e) {
        appDir = __dirname; // Development
      }

      this._mostRecentIssueId = issues[0].id;
      notifierScreen.setNotificationIcon(this._index);

      // Display the latest issue's subject only
      nodeNotifier.notify({
        title: `(${issueCount}) Redmine Notifier`,
        message: issues[0].subject,
        icon: `${appDir}/images/${COLOR_ICON_FILENAME_64}`,
        wait: true
      });

      nodeNotifier.removeAllListeners();

      nodeNotifier.once('click', () => {
        shell.openExternal(`${this._settings.url}/issues/${this._mostRecentIssueId}`);
        notifierScreen.setNormalIcon();
        nodeNotifier.removeAllListeners();
      });

      nodeNotifier.once('timeout', () => {
        nodeNotifier.removeAllListeners();
      });

      return this;
    }
  }

  window.addEventListener('load', () => {
    notie.setOptions({ colorInfo: '#3e5b76' });

    const notifier1 = new RedmineNotifier(0);
    notifier1.updateLastExecutionTime()
      .readStoredSettings()
      .displaySettings();

    if (notifier1.validateSettings()) {
      notifier1.initFetch();
    }

    const notifier2 = new RedmineNotifier(1);
    notifier2.updateLastExecutionTime()
      .readStoredSettings();

    if (notifier2.validateSettings()) {
      notifier2.initFetch();
    }

    notifierScreen = new RedmineNotifierScreen();
    notifierScreen.initNotifiers([notifier1, notifier2])
      .initMenu()
      .initEventListener()
      .displayDefaultSettings();
  });
})();

<commit_msg>Delete settings of old version<commit_after>'use strict';

(() => {
  const DEFAULT_FETCH_INTERVAL_SEC = 600;
  const NOTIE_DISPLAY_SEC = 1.5;
  const COLOR_ICON_FILENAME_64 = 'redmine_icon_color_64.png';
  const BLACK_ICON_FILENAME_24 = 'redmine_icon_black_24.png';
  const BLACK_ICON_FILENAME_24_NOTIFICATION = 'redmine_icon_black_24_notification.png';
  const COLOR_ICON_FILENAME_24 = 'redmine_icon_color_24.png';
  const COLOR_ICON_FILENAME_24_NOTIFICATION = 'redmine_icon_color_24_notification.png';

  const electron = require('electron');
  const remote = electron.remote;
  const shell = remote.shell;
  const Menu = remote.Menu;
  const Tray = remote.Tray;
  const fs = require('fs');
  const notie = require('notie');
  const nodeNotifier = require('node-notifier');

  const FETCH_MODE = Object.freeze({ TIME: 'TIME', DATE: 'DATE' });

  let notifierScreen = null;

  /**
   * Class to handle settings screen.
   */
  class RedmineNotifierScreen {
    /**
     * Initialize the RedmineNotifierScreen object.
     * @constructor
     */
    constructor() {
      this._notifiers = null;
      this._currentNotifierIndex = null;
      this._tray = null;
      this._contextMenu = null;
      this._mostRecentNotifierIndex = null;

      if (process.platform === 'darwin') {
        this._iconFilePath             = `${__dirname}/images/${BLACK_ICON_FILENAME_24}`;
        this._notificationIconFilePath = `${__dirname}/images/${BLACK_ICON_FILENAME_24_NOTIFICATION}`;
      } else {
        this._iconFilePath             = `${__dirname}/images/${COLOR_ICON_FILENAME_24}`;
        this._notificationIconFilePath = `${__dirname}/images/${COLOR_ICON_FILENAME_24_NOTIFICATION}`;
      }
    }

    /**
     * Initialize the RedmineNotifier objects.
     * @param {RedmineNotifier[]} notifiers - RedmineNotifier objects.
     * @return {Object} Current object.
     */
    initNotifiers(notifiers) {
      this._notifiers = notifiers;
      this._currentNotifierIndex = 0;
      return this;
    }

    /**
     * Initialize the application menu and context menu.
     * @return {Object} Current object.
     */
    initMenu() {
      const appMenu = Menu.buildFromTemplate([
        {
          label: 'Edit',
          submenu: [
            { role: 'undo' },
            { role: 'redo' },
            { role: 'cut' },
            { role: 'copy' },
            { role: 'paste' },
            { role: 'selectall' }
          ]
        }
      ]);

      this._contextMenu = Menu.buildFromTemplate([
        {
          label: 'Open Most Recent Issue in Browser',
          click: () => {
            const notifier = this._notifiers[this._mostRecentNotifierIndex];
            shell.openExternal(`${notifier._settings.url}/issues/${notifier._mostRecentIssueId}`);
            notifierScreen.setNormalIcon();
          },
          enabled: false
        },
        {
          label: 'Preferences',
          click: () => {
            remote.getCurrentWindow().show();
          }
        },
        {
          label: 'Quit',
          click: () => {
            remote.app.quit();
          }
        }
      ]);

      Menu.setApplicationMenu(appMenu);

      this._tray = new Tray(this._iconFilePath);
      this._tray.setContextMenu(this._contextMenu);

      return this;
    }

    /**
     * Initialize the event listeners.
     * @return {Object} Current object.
     */
    initEventListener() {
      document.getElementById('save-button').addEventListener('click', () => {
        const notifier = this._notifiers[this._currentNotifierIndex];
        notifier.readScreenSettings();

        if (notifier.validateSettings()) {
          notifier.initFetch()
            .updateSettings();
          notie.alert('success', 'Settings have been saved.', NOTIE_DISPLAY_SEC);
        } else {
          notifier.readStoredSettings();
        }
      });

      document.getElementById('close-button').addEventListener('click', () => {
        const notifier = this._notifiers[this._currentNotifierIndex];
        notifier.readStoredSettings()
          .displaySettings();
        remote.getCurrentWindow().hide();
      });

      document.getElementById('test-connection-button').addEventListener('click', () => {
        const notifier = this._notifiers[this._currentNotifierIndex];
        notifier.testConnection(FETCH_MODE.TIME);
      });

      document.getElementById('other-urls-button').addEventListener('click', () => {
        this.openURLMenu();
      });

      document.getElementById('delete-link').addEventListener('click', () => {
        notie.confirm('Are you sure you want to delete this setting?', 'Yes', 'No', () => {
          const notifier = this._notifiers[this._currentNotifierIndex];
          notifier.deleteStoredSettings()
            .readStoredSettings()
            .displaySettings();
          notie.alert('success', 'Settings have been deleted.', NOTIE_DISPLAY_SEC);
        });
      });

      return this;
    }

    /**
     * Display the default settings on the screen.
     * @return {Object} Current object.
     */
    displayDefaultSettings() {
      document.getElementById('default-fetch-interval-sec').innerHTML = DEFAULT_FETCH_INTERVAL_SEC;
      return this;
    }

    /**
     * Open the URL menu.
     * @return {Object} Current object.
     */
    openURLMenu() {
      notie.select('Stored URLs', 'Cancel',
        [
          {
            title: this._notifiers[0].getStoredSetting('url'),
            color: '#628db6',
            handler: () => {
              this._currentNotifierIndex = 0;
              const notifier = this._notifiers[this._currentNotifierIndex];
              notifier.readStoredSettings()
                .displaySettings();
            }
          },
          {
            title: this._notifiers[1].getStoredSetting('url'),
            color: '#628db6',
            handler: () => {
              this._currentNotifierIndex = 1;
              const notifier = this._notifiers[this._currentNotifierIndex];
              notifier.readStoredSettings()
                .displaySettings();
            }
          }
        ]
      );

      return this;
    }

    /**
     * Set normal icon and disable "Open Most Recent Issue in Browser" in context menu.
     * @return {Object} Current object.
     */
    setNormalIcon() {
      this._tray.setImage(this._iconFilePath);
      this._contextMenu.items[0].enabled = false;
      this._mostRecentNotifierIndex = null;
      return this;
    }

    /**
     * Set notification icon and enable "Open Most Recent Issue in Browser" in context menu.
     * @param {number} index - Index of the most recent RedmineNotifier object.
     * @return {Object} Current object.
     */
    setNotificationIcon(index) {
      this._tray.setImage(this._notificationIconFilePath);
      this._contextMenu.items[0].enabled = true;
      this._mostRecentNotifierIndex = index;
      return this;
    }
  }

  /**
   * Class to check updated issues.
   */
  class RedmineNotifier {
    /**
     * Initialize the RedmineNotifier object.
     * @constructor
     * @param {number} index - Index of the object.
     */
    constructor(index) {
      this._index = index;
      this._lastExecutionTime = null;
      this._settings = null;
      this._fetchTimer = null;
      this._fetchMode = null;
      this._mostRecentIssueId = null;
    }

    /**
     * Display the settings on the screen.
     * @return {Object} Current object.
     */
    displaySettings() {
      document.getElementById('url').value = this._settings.url;
      document.getElementById('api-key').value = this._settings.apiKey;
      document.getElementById('project-id').value = this._settings.projectId;
      document.getElementById('fetch-interval-sec').value = this._settings.fetchIntervalSec;
      return this;
    }

    /**
     * Get the settings from the screen.
     * @return {Object} Settings.
     */
    getPageSettings() {
      return {
        url: document.getElementById('url').value,
        apiKey: document.getElementById('api-key').value,
        projectId: document.getElementById('project-id').value,
        fetchIntervalSec: document.getElementById('fetch-interval-sec').value
      };
    }

    /**
     * Read the settings from the screen.
     * @return {Object} Current object.
     */
    readScreenSettings() {
      this._settings = this.getPageSettings();
      return this;
    }

    /**
     * Read the settings from the localStorage.
     * @return {Object} Current object.
     */
    readStoredSettings() {
      this._settings = {
        url: localStorage.getItem(`url${this._index}`),
        apiKey: localStorage.getItem(`apiKey${this._index}`),
        projectId: localStorage.getItem(`projectId${this._index}`),
        fetchIntervalSec: localStorage.getItem(`fetchIntervalSec${this._index}`)
      };

      return this;
    }

    /**
     * Get the setting from the localStorage.
     * @param {string} key - Setting key.
     * @return {string} Setting value.
     */
    getStoredSetting(key) {
      return localStorage.getItem(`${key}${this._index}`);
    }

    /**
     * Update the stored last execution time.
     * @return {Object} Current object.
     */
    updateLastExecutionTime() {
      this._lastExecutionTime = (new Date()).toISOString().replace(/\.\d+Z$/, 'Z');
      localStorage.setItem(`lastExecutionTime${this._index}`, this._lastExecutionTime);
      return this;
    }

    /**
     * Update the stored settings.
     * @return {Object} Current object.
     */
    updateSettings() {
      localStorage.setItem(`url${this._index}`, this._settings.url);
      localStorage.setItem(`apiKey${this._index}`, this._settings.apiKey);
      localStorage.setItem(`projectId${this._index}`, this._settings.projectId);
      localStorage.setItem(`fetchIntervalSec${this._index}`, this._settings.fetchIntervalSec);
      return this;
    }

    /**
     * Delete the settings.
     * @return {Object} Current object.
     */
    deleteStoredSettings() {
      localStorage.removeItem(`url${this._index}`);
      localStorage.removeItem(`apiKey${this._index}`);
      localStorage.removeItem(`projectId${this._index}`);
      localStorage.removeItem(`fetchIntervalSec${this._index}`);
      return this;
    }

    /**
     * Validate the settings.
     * @return {boolean} true if valid.
     */
    validateSettings() {
      if (this._settings.url && this._settings.apiKey) {
        return true;
      } else {
        notie.alert('error', 'Please enter required fields.', NOTIE_DISPLAY_SEC);
        return false;
      }
    }

    /**
     * Initialize the fetch function.
     * @return {Object} Current object.
     */
    initFetch() {
      const intervalMsec = 1000 * (this._settings.fetchIntervalSec || DEFAULT_FETCH_INTERVAL_SEC);

      clearInterval(this._fetchTimer);

      this._fetchTimer = setInterval(() => {
        this.fetch(this._fetchMode || FETCH_MODE.TIME);
      }, intervalMsec);

      return this;
    }

    /**
     * Fetch updated issues by using Redmine REST API.
     * @param {string} mode - Time or date.
     * @return {Object} Current object.
     */
    fetch(mode) {
      const xhr = new XMLHttpRequest();

      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4) {
          this.handleResponseFetch(mode, xhr.status, xhr.responseText);
        }
      };

      xhr.open('GET', `${this._settings.url}/issues.json${this.getRequestParams(mode, this._settings.projectId)}`);
      xhr.setRequestHeader('X-Redmine-API-Key', this._settings.apiKey);
      xhr.send();

      return this;
    }

    /**
     * Handle the response for the fetch.
     * @param {string} mode - Time or date.
     * @param {number} status - Response status.
     * @param {string} responseText - Response text.
     * @return {Object} Current object.
     */
    handleResponseFetch(mode, status, responseText) {
      if (mode === FETCH_MODE.TIME) {
        if (status === 200) {
          this.notify(JSON.parse(responseText).issues)
            .updateLastExecutionTime();
        } else if (status === 422) {
          // Retry with date mode if Redmine API doesn't accept time format
          this._fetchMode = FETCH_MODE.DATE;
          this.fetch(FETCH_MODE.DATE);
        }
      } else {
        if (status === 200) {
          this.notify(this.pickIssues(JSON.parse(responseText).issues));
        }

        this.updateLastExecutionTime();
      }

      return this;
    }

    /**
     * Get issues which were updated after last execution time.
     * @param {string} responseIssues - Response issues.
     * @return {Object[]} Processed issues.
     */
    pickIssues(responseIssues) {
      const lastExecutionTime = new Date(this._lastExecutionTime).getTime();

      const issues = responseIssues.filter((issue) => {
        const updatedTime = new Date(issue.updated_on).getTime();
        return updatedTime >= lastExecutionTime;
      });

      return issues;
    }

    /**
     * Test the connection to the Redmine.
     * @param {string} mode - Time or date.
     * @return {Object} Current object.
     */
    testConnection(mode) {
      const xhr = new XMLHttpRequest();
      const pageSettings = this.getPageSettings();

      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4) {
          this.handleResponseTestConnection(mode, xhr.status);
        }
      };

      xhr.open('GET', `${pageSettings.url}/issues.json${this.getRequestParams(mode, pageSettings.projectId)}`);
      xhr.setRequestHeader('X-Redmine-API-Key', pageSettings.apiKey);
      xhr.send();

      return this;
    }

    /**
     * Handle the response for the test connection.
     * @param {string} mode - Time or date.
     * @param {number} status - Response status.
     * @return {Object} Current object.
     */
    handleResponseTestConnection(mode, status) {
      if (status === 200) {
        notie.alert('success', 'Connection succeeded.', NOTIE_DISPLAY_SEC);
        return this;
      }

      // Retry with date mode if Redmine API doesn't accept time format
      if (mode === FETCH_MODE.TIME && status === 422) {
        this.testConnection(FETCH_MODE.DATE);
        return this;
      }

      notie.alert('error', 'Connection failed.', NOTIE_DISPLAY_SEC);

      return this;
    }

    /**
     * Get the request parameters.
     * @param {string} mode - Time or date.
     * @param {string} projectId - Project ID (a numeric value, not a project identifier).
     * @return {string} Request parameters.
     */
    getRequestParams(mode, projectId) {
      const params = [
        `updated_on=%3E%3D${this.getLastExecutionTime(mode)}`,
        'sort=updated_on:desc'
      ];

      if (typeof projectId === 'string' && projectId !== '') {
        params.unshift(`project_id=${projectId}`);
      }

      return `?${params.join('&')}`;
    }

    /**
     * Get last execution time by mode.
     * @param {string} mode - Time or date.
     * @return {string} Last execution time.
     */
    getLastExecutionTime(mode) {
      if (mode === FETCH_MODE.TIME) {
        return this._lastExecutionTime;
      } else {
        return this._lastExecutionTime.replace(/T.*/, ''); // Date
      }
    }

    /**
     * Send the desktop notification.
     * @param {Object} issues - All of updated issues.
     * @return {Object} Current object.
     */
    notify(issues) {
      const issueCount = issues.length;

      if (issueCount === 0) return this;

      let appDir = `${__dirname}.unpacked`; // Production
      try {
        fs.statSync(appDir);
      } catch(e) {
        appDir = __dirname; // Development
      }

      this._mostRecentIssueId = issues[0].id;
      notifierScreen.setNotificationIcon(this._index);

      // Display the latest issue's subject only
      nodeNotifier.notify({
        title: `(${issueCount}) Redmine Notifier`,
        message: issues[0].subject,
        icon: `${appDir}/images/${COLOR_ICON_FILENAME_64}`,
        wait: true
      });

      nodeNotifier.removeAllListeners();

      nodeNotifier.once('click', () => {
        shell.openExternal(`${this._settings.url}/issues/${this._mostRecentIssueId}`);
        notifierScreen.setNormalIcon();
        nodeNotifier.removeAllListeners();
      });

      nodeNotifier.once('timeout', () => {
        nodeNotifier.removeAllListeners();
      });

      return this;
    }
  }

  window.addEventListener('load', () => {
    // Delete settings of Redmine Notifier <= 0.6.0
    localStorage.removeItem('url');
    localStorage.removeItem('apiKey');
    localStorage.removeItem('projectId');
    localStorage.removeItem('fetchIntervalSec');
    localStorage.removeItem('lastExecutionTime');

    notie.setOptions({ colorInfo: '#3e5b76' });

    const notifier1 = new RedmineNotifier(0);
    notifier1.updateLastExecutionTime()
      .readStoredSettings()
      .displaySettings();

    if (notifier1.validateSettings()) {
      notifier1.initFetch();
    }

    const notifier2 = new RedmineNotifier(1);
    notifier2.updateLastExecutionTime()
      .readStoredSettings();

    if (notifier2.validateSettings()) {
      notifier2.initFetch();
    }

    notifierScreen = new RedmineNotifierScreen();
    notifierScreen.initNotifiers([notifier1, notifier2])
      .initMenu()
      .initEventListener()
      .displayDefaultSettings();
  });
})();

<|endoftext|>


<commit_before>/*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2017 Vector Creations 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';

import Matrix from 'matrix-js-sdk';

import utils from 'matrix-js-sdk/lib/utils';
import EventTimeline from 'matrix-js-sdk/lib/models/event-timeline';
import EventTimelineSet from 'matrix-js-sdk/lib/models/event-timeline-set';
import sdk from './index';
import createMatrixClient from './utils/createMatrixClient';
import SettingsStore from './settings/SettingsStore';
import MatrixActionCreators from './actions/MatrixActionCreators';
import {phasedRollOutExpiredForUser} from "./PhasedRollOut";
import Modal from './Modal';
import {verificationMethods} from 'matrix-js-sdk/lib/crypto';
import MatrixClientBackedSettingsHandler from "./settings/handlers/MatrixClientBackedSettingsHandler";
import * as StorageManager from './utils/StorageManager';
import IdentityAuthClient from './IdentityAuthClient';

interface MatrixClientCreds {
    homeserverUrl: string,
    identityServerUrl: string,
    userId: string,
    deviceId: string,
    accessToken: string,
    guest: boolean,
}

/**
 * Wrapper object for handling the js-sdk Matrix Client object in the react-sdk
 * Handles the creation/initialisation of client objects.
 * This module provides a singleton instance of this class so the 'current'
 * Matrix Client object is available easily.
 */
class MatrixClientPeg {
    constructor() {
        this.matrixClient = null;
        this._justRegisteredUserId = null;

        // These are the default options used when when the
        // client is started in 'start'. These can be altered
        // at any time up to after the 'will_start_client'
        // event is finished processing.
        this.opts = {
            initialSyncLimit: 20,
        };
        // the credentials used to init the current client object.
        // used if we tear it down & recreate it with a different store
        this._currentClientCreds = null;
    }

    /**
     * Sets the script href passed to the IndexedDB web worker
     * If set, a separate web worker will be started to run the IndexedDB
     * queries on.
     *
     * @param {string} script href to the script to be passed to the web worker
     */
    setIndexedDbWorkerScript(script) {
        createMatrixClient.indexedDbWorkerScript = script;
    }

    get(): MatrixClient {
        return this.matrixClient;
    }

    unset() {
        this.matrixClient = null;

        MatrixActionCreators.stop();
    }

    /*
     * If we've registered a user ID we set this to the ID of the
     * user we've just registered. If they then go & log in, we
     * can send them to the welcome user (obviously this doesn't
     * guarentee they'll get a chat with the welcome user).
     *
     * @param {string} uid The user ID of the user we've just registered
     */
    setJustRegisteredUserId(uid) {
        this._justRegisteredUserId = uid;
    }

    /*
     * Returns true if the current user has just been registered by this
     * client as determined by setJustRegisteredUserId()
     *
     * @returns {bool} True if user has just been registered
     */
    currentUserIsJustRegistered() {
        return (
            this.matrixClient &&
            this.matrixClient.credentials.userId === this._justRegisteredUserId
        );
    }

    /**
     * Replace this MatrixClientPeg's client with a client instance that has
     * homeserver / identity server URLs and active credentials
     */
    replaceUsingCreds(creds: MatrixClientCreds) {
        this._currentClientCreds = creds;
        this._createClient(creds);
    }

    async assign() {
        for (const dbType of ['indexeddb', 'memory']) {
            try {
                const promise = this.matrixClient.store.startup();
                console.log("MatrixClientPeg: waiting for MatrixClient store to initialise");
                await promise;
                break;
            } catch (err) {
                if (dbType === 'indexeddb') {
                    console.error('Error starting matrixclient store - falling back to memory store', err);
                    this.matrixClient.store = new Matrix.MemoryStore({
                        localStorage: global.localStorage,
                    });
                } else {
                    console.error('Failed to start memory store!', err);
                    throw err;
                }
            }
        }

        StorageManager.trackStores(this.matrixClient);

        // try to initialise e2e on the new client
        try {
            // check that we have a version of the js-sdk which includes initCrypto
            if (!SettingsStore.getValue("lowBandwidth") && this.matrixClient.initCrypto) {
                await this.matrixClient.initCrypto();
                StorageManager.setCryptoInitialised(true);
            }
        } catch (e) {
            if (e && e.name === 'InvalidCryptoStoreError') {
                // The js-sdk found a crypto DB too new for it to use
                const CryptoStoreTooNewDialog =
                    sdk.getComponent("views.dialogs.CryptoStoreTooNewDialog");
                Modal.createDialog(CryptoStoreTooNewDialog, {
                    host: window.location.host,
                });
            }
            // this can happen for a number of reasons, the most likely being
            // that the olm library was missing. It's not fatal.
            console.warn("Unable to initialise e2e", e);
        }

        const opts = utils.deepCopy(this.opts);
        // the react sdk doesn't work without this, so don't allow
        opts.pendingEventOrdering = "detached";
        opts.lazyLoadMembers = true;

        // Connect the matrix client to the dispatcher and setting handlers
        MatrixActionCreators.start(this.matrixClient);
        MatrixClientBackedSettingsHandler.matrixClient = this.matrixClient;

        return opts;
    }

    async start() {
        const opts = await this.assign();

        console.log(`MatrixClientPeg: really starting MatrixClient`);
        await this.get().startClient(opts);
        console.log(`MatrixClientPeg: MatrixClient started`);
    }

    getCredentials(): MatrixClientCreds {
        return {
            homeserverUrl: this.matrixClient.baseUrl,
            identityServerUrl: this.matrixClient.idBaseUrl,
            userId: this.matrixClient.credentials.userId,
            deviceId: this.matrixClient.getDeviceId(),
            accessToken: this.matrixClient.getAccessToken(),
            guest: this.matrixClient.isGuest(),
        };
    }

    /**
     * Return the server name of the user's homeserver
     * Throws an error if unable to deduce the homeserver name
     * (eg. if the user is not logged in)
     */
    getHomeserverName() {
        const matches = /^@.+:(.+)$/.exec(this.matrixClient.credentials.userId);
        if (matches === null || matches.length < 1) {
            throw new Error("Failed to derive homeserver name from user ID!");
        }
        return matches[1];
    }

    _createClient(creds: MatrixClientCreds) {
        const opts = {
            baseUrl: creds.homeserverUrl,
            idBaseUrl: creds.identityServerUrl,
            accessToken: creds.accessToken,
            userId: creds.userId,
            deviceId: creds.deviceId,
            timelineSupport: true,
            forceTURN: !SettingsStore.getValue('webRtcAllowPeerToPeer', false),
            fallbackICEServerAllowed: !!SettingsStore.getValue('fallbackICEServerAllowed'),
            verificationMethods: [verificationMethods.SAS],
            unstableClientRelationAggregation: true,
            getIdentityAccessToken: () => {
                return new IdentityAuthClient().getAccessToken();
            },
        };

        this.matrixClient = createMatrixClient(opts);

        // we're going to add eventlisteners for each matrix event tile, so the
        // potential number of event listeners is quite high.
        this.matrixClient.setMaxListeners(500);

        this.matrixClient.setGuest(Boolean(creds.guest));

        const notifTimelineSet = new EventTimelineSet(null, {
            timelineSupport: true,
        });
        // XXX: what is our initial pagination token?! it somehow needs to be synchronised with /sync.
        notifTimelineSet.getLiveTimeline().setPaginationToken("", EventTimeline.BACKWARDS);
        this.matrixClient.setNotifTimelineSet(notifTimelineSet);
    }
}

if (!global.mxMatrixClientPeg) {
    global.mxMatrixClientPeg = new MatrixClientPeg();
}
export default global.mxMatrixClientPeg;
<commit_msg>Change to provider object<commit_after>/*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2017 Vector Creations 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';

import Matrix from 'matrix-js-sdk';

import utils from 'matrix-js-sdk/lib/utils';
import EventTimeline from 'matrix-js-sdk/lib/models/event-timeline';
import EventTimelineSet from 'matrix-js-sdk/lib/models/event-timeline-set';
import sdk from './index';
import createMatrixClient from './utils/createMatrixClient';
import SettingsStore from './settings/SettingsStore';
import MatrixActionCreators from './actions/MatrixActionCreators';
import {phasedRollOutExpiredForUser} from "./PhasedRollOut";
import Modal from './Modal';
import {verificationMethods} from 'matrix-js-sdk/lib/crypto';
import MatrixClientBackedSettingsHandler from "./settings/handlers/MatrixClientBackedSettingsHandler";
import * as StorageManager from './utils/StorageManager';
import IdentityAuthClient from './IdentityAuthClient';

interface MatrixClientCreds {
    homeserverUrl: string,
    identityServerUrl: string,
    userId: string,
    deviceId: string,
    accessToken: string,
    guest: boolean,
}

/**
 * Wrapper object for handling the js-sdk Matrix Client object in the react-sdk
 * Handles the creation/initialisation of client objects.
 * This module provides a singleton instance of this class so the 'current'
 * Matrix Client object is available easily.
 */
class MatrixClientPeg {
    constructor() {
        this.matrixClient = null;
        this._justRegisteredUserId = null;

        // These are the default options used when when the
        // client is started in 'start'. These can be altered
        // at any time up to after the 'will_start_client'
        // event is finished processing.
        this.opts = {
            initialSyncLimit: 20,
        };
        // the credentials used to init the current client object.
        // used if we tear it down & recreate it with a different store
        this._currentClientCreds = null;
    }

    /**
     * Sets the script href passed to the IndexedDB web worker
     * If set, a separate web worker will be started to run the IndexedDB
     * queries on.
     *
     * @param {string} script href to the script to be passed to the web worker
     */
    setIndexedDbWorkerScript(script) {
        createMatrixClient.indexedDbWorkerScript = script;
    }

    get(): MatrixClient {
        return this.matrixClient;
    }

    unset() {
        this.matrixClient = null;

        MatrixActionCreators.stop();
    }

    /*
     * If we've registered a user ID we set this to the ID of the
     * user we've just registered. If they then go & log in, we
     * can send them to the welcome user (obviously this doesn't
     * guarentee they'll get a chat with the welcome user).
     *
     * @param {string} uid The user ID of the user we've just registered
     */
    setJustRegisteredUserId(uid) {
        this._justRegisteredUserId = uid;
    }

    /*
     * Returns true if the current user has just been registered by this
     * client as determined by setJustRegisteredUserId()
     *
     * @returns {bool} True if user has just been registered
     */
    currentUserIsJustRegistered() {
        return (
            this.matrixClient &&
            this.matrixClient.credentials.userId === this._justRegisteredUserId
        );
    }

    /**
     * Replace this MatrixClientPeg's client with a client instance that has
     * homeserver / identity server URLs and active credentials
     */
    replaceUsingCreds(creds: MatrixClientCreds) {
        this._currentClientCreds = creds;
        this._createClient(creds);
    }

    async assign() {
        for (const dbType of ['indexeddb', 'memory']) {
            try {
                const promise = this.matrixClient.store.startup();
                console.log("MatrixClientPeg: waiting for MatrixClient store to initialise");
                await promise;
                break;
            } catch (err) {
                if (dbType === 'indexeddb') {
                    console.error('Error starting matrixclient store - falling back to memory store', err);
                    this.matrixClient.store = new Matrix.MemoryStore({
                        localStorage: global.localStorage,
                    });
                } else {
                    console.error('Failed to start memory store!', err);
                    throw err;
                }
            }
        }

        StorageManager.trackStores(this.matrixClient);

        // try to initialise e2e on the new client
        try {
            // check that we have a version of the js-sdk which includes initCrypto
            if (!SettingsStore.getValue("lowBandwidth") && this.matrixClient.initCrypto) {
                await this.matrixClient.initCrypto();
                StorageManager.setCryptoInitialised(true);
            }
        } catch (e) {
            if (e && e.name === 'InvalidCryptoStoreError') {
                // The js-sdk found a crypto DB too new for it to use
                const CryptoStoreTooNewDialog =
                    sdk.getComponent("views.dialogs.CryptoStoreTooNewDialog");
                Modal.createDialog(CryptoStoreTooNewDialog, {
                    host: window.location.host,
                });
            }
            // this can happen for a number of reasons, the most likely being
            // that the olm library was missing. It's not fatal.
            console.warn("Unable to initialise e2e", e);
        }

        const opts = utils.deepCopy(this.opts);
        // the react sdk doesn't work without this, so don't allow
        opts.pendingEventOrdering = "detached";
        opts.lazyLoadMembers = true;

        // Connect the matrix client to the dispatcher and setting handlers
        MatrixActionCreators.start(this.matrixClient);
        MatrixClientBackedSettingsHandler.matrixClient = this.matrixClient;

        return opts;
    }

    async start() {
        const opts = await this.assign();

        console.log(`MatrixClientPeg: really starting MatrixClient`);
        await this.get().startClient(opts);
        console.log(`MatrixClientPeg: MatrixClient started`);
    }

    getCredentials(): MatrixClientCreds {
        return {
            homeserverUrl: this.matrixClient.baseUrl,
            identityServerUrl: this.matrixClient.idBaseUrl,
            userId: this.matrixClient.credentials.userId,
            deviceId: this.matrixClient.getDeviceId(),
            accessToken: this.matrixClient.getAccessToken(),
            guest: this.matrixClient.isGuest(),
        };
    }

    /**
     * Return the server name of the user's homeserver
     * Throws an error if unable to deduce the homeserver name
     * (eg. if the user is not logged in)
     */
    getHomeserverName() {
        const matches = /^@.+:(.+)$/.exec(this.matrixClient.credentials.userId);
        if (matches === null || matches.length < 1) {
            throw new Error("Failed to derive homeserver name from user ID!");
        }
        return matches[1];
    }

    _createClient(creds: MatrixClientCreds) {
        const opts = {
            baseUrl: creds.homeserverUrl,
            idBaseUrl: creds.identityServerUrl,
            accessToken: creds.accessToken,
            userId: creds.userId,
            deviceId: creds.deviceId,
            timelineSupport: true,
            forceTURN: !SettingsStore.getValue('webRtcAllowPeerToPeer', false),
            fallbackICEServerAllowed: !!SettingsStore.getValue('fallbackICEServerAllowed'),
            verificationMethods: [verificationMethods.SAS],
            unstableClientRelationAggregation: true,
            identityServer: new IdentityAuthClient(),
        };

        this.matrixClient = createMatrixClient(opts);

        // we're going to add eventlisteners for each matrix event tile, so the
        // potential number of event listeners is quite high.
        this.matrixClient.setMaxListeners(500);

        this.matrixClient.setGuest(Boolean(creds.guest));

        const notifTimelineSet = new EventTimelineSet(null, {
            timelineSupport: true,
        });
        // XXX: what is our initial pagination token?! it somehow needs to be synchronised with /sync.
        notifTimelineSet.getLiveTimeline().setPaginationToken("", EventTimeline.BACKWARDS);
        this.matrixClient.setNotifTimelineSet(notifTimelineSet);
    }
}

if (!global.mxMatrixClientPeg) {
    global.mxMatrixClientPeg = new MatrixClientPeg();
}
export default global.mxMatrixClientPeg;
<|endoftext|>


<commit_before>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');

var CordovaGenerator = module.exports = function CordovaGenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);

  this.on('end', function () {
    this.installDependencies({ skipInstall: options['skip-install'] });
  });

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(CordovaGenerator, yeoman.generators.NamedBase);

CordovaGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  // welcome message
  var welcome =
  '\n     _-----_' +
  '\n    |       |' +
  '\n    |' + '--(o)--'.red + '|   .--------------------------.' +
  '\n   `---------´  |    ' + 'Welcome to Yeoman,'.yellow.bold + '    |' +
  '\n    ' + '( '.yellow + '_' + '´U`'.yellow + '_' + ' )'.yellow + '   |   ' + 'ladies and gentlemen!'.yellow.bold + '  |' +
  '\n    /___A___\\   \'__________________________\'' +
  '\n     |  ~  |'.yellow +
  '\n   __' + '\'.___.\''.yellow + '__' +
  '\n ´   ' + '`  |'.red + '° ' + '´ Y'.red + ' `\n';

  console.log(welcome);

  var prompts = [{
    name: 'someOption',
    message: 'Would you like to enable this option?',
    default: 'Y/n',
    warning: 'Yes: Enabling this will be totally awesome!'
  }];

  this.prompt(prompts, function (err, props) {
    if (err) {
      return this.emit('error', err);
    }

    this.someOption = (/y/i).test(props.someOption);

    cb();
  }.bind(this));
};

CordovaGenerator.prototype.app = function app() {
  this.mkdir('app');
  this.mkdir('app/templates');

  this.copy('_package.json', 'package.json');
  this.copy('_component.json', 'component.json');
};

CordovaGenerator.prototype.projectfiles = function projectfiles() {
  this.copy('editorconfig', '.editorconfig');
  this.copy('jshintrc', '.jshintrc');
};
<commit_msg>Started actual work into index.js.<commit_after>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');

var CordovaGenerator = module.exports = function CordovaGenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);

  this.on('end', function () {
    this.installDependencies({ skipInstall: options['skip-install'] });
  });

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(CordovaGenerator, yeoman.generators.NamedBase);

CordovaGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  // welcome message
  var welcome =
  '\n     _-----_' +
  '\n    |       |' +
  '\n    |' + '--(o)--'.red + '|   .--------------------------.' +
  '\n   `---------´  |    ' + 'Welcome to Yeoman,'.yellow.bold + '    |' +
  '\n    ' + '( '.yellow + '_' + '´U`'.yellow + '_' + ' )'.yellow + '   |   ' + 'ladies and gentlemen!'.yellow.bold + '  |' +
  '\n    /___A___\\   \'__________________________\'' +
  '\n     |  ~  |'.yellow +
  '\n   __' + '\'.___.\''.yellow + '__' +
  '\n ´   ' + '`  |'.red + '° ' + '´ Y'.red + ' `\n' +
  '\n\nYeoman Cordova (Phonegap upstream) Generator'.red;

  console.log(welcome);

  var prompts = [{
    name: 'projectName',
    message: 'What is the name of your app?',
    default: 'Some App'
  },
  {
    name: 'iosApp',
    message: 'Would you like to scaffold iOS?',
    default: 'Y/n'
  },
  {
    name: 'androidApp',
    message: 'Would you like to scaffold Android?',
    default: 'Y/n'
  },
  {
    name: 'blackberryApp',
    message: 'Would you like to scaffold Blackberry?',
    default: 'Y/n'
  },];

  this.prompt(prompts, function (err, props) {
    if (err) {
      return this.emit('error', err);
    }

    this.someOption = (/y/i).test(props.someOption);

    cb();
  }.bind(this));
};

CordovaGenerator.prototype.app = function app() {
  this.mkdir('app');
  this.mkdir('app/css');
  this.mkdir('app/img');
  this.mkdir('app/js');
  this.copy('_index.html', 'app/index.html');
  this.copy('_index.css', 'app/index.css');
  this.copy('_index.js', 'app/index.js');
  this.copy('_config.xml', 'app/config.xml');

  this.mkdir('platforms');
  this.mkdir('merges');

  this.copy('_package.json', 'package.json');
  this.copy('_component.json', 'component.json');
};

CordovaGenerator.prototype.projectfiles = function projectfiles() {
  this.copy('editorconfig', '.editorconfig');
  this.copy('jshintrc', '.jshintrc');
};
<|endoftext|>


<commit_before>
/*
    generator-joomla-spc

    index.coffee
 */

(function() {
  var Generator, config, exec, fs, path, rimraf, semver, util, yeoman;

  Generator = function(args, options) {
    yeoman.generators.Base.apply(this, arguments);
    this.sourceRoot(path.join(__dirname, 'templates'));
    this.on('end', function() {
      this.installDependencies({
        skipInstall: options['skip-install']
      });
    });
  };

  'use strict';

  util = require('util');

  path = require('path');

  fs = require('fs');

  yeoman = require('yeoman-generator');
  yosay = require('yosay');
  chalk = require('chalk');

  rimraf = require('rimraf');

  exec = require('child_process').exec;

  semver = require('semver');

  config = require('../config.js');

  module.exports = Generator;

  util.inherits(Generator, yeoman.generators.NamedBase);

  Generator.prototype.startGenerator = function() {
 //  // initializing: {

 //    // Welcome
     //welcome: function () {
      this.log(yosay(chalk.white('Welcome to the SPC Joomla Extension generator!')));
    //}
  };

  Generator.prototype.getConfig = function() {
    var cb, self;
    cb = this.async();
    self = this;
    self.configExists = false;
    config.getConfig(function(err, data) {
      if (!err) {
        self.configExists = true;
      }
      self.defaultAuthorName = data.authorName;
      self.defaultAuthorURL = data.authorURL;
      self.defaultAuthorEmail = data.authorEmail;
      self.latestVersion = data.latestVersion;
      cb();
    });
  };

  Generator.prototype.askFor = function() {
    var cb, prompts, self;
    cb = this.async();
    self = this;
    // console.log(this.yeoman)
    prompts = [
      {
        name: 'description',
        message: 'Describe your component',
        'default': 'A sample description'
      }, {
        name: 'componentName',
        message: 'What\'s the component\'s name?',
        'default': 'default-value'
      }, {
        name: 'authorName',
        message: 'What\'s your name?',
        'default': chalk.white(self.defaultAuthorName)
      }, {
        name: 'authorEmail',
        message: 'What\'s your e-mail?',
        'default': chalk.white(self.defaultAuthorEmail)
      }, {
        name: 'authorURL',
        message: 'What\'s your website?',
        'default': chalk.white(self.defaultAuthorURL)
      }, {
        name: 'versionno',
        message: 'What\'s the version number?',
        'default': '1.0.0'
      }, {
        name: 'license',
        message: 'What\'s the copyright license?',
        'default': 'MIT'
      }, {
        type: 'confirm',
        name: 'requireManageRights',
        message: 'Does your component require admin manage rights to access it?'
      }, {
        type: 'confirm',
        name: 'legacyJoomla',
        message: 'Support Joomla 2.5x with compatibility layer?'
      }
    ];
    this.prompt(prompts, (function(props) {
      var values;
      values = void 0;
      this.description = props.description;
      this.componentName = props.componentName;
      this.authorName = props.authorName;
      this.authorEmail = props.authorEmail;
      this.authorURL = props.authorURL;
      this.versionno = props.versionno;
      this.license = props.license;
      this.requireManageRights = props.requireManageRights;
      this.legacyJoomla = props.legacyJoomla;
      this.currentDate = this._getCurrentDate();
      this.currentYear = this._getCurrentYear();
      if (!self.configExists) {
        values = {
          authorName: self.authorName,
          authorURL: self.authorURL,
          authorEmail: self.authorEmail,
          versionno: self.versionno
        };
        return config.createConfig(values, cb);
      } else {
        return cb();
      }
    }).bind(this));
  };

  Generator.prototype.app = function() {
    this.mkdir('app');
    this.mkdir('app/templates');
    this.mkdir('app/admin');
    this.mkdir('app/site');
    this.mkdir('src');
    this.template('_package.json', 'package.json');
    this.copy('_Gruntfile.js', 'Gruntfile.js');
    this.copy('../USAGE', 'USAGE');
    this.template('_bower.json', 'bower.json');
    return this.copy('_gitignore', '.gitignore');
  };

  Generator.prototype._getCurrentDate = function() {
    var dd, mm, today, yyyy;
    dd = void 0;
    mm = void 0;
    today = void 0;
    yyyy = void 0;
    today = new Date;
    dd = today.getDate();
    mm = this._getCurrentMonthName();
    yyyy = today.getFullYear();
    if (dd < 10) {
      dd = '0' + dd;
    }
    if (mm < 10) {
      mm = '0' + mm;
    }
    return today = dd + '-' + mm + '-' + yyyy;
  };

  Generator.prototype._getCurrentMonthName = function() {
    var d, month, n;
    d = void 0;
    month = void 0;
    n = void 0;
    d = new Date;
    month = new Array;
    month[0] = 'January';
    month[1] = 'February';
    month[2] = 'March';
    month[3] = 'April';
    month[4] = 'May';
    month[5] = 'June';
    month[6] = 'July';
    month[7] = 'August';
    month[8] = 'September';
    month[9] = 'October';
    month[10] = 'November';
    month[11] = 'December';
    return n = month[d.getMonth()];
  };

  Generator.prototype._getCurrentYear = function() {
    var today, year, yyyy;
    today = void 0;
    year = void 0;
    yyyy = void 0;
    today = new Date;
    yyyy = today.getFullYear();
    return year = yyyy;
  };

  Generator.prototype.projectfiles = function() {
    this.copy('editorconfig', '.editorconfig');
    return this.copy('jshintrc', '.jshintrc');
  };

  Generator.prototype.createConfigFiles = function() {
    this.template('_component-name.xml', 'src/' + this._.slugify(this.componentName) + '.xml');
    this.template('_config.xml', 'src/' + 'config.xml');
    return this.template('_access.xml', 'src/' + 'access.xml');
  };

  /*
      Create legacy files for fallback to Joomla 2.5x
   */

  Generator.prototype.createLegacyFallbackFiles = function() {
    if (this.legacyJoomla === true) {
      return this.template('_legacy.php', 'src/' + 'legacy.php');
    }
  };

  Generator.prototype.createPHPFiles = function() {
    this.template('_component-name.php', 'src/' + this._.slugify(this.componentName) + '.php');
    return this.template('_router.php', 'src/' + 'router.php');
  };

  Generator.prototype.createDatabaseFiles = function() {
    this.template('sql/_install.mysql.utf8.sql', 'src/' + 'sql/install.mysql.utf8.sql');
    this.template('sql/_uninstall.mysql.utf8.sql', 'src/' + 'sql/uninstall.mysql.utf8.sql');
    return this.template('_install-uninstall.php', 'src/' + 'install-uninstall.php');
  };

  Generator.prototype.createLanguageFiles = function() {
    this.template('languages/en-GB/_en-GB.com_component-name.ini', 'src/' + 'languages/en-GB/en-GB.com_' + this._.slugify(this.componentName) + '.ini');
    return this.template('languages/en-GB/_en-GB.com_component-name.ini', 'src/' + 'languages/en-GB/en-GB.com_' + this._.slugify(this.componentName) + '.sys.ini');
  };

  Generator.prototype.createEmptyMVCFolders = function() {
    var emptyMVCFolders, folderName, i, len;
    emptyMVCFolders = void 0;
    folderName = void 0;
    i = void 0;
    len = void 0;
    emptyMVCFolders = ['src/' + 'controllers', 'src/' + 'helpers', 'src/' + 'models', 'src/' + 'sql', 'src/' + 'tables', 'src/' + 'views'];
    i = 0;
    len = emptyMVCFolders.length;
    while (i < len) {
      folderName = emptyMVCFolders[i];
      this.template('_index.html', folderName + '/index.html');
      i++;
    }
    this.template('_index.html', 'src/' + 'index.html');
    this.template('_index.html', 'src/' + 'languages/index.html');
    return this.template('_index.html', 'src/' + 'languages/en-GB/index.html');
  };

  Generator.prototype.endGenerator = function() {
    this.log.writeln('');
    this.log.writeln('Looks like we\'re done!');
    this.log.writeln('');
  };

}).call(this);
<commit_msg>removed esc chars from user data<commit_after>
/*
    generator-joomla-spc

    index.coffee
 */

(function() {
  var Generator, config, exec, fs, path, rimraf, semver, util, yeoman;

  Generator = function(args, options) {
    yeoman.generators.Base.apply(this, arguments);
    this.sourceRoot(path.join(__dirname, 'templates'));
    this.on('end', function() {
      this.installDependencies({
        skipInstall: options['skip-install']
      });
    });
  };

  'use strict';

  util = require('util');

  path = require('path');

  fs = require('fs');

  yeoman = require('yeoman-generator');
  yosay = require('yosay');
  chalk = require('chalk');

  rimraf = require('rimraf');

  exec = require('child_process').exec;

  semver = require('semver');

  config = require('../config.js');

  module.exports = Generator;

  util.inherits(Generator, yeoman.generators.NamedBase);

  Generator.prototype.startGenerator = function() {
 //  // initializing: {

 //    // Welcome
     //welcome: function () {
      this.log(yosay(chalk.white('Welcome to the SPC Joomla Extension generator!')));
    //}
  };

  Generator.prototype.getConfig = function() {
    var cb, self;
    cb = this.async();
    self = this;
    self.configExists = false;
    config.getConfig(function(err, data) {
      if (!err) {
        self.configExists = true;
      }
      self.defaultAuthorName = data.authorName;
      self.defaultAuthorURL = data.authorURL;
      self.defaultAuthorEmail = data.authorEmail;
      self.latestVersion = data.latestVersion;
      cb();
    });
  };

  Generator.prototype.askFor = function() {
    var cb, prompts, self;
    cb = this.async();
    self = this;
    // console.log(this.yeoman)
    prompts = [
      {
        name: 'description',
        message: 'Describe your component',
        'default': 'A sample description'
      }, {
        name: 'componentName',
        message: 'What\'s the component\'s name?',
        'default': 'default-value'
      }, {
        name: 'authorName',
        message: 'What\'s your name?',
        'default': self.defaultAuthorName
      }, {
        name: 'authorEmail',
        message: 'What\'s your e-mail?',
        'default': self.defaultAuthorEmail
      }, {
        name: 'authorURL',
        message: 'What\'s your website?',
        'default': self.defaultAuthorURL
      }, {
        name: 'versionno',
        message: 'What\'s the version number?',
        'default': '1.0.0'
      }, {
        name: 'license',
        message: 'What\'s the copyright license?',
        'default': 'MIT'
      }, {
        type: 'confirm',
        name: 'requireManageRights',
        message: 'Does your component require admin manage rights to access it?'
      }, {
        type: 'confirm',
        name: 'legacyJoomla',
        message: 'Support Joomla 2.5x with compatibility layer?'
      }
    ];
    this.prompt(prompts, (function(props) {
      var values;
      values = void 0;
      this.description = props.description;
      this.componentName = props.componentName;
      this.authorName = props.authorName;
      this.authorEmail = props.authorEmail;
      this.authorURL = props.authorURL;
      this.versionno = props.versionno;
      this.license = props.license;
      this.requireManageRights = props.requireManageRights;
      this.legacyJoomla = props.legacyJoomla;
      this.currentDate = this._getCurrentDate();
      this.currentYear = this._getCurrentYear();
      if (!self.configExists) {
        values = {
          authorName: self.authorName,
          authorURL: self.authorURL,
          authorEmail: self.authorEmail,
          versionno: self.versionno
        };
        return config.createConfig(values, cb);
      } else {
        return cb();
      }
    }).bind(this));
  };

  Generator.prototype.app = function() {
    this.mkdir('app');
    this.mkdir('app/templates');
    this.mkdir('app/admin');
    this.mkdir('app/site');
    this.mkdir('src');
    this.template('_package.json', 'package.json');
    this.copy('_Gruntfile.js', 'Gruntfile.js');
    this.copy('../USAGE', 'USAGE');
    this.template('_bower.json', 'bower.json');
    return this.copy('_gitignore', '.gitignore');
  };

  Generator.prototype._getCurrentDate = function() {
    var dd, mm, today, yyyy;
    dd = void 0;
    mm = void 0;
    today = void 0;
    yyyy = void 0;
    today = new Date;
    dd = today.getDate();
    mm = this._getCurrentMonthName();
    yyyy = today.getFullYear();
    if (dd < 10) {
      dd = '0' + dd;
    }
    if (mm < 10) {
      mm = '0' + mm;
    }
    return today = dd + '-' + mm + '-' + yyyy;
  };

  Generator.prototype._getCurrentMonthName = function() {
    var d, month, n;
    d = void 0;
    month = void 0;
    n = void 0;
    d = new Date;
    month = new Array;
    month[0] = 'January';
    month[1] = 'February';
    month[2] = 'March';
    month[3] = 'April';
    month[4] = 'May';
    month[5] = 'June';
    month[6] = 'July';
    month[7] = 'August';
    month[8] = 'September';
    month[9] = 'October';
    month[10] = 'November';
    month[11] = 'December';
    return n = month[d.getMonth()];
  };

  Generator.prototype._getCurrentYear = function() {
    var today, year, yyyy;
    today = void 0;
    year = void 0;
    yyyy = void 0;
    today = new Date;
    yyyy = today.getFullYear();
    return year = yyyy;
  };

  Generator.prototype.projectfiles = function() {
    this.copy('editorconfig', '.editorconfig');
    return this.copy('jshintrc', '.jshintrc');
  };

  Generator.prototype.createConfigFiles = function() {
    this.template('_component-name.xml', 'src/' + this._.slugify(this.componentName) + '.xml');
    this.template('_config.xml', 'src/' + 'config.xml');
    return this.template('_access.xml', 'src/' + 'access.xml');
  };

  /*
      Create legacy files for fallback to Joomla 2.5x
   */

  Generator.prototype.createLegacyFallbackFiles = function() {
    if (this.legacyJoomla === true) {
      return this.template('_legacy.php', 'src/' + 'legacy.php');
    }
  };

  Generator.prototype.createPHPFiles = function() {
    this.template('_component-name.php', 'src/' + this._.slugify(this.componentName) + '.php');
    return this.template('_router.php', 'src/' + 'router.php');
  };

  Generator.prototype.createDatabaseFiles = function() {
    this.template('sql/_install.mysql.utf8.sql', 'src/' + 'sql/install.mysql.utf8.sql');
    this.template('sql/_uninstall.mysql.utf8.sql', 'src/' + 'sql/uninstall.mysql.utf8.sql');
    return this.template('_install-uninstall.php', 'src/' + 'install-uninstall.php');
  };

  Generator.prototype.createLanguageFiles = function() {
    this.template('languages/en-GB/_en-GB.com_component-name.ini', 'src/' + 'languages/en-GB/en-GB.com_' + this._.slugify(this.componentName) + '.ini');
    return this.template('languages/en-GB/_en-GB.com_component-name.ini', 'src/' + 'languages/en-GB/en-GB.com_' + this._.slugify(this.componentName) + '.sys.ini');
  };

  Generator.prototype.createEmptyMVCFolders = function() {
    var emptyMVCFolders, folderName, i, len;
    emptyMVCFolders = void 0;
    folderName = void 0;
    i = void 0;
    len = void 0;
    emptyMVCFolders = ['src/' + 'controllers', 'src/' + 'helpers', 'src/' + 'models', 'src/' + 'sql', 'src/' + 'tables', 'src/' + 'views'];
    i = 0;
    len = emptyMVCFolders.length;
    while (i < len) {
      folderName = emptyMVCFolders[i];
      this.template('_index.html', folderName + '/index.html');
      i++;
    }
    this.template('_index.html', 'src/' + 'index.html');
    this.template('_index.html', 'src/' + 'languages/index.html');
    return this.template('_index.html', 'src/' + 'languages/en-GB/index.html');
  };

  Generator.prototype.endGenerator = function() {
    this.log.writeln('');
    this.log.writeln('Looks like we\'re done!');
    this.log.writeln('');
  };

}).call(this);
<|endoftext|>