<commit_before>var glob = require("glob"),
    path = require("path-posix"),
    merge = require("merge-stream"),
    gulpif = require("gulp-if"),
    gulp = require("gulp"),
    newer = require("gulp-newer"),
	plumber = require("gulp-plumber"),
    sourcemaps = require("gulp-sourcemaps"),
    less = require("gulp-less"),
	autoprefixer = require("gulp-autoprefixer"),
	minify = require("gulp-minify-css"),
    typescript = require("gulp-typescript"),
	uglify = require("gulp-uglify"),
	rename = require("gulp-rename"),
    concat = require("gulp-concat"),
	header = require("gulp-header")

/*
** GULP TASKS
*/

// Incremental build (each asset group is built only if one or more inputs are newer than the output).
gulp.task("build", function () {
    var assetGroupTasks = getAssetGroups().map(function (assetGroup) {
        var doRebuild = false;
        return createAssetGroupTask(assetGroup, doRebuild);
    });
    return merge(assetGroupTasks);
});

// Full rebuild (all assets groups are built regardless of timestamps).
gulp.task("rebuild", function () {
    var assetGroupTasks = getAssetGroups().map(function (assetGroup) {
        var doRebuild = true;
        return createAssetGroupTask(assetGroup, doRebuild);
    });
    return merge(assetGroupTasks);
});

// Continuous watch (each asset group is built whenever one of its inputs changes).
gulp.task("watch", function () {
    getAssetGroups().forEach(function (assetGroup) {
        gulp.watch(assetGroup.inputPaths, function (event) {
            console.log("Asset file '" + event.path + "' was " + event.type + ", rebuilding output '" + assetGroup.outputPath + "'.");
            var task = createAssetGroupTask(assetGroup);
        });
    });
});

/*
** ASSET GROUPS
*/

function getAssetGroups() {
    var assetManifestPaths = glob.sync("Orchard.Web/{Core,Modules,Themes}/*/Assets.json");
    var assetGroups = [];
    assetManifestPaths.forEach(function (assetManifestPath) {
        var assetManifest = require("./" + assetManifestPath);
        assetManifest.forEach(function (assetGroup) {
            resolveAssetGroupPaths(assetGroup, assetManifestPath);
            assetGroups.push(assetGroup);
        });
    });
    return assetGroups;
}

function resolveAssetGroupPaths(assetGroup, assetManifestPath) {
    assetGroup.basePath = path.dirname(assetManifestPath);
    assetGroup.inputPaths = assetGroup.inputs.map(function (inputPath) {
        return path.join(assetGroup.basePath, inputPath);
    });
    assetGroup.outputPath = path.join(assetGroup.basePath, assetGroup.output);
    assetGroup.outputDir = path.dirname(assetGroup.outputPath);
    assetGroup.outputFileName = path.basename(assetGroup.output);
}

function createAssetGroupTask(assetGroup, doRebuild) {
    var outputExt = path.extname(assetGroup.output).toLowerCase();
    switch (outputExt) {
        case ".css":
            return buildCssPipeline(assetGroup, doRebuild);
        case ".js":
            return buildJsPipeline(assetGroup, doRebuild);
    }
}

/*
** PROCESSING PIPELINES
*/

function buildCssPipeline(assetGroup, doRebuild) {
    assetGroup.inputPaths.forEach(function (inputPath) {
        var ext = path.extname(inputPath).toLowerCase();
        if (ext !== ".less" && ext !== ".css")
            throw "Input file '" + inputPath + "' is not of a valid type for output file '" + assetGroup.outputPath + "'.";
    });
    var doConcat = path.basename(assetGroup.outputFileName, ".css") !== "@";
    return gulp.src(assetGroup.inputPaths)
        .pipe(gulpif(!doRebuild,
            gulpif(doConcat,
                newer(assetGroup.outputPath),
                newer({
                    dest: assetGroup.outputDir,
                    ext: ".css"
                }))))
        .pipe(plumber())
        .pipe(sourcemaps.init())
        .pipe(gulpif("*.less", less()))
        .pipe(gulpif(doConcat, concat(assetGroup.outputFileName)))
        .pipe(autoprefixer({ browsers: ["last 2 versions"] }))
        // TODO: Start using below whenever gulp-header supports sourcemaps.
        //.pipe(header(
        //    "/*\n" +
        //    "** NOTE: This file is generated by Gulp compilation and should not be edited directly!\n" +
        //    "** Any changes made directly to this file will be overwritten next time the Gulp compilation runs.\n" +
        //    "** For more information, see the Readme.txt file in the Gulp solution folder.\n" +
        //    "*/\n\n"))
        .pipe(sourcemaps.write())
        .pipe(gulp.dest(assetGroup.outputDir))
        .pipe(minify())
        .pipe(rename({
            suffix: ".min"
        }))
        .pipe(gulp.dest(assetGroup.outputDir));
}

function buildJsPipeline(assetGroup, doRebuild) {
    assetGroup.inputPaths.forEach(function (inputPath) {
        var ext = path.extname(inputPath).toLowerCase();
        if (ext !== ".ts" && ext !== ".js")
            throw "Input file '" + inputPath + "' is not of a valid type for output file '" + assetGroup.outputPath + "'.";
    });
    var doConcat = path.basename(assetGroup.outputFileName, ".js") !== "@";
    return gulp.src(assetGroup.inputPaths)
        .pipe(gulpif(!doRebuild,
            gulpif(doConcat,
                newer(assetGroup.outputPath),
                newer({
                    dest: assetGroup.outputDir,
                    ext: ".js"
                }))))
        .pipe(plumber())
        .pipe(sourcemaps.init())
        .pipe(gulpif("*.ts", typescript({
            declaration: false,
            //noImplicitAny: true,
            noEmitOnError: true,
            sortOutput: true,
        }).js))
		.pipe(gulpif(doConcat, concat(assetGroup.outputFileName)))
        // TODO: Start using below whenever gulp-header supports sourcemaps.
        //.pipe(header(
        //    "/*\n" +
        //    "** NOTE: This file is generated by Gulp compilation and should not be edited directly!\n" +
        //    "** Any changes made directly to this file will be overwritten next time the Gulp compilation runs.\n" +
        //    "** For more information, see the Readme.txt file in the Gulp solution folder.\n" +
        //    "*/\n\n"))
        .pipe(sourcemaps.write())
        .pipe(gulp.dest(assetGroup.outputDir))
		.pipe(uglify())
		.pipe(rename({
		    suffix: ".min"
		}))
		.pipe(gulp.dest(assetGroup.outputDir));
}<commit_msg>Fixes #5607<commit_after>var glob = require("glob"),
    path = require("path-posix"),
    merge = require("merge-stream"),
    gulpif = require("gulp-if"),
    gulp = require("gulp"),
    newer = require("gulp-newer"),
	plumber = require("gulp-plumber"),
    sourcemaps = require("gulp-sourcemaps"),
    less = require("gulp-less"),
	autoprefixer = require("gulp-autoprefixer"),
	minify = require("gulp-minify-css"),
    typescript = require("gulp-typescript"),
	uglify = require("gulp-uglify"),
	rename = require("gulp-rename"),
    concat = require("gulp-concat"),
	header = require("gulp-header"),
    notify = require("gulp-notify")

/*
** GULP TASKS
*/

// Incremental build (each asset group is built only if one or more inputs are newer than the output).
gulp.task("build", function () {
    var assetGroupTasks = getAssetGroups().map(function (assetGroup) {
        var doRebuild = false;
        return createAssetGroupTask(assetGroup, doRebuild);
    });
    return merge(assetGroupTasks);
});

// Full rebuild (all assets groups are built regardless of timestamps).
gulp.task("rebuild", function () {
    var assetGroupTasks = getAssetGroups().map(function (assetGroup) {
        var doRebuild = true;
        return createAssetGroupTask(assetGroup, doRebuild);
    });
    return merge(assetGroupTasks);
});

// Continuous watch (each asset group is built whenever one of its inputs changes).
gulp.task("watch", function () {
    getAssetGroups().forEach(function (assetGroup) {
        gulp.watch(assetGroup.watchPaths != undefined ? assetGroup.watchPaths : assetGroup.inputPaths, function (event) {
            console.log("Asset file '" + event.path + "' was " + event.type + ", rebuilding output '" + assetGroup.outputPath + "'.");
            var task = createAssetGroupTask(assetGroup, assetGroup.rebuildAlways);
        });
    });
});

/*
** ASSET GROUPS
*/

function getAssetGroups() {
    var assetManifestPaths = glob.sync("Orchard.Web/{Core,Modules,Themes}/*/Assets.json");
    var assetGroups = [];
    assetManifestPaths.forEach(function (assetManifestPath) {
        var assetManifest = require("./" + assetManifestPath);
        assetManifest.forEach(function (assetGroup) {
            resolveAssetGroupPaths(assetGroup, assetManifestPath);
            assetGroups.push(assetGroup);
        });
    });
    return assetGroups;
}

function resolveAssetGroupPaths(assetGroup, assetManifestPath) {
    assetGroup.basePath = path.dirname(assetManifestPath);
    if (assetGroup.watch != undefined) {
        assetGroup.watchPaths = assetGroup.watch.map(function (watchPath) {
            return path.join(assetGroup.basePath, watchPath);
        });
    }
    assetGroup.inputPaths = assetGroup.inputs.map(function (inputPath) {
        return path.join(assetGroup.basePath, inputPath);
    });
    assetGroup.outputPath = path.join(assetGroup.basePath, assetGroup.output);
    assetGroup.outputDir = path.dirname(assetGroup.outputPath);
    assetGroup.outputFileName = path.basename(assetGroup.output);
}

function createAssetGroupTask(assetGroup, doRebuild) {
    var outputExt = path.extname(assetGroup.output).toLowerCase();
    switch (outputExt) {
        case ".css":
            return buildCssPipeline(assetGroup, doRebuild);
        case ".js":
            return buildJsPipeline(assetGroup, doRebuild);
    }
}

/*
** PROCESSING PIPELINES
*/

function buildCssPipeline(assetGroup, doRebuild) {
    assetGroup.inputPaths.forEach(function (inputPath) {
        var ext = path.extname(inputPath).toLowerCase();
        if (ext !== ".less" && ext !== ".css")
            throw "Input file '" + inputPath + "' is not of a valid type for output file '" + assetGroup.outputPath + "'.";
    });
    var doConcat = path.basename(assetGroup.outputFileName, ".css") !== "@";

    if (!doRebuild) {
        console.log("CSS will only rebuild if less files specified in 'inputs' are newer.");
    }
    else {
        console.log("Force Rebuild is enabled, rebuilding all input files.");
    }

    var includeSourcepaths = assetGroup.excludeSourceMaps != undefined ? !assetGroup.excludeSourceMaps : true;

    return gulp.src(assetGroup.inputPaths)
        .pipe(gulpif(!doRebuild,
            gulpif(doConcat,
                newer(assetGroup.outputPath),
                newer({
                    dest: assetGroup.outputDir,
                    ext: ".css"
                }))))
        .pipe(plumber())
        .pipe(gulpif(includeSourcepaths,sourcemaps.init()))
        .pipe(gulpif("*.less", less()))
        .pipe(gulpif(doConcat, concat(assetGroup.outputFileName)))
        .pipe(autoprefixer({ browsers: ["last 2 versions"] }))
        // TODO: Start using below whenever gulp-header supports sourcemaps.
        //.pipe(header(
        //    "/*\n" +
        //    "** NOTE: This file is generated by Gulp compilation and should not be edited directly!\n" +
        //    "** Any changes made directly to this file will be overwritten next time the Gulp compilation runs.\n" +
        //    "** For more information, see the Readme.txt file in the Gulp solution folder.\n" +
        //    "*/\n\n"))
        .pipe(gulpif(includeSourcepaths,sourcemaps.write()))
        .pipe(gulp.dest(assetGroup.outputDir))
        .pipe(minify())
        .pipe(rename({
            suffix: ".min"
        }))
        .pipe(gulp.dest(assetGroup.outputDir))
        //.pipe(notify("Build process complete"));
        .pipe(gulpif(doRebuild, notify("Rebuild complete"),notify("Build process complete")));
}

function buildJsPipeline(assetGroup, doRebuild) {
    assetGroup.inputPaths.forEach(function (inputPath) {
        var ext = path.extname(inputPath).toLowerCase();
        if (ext !== ".ts" && ext !== ".js")
            throw "Input file '" + inputPath + "' is not of a valid type for output file '" + assetGroup.outputPath + "'.";
    });
    var doConcat = path.basename(assetGroup.outputFileName, ".js") !== "@";
    return gulp.src(assetGroup.inputPaths)
        .pipe(gulpif(!doRebuild,
            gulpif(doConcat,
                newer(assetGroup.outputPath),
                newer({
                    dest: assetGroup.outputDir,
                    ext: ".js"
                }))))
        .pipe(plumber())
        .pipe(sourcemaps.init())
        .pipe(gulpif("*.ts", typescript({
            declaration: false,
            //noImplicitAny: true,
            noEmitOnError: true,
            sortOutput: true,
        }).js))
	.pipe(gulpif(doConcat, concat(assetGroup.outputFileName)))
        // TODO: Start using below whenever gulp-header supports sourcemaps.
        //.pipe(header(
        //    "/*\n" +
        //    "** NOTE: This file is generated by Gulp compilation and should not be edited directly!\n" +
        //    "** Any changes made directly to this file will be overwritten next time the Gulp compilation runs.\n" +
        //    "** For more information, see the Readme.txt file in the Gulp solution folder.\n" +
        //    "*/\n\n"))
        .pipe(sourcemaps.write())
        .pipe(gulp.dest(assetGroup.outputDir))
	.pipe(uglify())
	.pipe(rename({
		suffix: ".min"
	}))
	.pipe(gulp.dest(assetGroup.outputDir));
}
<|endoftext|>


<commit_before>var static = require('node-static');
var http = require('http');
var file = new(static.Server)();
var app = http.createServer(function (req, res) {
  file.serve(req, res);
}).listen(2013);
<commit_msg>Update adapter.js<commit_after>ar RTCPeerConnection = null;
var getUserMedia = null;
var attachMediaStream = null;
var reattachMediaStream = null;
var webrtcDetectedBrowser = null;
var webrtcDetectedVersion = null;

function trace(text) {
  // This function is used for logging.
  if (text[text.length - 1] == '\n') {
    text = text.substring(0, text.length - 1);
  }
  console.log((performance.now() / 1000).toFixed(3) + ": " + text);
}

if (navigator.mozGetUserMedia) {
  console.log("This appears to be Firefox");

  webrtcDetectedBrowser = "firefox";

  webrtcDetectedVersion =
                  parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1]);

  // The RTCPeerConnection object.
  RTCPeerConnection = mozRTCPeerConnection;

  // The RTCSessionDescription object.
  RTCSessionDescription = mozRTCSessionDescription;

  // The RTCIceCandidate object.
  RTCIceCandidate = mozRTCIceCandidate;

  // Get UserMedia (only difference is the prefix).
  // Code from Adam Barth.
  getUserMedia = navigator.mozGetUserMedia.bind(navigator);

  // Creates iceServer from the url for FF.
  createIceServer = function(url, username, password) {
    var iceServer = null;
    var url_parts = url.split(':');
    if (url_parts[0].indexOf('stun') === 0) {
      // Create iceServer with stun url.
      iceServer = { 'url': url };
    } else if (url_parts[0].indexOf('turn') === 0 &&
               (url.indexOf('transport=udp') !== -1 ||
                url.indexOf('?transport') === -1)) {
      // Create iceServer with turn url.
      // Ignore the transport parameter from TURN url.
      var turn_url_parts = url.split("?");
      iceServer = { 'url': turn_url_parts[0],
                    'credential': password,
                    'username': username };
    }
    return iceServer;
  };

  // Attach a media stream to an element.
  attachMediaStream = function(element, stream) {
    console.log("Attaching media stream");
    element.mozSrcObject = stream;
    element.play();
  };

  reattachMediaStream = function(to, from) {
    console.log("Reattaching media stream");
    to.mozSrcObject = from.mozSrcObject;
    to.play();
  };

  // Fake get{Video,Audio}Tracks
  MediaStream.prototype.getVideoTracks = function() {
    return [];
  };

  MediaStream.prototype.getAudioTracks = function() {
    return [];
  };
} else if (navigator.webkitGetUserMedia) {
  console.log("This appears to be Chrome");

  webrtcDetectedBrowser = "chrome";
  webrtcDetectedVersion =
             parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2]);

  // Creates iceServer from the url for Chrome.
  createIceServer = function(url, username, password) {
    var iceServer = null;
    var url_parts = url.split(':');
    if (url_parts[0].indexOf('stun') === 0) {
      // Create iceServer with stun url.
      iceServer = { 'url': url };
    } else if (url_parts[0].indexOf('turn') === 0) {
      if (webrtcDetectedVersion < 28) {
        // For pre-M28 chrome versions use old TURN format.
        var url_turn_parts = url.split("turn:");
        iceServer = { 'url': 'turn:' + username + '@' + url_turn_parts[1],
                      'credential': password };
      } else {
        // For Chrome M28 & above use new TURN format.
        iceServer = { 'url': url,
                      'credential': password,
                      'username': username };
      }
    }
    return iceServer;
  };

  // The RTCPeerConnection object.
  RTCPeerConnection = webkitRTCPeerConnection;

  // Get UserMedia (only difference is the prefix).
  // Code from Adam Barth.
  getUserMedia = navigator.webkitGetUserMedia.bind(navigator);

  // Attach a media stream to an element.
  attachMediaStream = function(element, stream) {
    if (typeof element.srcObject !== 'undefined') {
      element.srcObject = stream;
    } else if (typeof element.mozSrcObject !== 'undefined') {
      element.mozSrcObject = stream;
    } else if (typeof element.src !== 'undefined') {
      element.src = URL.createObjectURL(stream);
    } else {
      console.log('Error attaching stream to element.');
    }
  };

  reattachMediaStream = function(to, from) {
    to.src = from.src;
  };

  // The representation of tracks in a stream is changed in M26.
  // Unify them for earlier Chrome versions in the coexisting period.
  if (!webkitMediaStream.prototype.getVideoTracks) {
    webkitMediaStream.prototype.getVideoTracks = function() {
      return this.videoTracks;
    };
    webkitMediaStream.prototype.getAudioTracks = function() {
      return this.audioTracks;
    };
  }

  // New syntax of getXXXStreams method in M26.
  if (!webkitRTCPeerConnection.prototype.getLocalStreams) {
    webkitRTCPeerConnection.prototype.getLocalStreams = function() {
      return this.localStreams;
    };
    webkitRTCPeerConnection.prototype.getRemoteStreams = function() {
      return this.remoteStreams;
    };
  }
} else {
  console.log("Browser does not appear to be WebRTC-capable");
}
<|endoftext|>


<commit_before>/**
 * @flow
 */

import * as Diagnostics from './Diagnostics';

let _version;
let _isBooted = false;

function _isWindowDefined() {
  return typeof window !== 'undefined' && window && window.Intercom;
}

export async function update(user_id: ?string, user_hash: ?string) {
  try {
    if (_isWindowDefined()) {
      let deviceInfo = {};

      try {
        deviceInfo = await Diagnostics.getDeviceInfoAsync({
          limitLengthForIntercom: true,
        });
      } catch (e) {
        console.error(e);
      }

      let data = {
        app_id: 'fhlr5ht1',
        user_id,
        user_hash,
        ...deviceInfo,
      };

      if (_version) {
        data = {
          ...data,
          version: _version,
        };
      }

      if (_isBooted) {
        if (user_id) {
          // Call update so that any conversations carry over from the logged out to
          // the logged in user.
          window.Intercom('update', data);
        } else {
          // Was logged in and is now logging out, restart intercom.
          window.Intercom('shutdown');
          window.Intercom('boot', data);
        }
      } else {
        window.Intercom('boot', data);
        _isBooted = true;
      }
      window.IntercomUpdateStyle();
    }
  } catch (e) {
    console.error(e);
  }
}

export function trackEvent(name: string, metadata: any) {
  try {
    if (_isWindowDefined()) {
      window.Intercom('trackEvent', name, metadata);
    }
  } catch (e) {
    console.error(e);
  }
}

export function showNewMessage(message: string) {
  try {
    if (_isWindowDefined()) {
      window.Intercom('showNewMessage', message);
    }
  } catch (e) {
    console.error(e);
  }
}

export function setVersionName(name: string) {
  _version = name;
}
<commit_msg>update Intercom app_id for new account<commit_after>/**
 * @flow
 */

import * as Diagnostics from './Diagnostics';

let _version;
let _isBooted = false;

function _isWindowDefined() {
  return typeof window !== 'undefined' && window && window.Intercom;
}

export async function update(user_id: ?string, user_hash: ?string) {
  try {
    if (_isWindowDefined()) {
      let deviceInfo = {};

      try {
        deviceInfo = await Diagnostics.getDeviceInfoAsync({
          limitLengthForIntercom: true,
        });
      } catch (e) {
        console.error(e);
      }

      let data = {
        app_id: 'beew3st8',
        user_id,
        user_hash,
        ...deviceInfo,
      };

      if (_version) {
        data = {
          ...data,
          version: _version,
        };
      }

      if (_isBooted) {
        if (user_id) {
          // Call update so that any conversations carry over from the logged out to
          // the logged in user.
          window.Intercom('update', data);
        } else {
          // Was logged in and is now logging out, restart intercom.
          window.Intercom('shutdown');
          window.Intercom('boot', data);
        }
      } else {
        window.Intercom('boot', data);
        _isBooted = true;
      }
      window.IntercomUpdateStyle();
    }
  } catch (e) {
    console.error(e);
  }
}

export function trackEvent(name: string, metadata: any) {
  try {
    if (_isWindowDefined()) {
      window.Intercom('trackEvent', name, metadata);
    }
  } catch (e) {
    console.error(e);
  }
}

export function showNewMessage(message: string) {
  try {
    if (_isWindowDefined()) {
      window.Intercom('showNewMessage', message);
    }
  } catch (e) {
    console.error(e);
  }
}

export function setVersionName(name: string) {
  _version = name;
}
<|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.
*/

import MatrixClientPeg from './MatrixClientPeg';
import PlatformPeg from './PlatformPeg';
import TextForEvent from './TextForEvent';
import Analytics from './Analytics';
import Avatar from './Avatar';
import dis from './dispatcher';
import sdk from './index';
import { _t } from './languageHandler';
import Modal from './Modal';
import SettingsStore, {SettingLevel} from "./settings/SettingsStore";

/*
 * Dispatches:
 * {
 *   action: "notifier_enabled",
 *   value: boolean
 * }
 */

const MAX_PENDING_ENCRYPTED = 20;

const Notifier = {
    notifsByRoom: {},

    // A list of event IDs that we've received but need to wait until
    // they're decrypted until we decide whether to notify for them
    // or not
    pendingEncryptedEventIds: [],

    notificationMessageForEvent: function(ev) {
        return TextForEvent.textForEvent(ev);
    },

    _displayPopupNotification: function(ev, room) {
        const plaf = PlatformPeg.get();
        if (!plaf) {
            return;
        }
        if (!plaf.supportsNotifications() || !plaf.maySendNotifications()) {
            return;
        }
        if (global.document.hasFocus()) {
            return;
        }

        let msg = this.notificationMessageForEvent(ev);
        if (!msg) return;

        let title;
        if (!ev.sender || room.name === ev.sender.name) {
            title = room.name;
            // notificationMessageForEvent includes sender,
            // but we already have the sender here
            if (ev.getContent().body) msg = ev.getContent().body;
        } else if (ev.getType() === 'm.room.member') {
            // context is all in the message here, we don't need
            // to display sender info
            title = room.name;
        } else if (ev.sender) {
            title = ev.sender.name + " (" + room.name + ")";
            // notificationMessageForEvent includes sender,
            // but we've just out sender in the title
            if (ev.getContent().body) msg = ev.getContent().body;
        }

        if (!this.isBodyEnabled()) {
            msg = '';
        }

        const avatarUrl = ev.sender ? Avatar.avatarUrlForMember(ev.sender, 40, 40, 'crop') : null;
        const notif = plaf.displayNotification(title, msg, avatarUrl, room);

        // if displayNotification returns non-null,  the platform supports
        // clearing notifications later, so keep track of this.
        if (notif) {
            if (this.notifsByRoom[ev.getRoomId()] === undefined) this.notifsByRoom[ev.getRoomId()] = [];
            this.notifsByRoom[ev.getRoomId()].push(notif);
        }
    },

    getSoundForRoom: async function(roomId) {
        // We do no caching here because the SDK caches the event content
        // and the browser will cache the sound.
        let content = SettingsStore.getValue("notificationSound", roomId);
        if (!content) {
            content = SettingsStore.getValue("notificationSound");
            if (!content) {
                return null;
            }
        }

        if (!content.url) {
            console.warn(`${roomId} has custom notification sound event, but no url key`);
            return null;
        }

        return {
            url: MatrixClientPeg.get().mxcUrlToHttp(content.url),
            name: content.name,
            type: content.type,
            size: content.size,
        };
    },

    _playAudioNotification: function(ev, room) {
        this.getSoundForRoom(room.roomId).then((sound) => {
            console.log(`Got sound ${sound.name || "default"} for ${room.roomId}`);
            // XXX: How do we ensure this is a sound file and not
            // going to be exploited?
            const selector = document.querySelector(sound ? `audio[src='${sound.url}']` : "#messageAudio");
            let audioElement = selector;
            if (!selector) {
                if (!sound) {
                    console.error("Tried to play alert sound but missing #messageAudio");
                    return;
                }
                audioElement = new Audio(sound.url);
                if (sound.type) {
                    audioElement.type = sound.type;
                }
                document.body.appendChild(audioElement);
            }
            audioElement.play();
        }).catch((ex) => {
            console.warn("Caught error when trying to fetch room notification sound:", ex);
        });
    },

    start: function() {
        this.boundOnEvent = this.onEvent.bind(this);
        this.boundOnSyncStateChange = this.onSyncStateChange.bind(this);
        this.boundOnRoomReceipt = this.onRoomReceipt.bind(this);
        this.boundOnEventDecrypted = this.onEventDecrypted.bind(this);
        MatrixClientPeg.get().on('event', this.boundOnEvent);
        MatrixClientPeg.get().on('Room.receipt', this.boundOnRoomReceipt);
        MatrixClientPeg.get().on('Event.decrypted', this.boundOnEventDecrypted);
        MatrixClientPeg.get().on("sync", this.boundOnSyncStateChange);
        this.toolbarHidden = false;
        this.isSyncing = false;
    },

    stop: function() {
        if (MatrixClientPeg.get() && this.boundOnRoomTimeline) {
            MatrixClientPeg.get().removeListener('Event', this.boundOnEvent);
            MatrixClientPeg.get().removeListener('Room.receipt', this.boundOnRoomReceipt);
            MatrixClientPeg.get().removeListener('Event.decrypted', this.boundOnEventDecrypted);
            MatrixClientPeg.get().removeListener('sync', this.boundOnSyncStateChange);
        }
        this.isSyncing = false;
    },

    supportsDesktopNotifications: function() {
        const plaf = PlatformPeg.get();
        return plaf && plaf.supportsNotifications();
    },

    setEnabled: function(enable, callback) {
        const plaf = PlatformPeg.get();
        if (!plaf) return;

        // Dev note: We don't set the "notificationsEnabled" setting to true here because it is a
        // calculated value. It is determined based upon whether or not the master rule is enabled
        // and other flags. Setting it here would cause a circular reference.

        Analytics.trackEvent('Notifier', 'Set Enabled', enable);

        // make sure that we persist the current setting audio_enabled setting
        // before changing anything
        if (SettingsStore.isLevelSupported(SettingLevel.DEVICE)) {
            SettingsStore.setValue("audioNotificationsEnabled", null, SettingLevel.DEVICE, this.isEnabled());
        }

        if (enable) {
            // Attempt to get permission from user
            plaf.requestNotificationPermission().done((result) => {
                if (result !== 'granted') {
                    // The permission request was dismissed or denied
                    // TODO: Support alternative branding in messaging
                    const description = result === 'denied'
                        ? _t('Riot does not have permission to send you notifications - please check your browser settings')
                        : _t('Riot was not given permission to send notifications - please try again');
                    const ErrorDialog = sdk.getComponent('dialogs.ErrorDialog');
                    Modal.createTrackedDialog('Unable to enable Notifications', result, ErrorDialog, {
                        title: _t('Unable to enable Notifications'),
                        description,
                    });
                    return;
                }

                if (callback) callback();
                dis.dispatch({
                    action: "notifier_enabled",
                    value: true,
                });
            });
        } else {
            dis.dispatch({
                action: "notifier_enabled",
                value: false,
            });
        }
        // set the notifications_hidden flag, as the user has knowingly interacted
        // with the setting we shouldn't nag them any further
        this.setToolbarHidden(true);
    },

    isEnabled: function() {
        return this.isPossible() && SettingsStore.getValue("notificationsEnabled");
    },

    isPossible: function() {
        const plaf = PlatformPeg.get();
        if (!plaf) return false;
        if (!plaf.supportsNotifications()) return false;
        if (!plaf.maySendNotifications()) return false;

        return true; // possible, but not necessarily enabled
    },

    isBodyEnabled: function() {
        return this.isEnabled() && SettingsStore.getValue("notificationBodyEnabled");
    },

    isAudioEnabled: function() {
        return this.isEnabled() && SettingsStore.getValue("audioNotificationsEnabled");
    },

    setToolbarHidden: function(hidden, persistent = true) {
        this.toolbarHidden = hidden;

        Analytics.trackEvent('Notifier', 'Set Toolbar Hidden', hidden);

        // XXX: why are we dispatching this here?
        // this is nothing to do with notifier_enabled
        dis.dispatch({
            action: "notifier_enabled",
            value: this.isEnabled(),
        });

        // update the info to localStorage for persistent settings
        if (persistent && global.localStorage) {
            global.localStorage.setItem("notifications_hidden", hidden);
        }
    },

    shouldShowToolbar: function() {
        const client = MatrixClientPeg.get();
        if (!client) {
            return false;
        }
        const isGuest = client.isGuest();
        return !isGuest && this.supportsDesktopNotifications() &&
            !this.isEnabled() && !this._isToolbarHidden();
    },

    _isToolbarHidden: function() {
        // Check localStorage for any such meta data
        if (global.localStorage) {
            return global.localStorage.getItem("notifications_hidden") === "true";
        }

        return this.toolbarHidden;
    },

    onSyncStateChange: function(state) {
        if (state === "SYNCING") {
            this.isSyncing = true;
        } else if (state === "STOPPED" || state === "ERROR") {
            this.isSyncing = false;
        }
    },

    onEvent: function(ev) {
        if (!this.isSyncing) return; // don't alert for any messages initially
        if (ev.sender && ev.sender.userId === MatrixClientPeg.get().credentials.userId) return;

        // If it's an encrypted event and the type is still 'm.room.encrypted',
        // it hasn't yet been decrypted, so wait until it is.
        if (ev.isBeingDecrypted() || ev.isDecryptionFailure()) {
            this.pendingEncryptedEventIds.push(ev.getId());
            // don't let the list fill up indefinitely
            while (this.pendingEncryptedEventIds.length > MAX_PENDING_ENCRYPTED) {
                this.pendingEncryptedEventIds.shift();
            }
            return;
        }

        this._evaluateEvent(ev);
    },

    onEventDecrypted: function(ev) {
        // 'decrypted' means the decryption process has finished: it may have failed,
        // in which case it might decrypt soon if the keys arrive
        if (ev.isDecryptionFailure()) return;

        const idx = this.pendingEncryptedEventIds.indexOf(ev.getId());
        if (idx === -1) return;

        this.pendingEncryptedEventIds.splice(idx, 1);
        this._evaluateEvent(ev);
    },

    onRoomReceipt: function(ev, room) {
        if (room.getUnreadNotificationCount() === 0) {
            // ideally we would clear each notification when it was read,
            // but we have no way, given a read receipt, to know whether
            // the receipt comes before or after an event, so we can't
            // do this. Instead, clear all notifications for a room once
            // there are no notifs left in that room., which is not quite
            // as good but it's something.
            const plaf = PlatformPeg.get();
            if (!plaf) return;
            if (this.notifsByRoom[room.roomId] === undefined) return;
            for (const notif of this.notifsByRoom[room.roomId]) {
                plaf.clearNotification(notif);
            }
            delete this.notifsByRoom[room.roomId];
        }
    },

    _evaluateEvent: function(ev) {
        const room = MatrixClientPeg.get().getRoom(ev.getRoomId());
        const actions = MatrixClientPeg.get().getPushActionsForEvent(ev);
        if (actions && actions.notify) {
            if (this.isEnabled()) {
                this._displayPopupNotification(ev, room);
            }
            if (actions.tweaks.sound && this.isAudioEnabled()) {
                PlatformPeg.get().loudNotification(ev, room);
                this._playAudioNotification(ev, room);
            }
        }
    },
};

if (!global.mxNotifier) {
    global.mxNotifier = Notifier;
}

module.exports = global.mxNotifier;
<commit_msg>Check for sound before logging it<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.
*/

import MatrixClientPeg from './MatrixClientPeg';
import PlatformPeg from './PlatformPeg';
import TextForEvent from './TextForEvent';
import Analytics from './Analytics';
import Avatar from './Avatar';
import dis from './dispatcher';
import sdk from './index';
import { _t } from './languageHandler';
import Modal from './Modal';
import SettingsStore, {SettingLevel} from "./settings/SettingsStore";

/*
 * Dispatches:
 * {
 *   action: "notifier_enabled",
 *   value: boolean
 * }
 */

const MAX_PENDING_ENCRYPTED = 20;

const Notifier = {
    notifsByRoom: {},

    // A list of event IDs that we've received but need to wait until
    // they're decrypted until we decide whether to notify for them
    // or not
    pendingEncryptedEventIds: [],

    notificationMessageForEvent: function(ev) {
        return TextForEvent.textForEvent(ev);
    },

    _displayPopupNotification: function(ev, room) {
        const plaf = PlatformPeg.get();
        if (!plaf) {
            return;
        }
        if (!plaf.supportsNotifications() || !plaf.maySendNotifications()) {
            return;
        }
        if (global.document.hasFocus()) {
            return;
        }

        let msg = this.notificationMessageForEvent(ev);
        if (!msg) return;

        let title;
        if (!ev.sender || room.name === ev.sender.name) {
            title = room.name;
            // notificationMessageForEvent includes sender,
            // but we already have the sender here
            if (ev.getContent().body) msg = ev.getContent().body;
        } else if (ev.getType() === 'm.room.member') {
            // context is all in the message here, we don't need
            // to display sender info
            title = room.name;
        } else if (ev.sender) {
            title = ev.sender.name + " (" + room.name + ")";
            // notificationMessageForEvent includes sender,
            // but we've just out sender in the title
            if (ev.getContent().body) msg = ev.getContent().body;
        }

        if (!this.isBodyEnabled()) {
            msg = '';
        }

        const avatarUrl = ev.sender ? Avatar.avatarUrlForMember(ev.sender, 40, 40, 'crop') : null;
        const notif = plaf.displayNotification(title, msg, avatarUrl, room);

        // if displayNotification returns non-null,  the platform supports
        // clearing notifications later, so keep track of this.
        if (notif) {
            if (this.notifsByRoom[ev.getRoomId()] === undefined) this.notifsByRoom[ev.getRoomId()] = [];
            this.notifsByRoom[ev.getRoomId()].push(notif);
        }
    },

    getSoundForRoom: async function(roomId) {
        // We do no caching here because the SDK caches the event content
        // and the browser will cache the sound.
        let content = SettingsStore.getValue("notificationSound", roomId);
        if (!content) {
            content = SettingsStore.getValue("notificationSound");
            if (!content) {
                return null;
            }
        }

        if (!content.url) {
            console.warn(`${roomId} has custom notification sound event, but no url key`);
            return null;
        }

        return {
            url: MatrixClientPeg.get().mxcUrlToHttp(content.url),
            name: content.name,
            type: content.type,
            size: content.size,
        };
    },

    _playAudioNotification: function(ev, room) {
        this.getSoundForRoom(room.roomId).then((sound) => {
            console.log(`Got sound ${sound && sound.name ? sound.name : "default"} for ${room.roomId}`);
            // XXX: How do we ensure this is a sound file and not
            // going to be exploited?
            const selector = document.querySelector(sound ? `audio[src='${sound.url}']` : "#messageAudio");
            let audioElement = selector;
            if (!selector) {
                if (!sound) {
                    console.error("Tried to play alert sound but missing #messageAudio");
                    return;
                }
                audioElement = new Audio(sound.url);
                if (sound.type) {
                    audioElement.type = sound.type;
                }
                document.body.appendChild(audioElement);
            }
            audioElement.play();
        }).catch((ex) => {
            console.warn("Caught error when trying to fetch room notification sound:", ex);
        });
    },

    start: function() {
        this.boundOnEvent = this.onEvent.bind(this);
        this.boundOnSyncStateChange = this.onSyncStateChange.bind(this);
        this.boundOnRoomReceipt = this.onRoomReceipt.bind(this);
        this.boundOnEventDecrypted = this.onEventDecrypted.bind(this);
        MatrixClientPeg.get().on('event', this.boundOnEvent);
        MatrixClientPeg.get().on('Room.receipt', this.boundOnRoomReceipt);
        MatrixClientPeg.get().on('Event.decrypted', this.boundOnEventDecrypted);
        MatrixClientPeg.get().on("sync", this.boundOnSyncStateChange);
        this.toolbarHidden = false;
        this.isSyncing = false;
    },

    stop: function() {
        if (MatrixClientPeg.get() && this.boundOnRoomTimeline) {
            MatrixClientPeg.get().removeListener('Event', this.boundOnEvent);
            MatrixClientPeg.get().removeListener('Room.receipt', this.boundOnRoomReceipt);
            MatrixClientPeg.get().removeListener('Event.decrypted', this.boundOnEventDecrypted);
            MatrixClientPeg.get().removeListener('sync', this.boundOnSyncStateChange);
        }
        this.isSyncing = false;
    },

    supportsDesktopNotifications: function() {
        const plaf = PlatformPeg.get();
        return plaf && plaf.supportsNotifications();
    },

    setEnabled: function(enable, callback) {
        const plaf = PlatformPeg.get();
        if (!plaf) return;

        // Dev note: We don't set the "notificationsEnabled" setting to true here because it is a
        // calculated value. It is determined based upon whether or not the master rule is enabled
        // and other flags. Setting it here would cause a circular reference.

        Analytics.trackEvent('Notifier', 'Set Enabled', enable);

        // make sure that we persist the current setting audio_enabled setting
        // before changing anything
        if (SettingsStore.isLevelSupported(SettingLevel.DEVICE)) {
            SettingsStore.setValue("audioNotificationsEnabled", null, SettingLevel.DEVICE, this.isEnabled());
        }

        if (enable) {
            // Attempt to get permission from user
            plaf.requestNotificationPermission().done((result) => {
                if (result !== 'granted') {
                    // The permission request was dismissed or denied
                    // TODO: Support alternative branding in messaging
                    const description = result === 'denied'
                        ? _t('Riot does not have permission to send you notifications - please check your browser settings')
                        : _t('Riot was not given permission to send notifications - please try again');
                    const ErrorDialog = sdk.getComponent('dialogs.ErrorDialog');
                    Modal.createTrackedDialog('Unable to enable Notifications', result, ErrorDialog, {
                        title: _t('Unable to enable Notifications'),
                        description,
                    });
                    return;
                }

                if (callback) callback();
                dis.dispatch({
                    action: "notifier_enabled",
                    value: true,
                });
            });
        } else {
            dis.dispatch({
                action: "notifier_enabled",
                value: false,
            });
        }
        // set the notifications_hidden flag, as the user has knowingly interacted
        // with the setting we shouldn't nag them any further
        this.setToolbarHidden(true);
    },

    isEnabled: function() {
        return this.isPossible() && SettingsStore.getValue("notificationsEnabled");
    },

    isPossible: function() {
        const plaf = PlatformPeg.get();
        if (!plaf) return false;
        if (!plaf.supportsNotifications()) return false;
        if (!plaf.maySendNotifications()) return false;

        return true; // possible, but not necessarily enabled
    },

    isBodyEnabled: function() {
        return this.isEnabled() && SettingsStore.getValue("notificationBodyEnabled");
    },

    isAudioEnabled: function() {
        return this.isEnabled() && SettingsStore.getValue("audioNotificationsEnabled");
    },

    setToolbarHidden: function(hidden, persistent = true) {
        this.toolbarHidden = hidden;

        Analytics.trackEvent('Notifier', 'Set Toolbar Hidden', hidden);

        // XXX: why are we dispatching this here?
        // this is nothing to do with notifier_enabled
        dis.dispatch({
            action: "notifier_enabled",
            value: this.isEnabled(),
        });

        // update the info to localStorage for persistent settings
        if (persistent && global.localStorage) {
            global.localStorage.setItem("notifications_hidden", hidden);
        }
    },

    shouldShowToolbar: function() {
        const client = MatrixClientPeg.get();
        if (!client) {
            return false;
        }
        const isGuest = client.isGuest();
        return !isGuest && this.supportsDesktopNotifications() &&
            !this.isEnabled() && !this._isToolbarHidden();
    },

    _isToolbarHidden: function() {
        // Check localStorage for any such meta data
        if (global.localStorage) {
            return global.localStorage.getItem("notifications_hidden") === "true";
        }

        return this.toolbarHidden;
    },

    onSyncStateChange: function(state) {
        if (state === "SYNCING") {
            this.isSyncing = true;
        } else if (state === "STOPPED" || state === "ERROR") {
            this.isSyncing = false;
        }
    },

    onEvent: function(ev) {
        if (!this.isSyncing) return; // don't alert for any messages initially
        if (ev.sender && ev.sender.userId === MatrixClientPeg.get().credentials.userId) return;

        // If it's an encrypted event and the type is still 'm.room.encrypted',
        // it hasn't yet been decrypted, so wait until it is.
        if (ev.isBeingDecrypted() || ev.isDecryptionFailure()) {
            this.pendingEncryptedEventIds.push(ev.getId());
            // don't let the list fill up indefinitely
            while (this.pendingEncryptedEventIds.length > MAX_PENDING_ENCRYPTED) {
                this.pendingEncryptedEventIds.shift();
            }
            return;
        }

        this._evaluateEvent(ev);
    },

    onEventDecrypted: function(ev) {
        // 'decrypted' means the decryption process has finished: it may have failed,
        // in which case it might decrypt soon if the keys arrive
        if (ev.isDecryptionFailure()) return;

        const idx = this.pendingEncryptedEventIds.indexOf(ev.getId());
        if (idx === -1) return;

        this.pendingEncryptedEventIds.splice(idx, 1);
        this._evaluateEvent(ev);
    },

    onRoomReceipt: function(ev, room) {
        if (room.getUnreadNotificationCount() === 0) {
            // ideally we would clear each notification when it was read,
            // but we have no way, given a read receipt, to know whether
            // the receipt comes before or after an event, so we can't
            // do this. Instead, clear all notifications for a room once
            // there are no notifs left in that room., which is not quite
            // as good but it's something.
            const plaf = PlatformPeg.get();
            if (!plaf) return;
            if (this.notifsByRoom[room.roomId] === undefined) return;
            for (const notif of this.notifsByRoom[room.roomId]) {
                plaf.clearNotification(notif);
            }
            delete this.notifsByRoom[room.roomId];
        }
    },

    _evaluateEvent: function(ev) {
        const room = MatrixClientPeg.get().getRoom(ev.getRoomId());
        const actions = MatrixClientPeg.get().getPushActionsForEvent(ev);
        if (actions && actions.notify) {
            if (this.isEnabled()) {
                this._displayPopupNotification(ev, room);
            }
            if (actions.tweaks.sound && this.isAudioEnabled()) {
                PlatformPeg.get().loudNotification(ev, room);
                this._playAudioNotification(ev, room);
            }
        }
    },
};

if (!global.mxNotifier) {
    global.mxNotifier = Notifier;
}

module.exports = global.mxNotifier;
<|endoftext|>


<commit_before>import Banner from 'components/Banner/Banner.react';
import Button from 'components/Button/Button.react';
import Event from 'components/Event/Event.react';
import FAQ from 'components/FAQ/FAQ.react';
import Hackry from 'hackry';
import Logo from 'components/Logo/Logo.react';
import Navbar from 'components/Navbar/Navbar.react';
import React from 'react';
import styles from 'web/App.scss';
import Summary from 'components/Summary/Summary.react';
import Section from 'components/Section/Section.react.js'
import Track from 'components/Track/Track.react';
import tracks from 'data/tracks';

export default class App extends React.Component {

  constructor(props) {
    super(props);

    this.hackry = new Hackry('NQZBtoIMDJ');
    this.state = {
      faqs: [],
      events: []
    };
  }

  componentWillMount() {
    this.hackry.faqs((faqs) => {
      this.setState({
        faqs: faqs
      });
    });

    this.hackry.events((events) => {
      this.setState({
        events: events
      });
    });
  }

  renderComingSoon() {
    return (

Coming soon...

    )
  }

  render() {
    return (

            <Navbar
             items={[{
               name: 'Tracks',
               scrollId: 'tracks'
             }, {
               name: 'FAQs',
               scrollId: 'faqs'
             }, {
               name: 'Schedule',
               scrollId: 'schedule'
             }]} />

          <Logo />

              <Button
               title='Registration Coming Soon'
               color='darkBlue' />
              <Button
               title='Sponsor'
               externalLink='/sponsorship'
               color='red' />

            {Object.keys(tracks).map((name, index) => {
              const track = tracks[name.toLowerCase()];
              return (
                <Track
                 key={index}
                 name={name.charAt(0).toUpperCase() + name.slice(1)}
                 image={track.image}
                 description={track.description} />
              )
            })}

            {this.state.faqs.length > 0 ? this.state.faqs.map((faq, index) => {
              return (
                <FAQ
                 key={index}
                 question={faq.question}
                 answer={faq.answer} />
              )
            }) : this.renderComingSoon()}

            {this.state.events.length > 0 ? this.state.events.map((event, index) => {
              return (
                <Event
                 key={index}
                 name={event.name}
                 when='idk'
                 where={event.location}
                 description={event.description} />
              )
            }) : this.renderComingSoon()}

    );
  }

}
<commit_msg>Add registration link<commit_after>import Banner from 'components/Banner/Banner.react';
import Button from 'components/Button/Button.react';
import Event from 'components/Event/Event.react';
import FAQ from 'components/FAQ/FAQ.react';
import Hackry from 'hackry';
import Logo from 'components/Logo/Logo.react';
import Navbar from 'components/Navbar/Navbar.react';
import React from 'react';
import styles from 'web/App.scss';
import Summary from 'components/Summary/Summary.react';
import Section from 'components/Section/Section.react.js'
import Track from 'components/Track/Track.react';
import tracks from 'data/tracks';

export default class App extends React.Component {

  constructor(props) {
    super(props);

    this.hackry = new Hackry('NQZBtoIMDJ');
    this.state = {
      faqs: [],
      events: []
    };
  }

  componentWillMount() {
    this.hackry.faqs((faqs) => {
      this.setState({
        faqs: faqs
      });
    });

    this.hackry.events((events) => {
      this.setState({
        events: events
      });
    });
  }

  renderComingSoon() {
    return (

Coming soon...

    )
  }

  render() {
    return (

            <Navbar
             items={[{
               name: 'Tracks',
               scrollId: 'tracks'
             }, {
               name: 'FAQs',
               scrollId: 'faqs'
             }, {
               name: 'Schedule',
               scrollId: 'schedule'
             }]} />

          <Logo />

              <Button
               title='Register'
               externalLink='https://dashboard.hackry.io/register?hackathonId=NQZBtoIMDJ'
               color='darkBlue' />
              <Button
               title='Sponsor'
               externalLink='/sponsorship'
               color='red' />

            {Object.keys(tracks).map((name, index) => {
              const track = tracks[name.toLowerCase()];
              return (
                <Track
                 key={index}
                 name={name.charAt(0).toUpperCase() + name.slice(1)}
                 image={track.image}
                 description={track.description} />
              )
            })}

            {this.state.faqs.length > 0 ? this.state.faqs.map((faq, index) => {
              return (
                <FAQ
                 key={index}
                 question={faq.question}
                 answer={faq.answer} />
              )
            }) : this.renderComingSoon()}

            {this.state.events.length > 0 ? this.state.events.map((event, index) => {
              return (
                <Event
                 key={index}
                 name={event.name}
                 when='idk'
                 where={event.location}
                 description={event.description} />
              )
            }) : this.renderComingSoon()}

    );
  }

}
<|endoftext|>


<commit_before>import request from 'superagent';
import Defaults from './Defaults';

import path from 'path';
import { parse, resolve } from 'url';

class Particle {

	constructor(options = Defaults) {
		Object.assign(this, options);
	}

	get baseUrl() { return this.__baseUrl.href; }
	set baseUrl(uri) { this.__baseUrl = parse(uri); }

	url() { return resolve(this.baseUrl, path.join.apply(null, arguments)); }

	login({ username, password, tokenDuration = this.tokenDuration }) {
		return Particle.post(this.url('oauth/token'), {
			username,
			password,
			grant_type: 'password',
			client_id: this.clientId,
			client_secret: this.clientSecret,
			expires_in: tokenDuration,
		});
	}

	createUser({ username, password }) {
		return Particle.post(this.url('v1/users'), {
			username, password,
		});
	}

	removeAccessToken({ username, password, token }) {
		return Particle.delete(this.url('v1/access_tokens', token), {
			access_token: token,
		}, { username, password });
	}

	listDevices({ auth }) {
		return Particle.get(this.url('v1/devices'), auth);
	}

	getDevice({ deviceId, auth }) {
		return Particle.get(this.url('v1/devices', deviceId), auth);
	}

	claimDevice({ deviceId, auth }) {
		return Particle.post(this.url('v1/devices'), {
			id: deviceId,
		}, auth);
	}

	removeDevice({ deviceId, auth }) {
		return Particle.delete(this.url('v1/devices', deviceId), null, auth);
	}

	renameDevice({ deviceId, name, auth }) {
		return Particle.put(this.url('v1/devices', deviceId), { name }, auth);
	}

	getClaimCode({ auth, iccid = undefined }) {
		return Particle.post(this.url('v1/device_claims'), { iccid }, auth);
	}

	changeProduct({ deviceId, productId, shouldUpdate, auth }) {
		return Particle.put(this.url('v1/devices', deviceId), {
			product_id: productId,
			update_after_claim: shouldUpdate || false,
		}, auth);
	}

	getVariable({ deviceId, name, auth }) {
		return Particle.get(this.url('v1/devices', deviceId, name), auth);
	}

	signalDevice({ deviceId, signal, auth }) {
		return Particle.put(this.url('v1/devices/', deviceId), {
			signal: ( !!signal ? 1 : 0 ),
		}, auth);
	}

	flashTinker({ deviceId, auth }) {
		return Particle.put(this.url('v1/devices', deviceId), {
			app: 'tinker',
		}, auth);
	}

	// TODO: Platform agnostic flashDevice (flashCore in SparkJS)
	// TODO: Platform agnostic compileCode
	// NOTE: use Buffer: https://github.com/feross/buffer

	sendPublicKey({ deviceId, key, auth }) {
		return Particle.post(this.url('v1/provisioning', deviceId), {
			deviceID: deviceId,
			publicKey: ( typeof key === 'string' ? key : key.toString() ),
			filename: 'particle-api',
			order: `manual_${ new Date().getTime() }`,
		}, auth);
	}

	callFunction({ deviceId, name, argument, auth }) {
		return Particle.post(this.url('v1/devices', deviceId, name), {
			args: argument,
		}, auth);
	}

	getEventStream({ deviceId, name, auth }) {
		let uri;
		if (!deviceId) { uri = 'v1/events'; }
		else if (deviceId.toLowerCase() === 'mine') { uri = 'v1/devices/events'; }
		else { uri = `v1/devices/${ deviceId }/events`; }

		if (name) { uri += `/${ name }`; }
		// TODO: Add tests for event stream?
		return Particle.get(this.url(uri), auth);
	}

	publishEvent({ name, data, auth }) {
		return Particle.post(this.url('v1/devices/events'), {
			name,
			data,
		}, auth);
	}

	createWebhook({ deviceId, name, url, auth }) {
		const form = { event: name, url };
		if (deviceId === 'mine') { form.mydevices = true; }
		else { form.deviceid = deviceId; }
		return Particle.post(this.url('v1/webhooks'), form, auth);
	}

	deleteWebhook({ hookId, auth }) {
		return Particle.delete(this.url('v1/webhooks', hookId), null, auth);
	}

	listWebhooks({ auth }) {
		return Particle.get(this.url('v1/webhooks'), auth);
	}

	getUserInfo({ auth }) {
		return Particle.get(this.url('v1/user'), auth);
	}

	setUserInfo({ stripeToken, auth }) {
		return Particle.put(this.url('v1/user'), {
			stripe_token: stripeToken,
		}, auth);
	}

	checkSIM({ iccid, auth }) {
		return Particle.head(this.url('v1/sims', iccid), auth);
	}

	activateSIM({ iccid, auth }) {
		return Particle.put(this.url('v1/sims', iccid), auth);
	}

	static get(uri, auth) {
		return Particle.request({ uri, auth, method: 'get' });
	}

	static head(uri, auth) {
		return Particle.request({ uri, auth, method: 'head' });
	}

	static post(uri, form, auth) {
		return Particle.request({ uri, form, auth, method: 'post' });
	}

	static put(uri, form, auth) {
		return Particle.request({ uri, form, auth, method: 'put' });
	}

	static delete(uri, form, auth) {
		return Particle.request({ uri, form, auth, method: 'delete' });
	}

	static request({ uri, method, form = undefined, auth }) {
		return new Promise((fulfill, reject) => {
			const req = request(method, uri);
			if (auth) { req.set(Particle.headers(auth)); }
			if (form) {
				if (form.username) { req.type('form'); }
				req.send(form);
			}
			req.end((error, res) => {
				const body = res && res.body;
				if (error) {
					const code = error.status;
					let errorDescription = `${ code ? 'HTTP error' : 'Network error' } ${ code } from ${ uri }`;
					if (body && body.error_description) { errorDescription += ' - ' + body.error_description; }
					reject({ code, errorDescription, error });
				}
				else {
					fulfill(body);
				}
			});
		});
	}

	static headers(auth) {
		let header;
		if (!auth) { return undefined; }
		if (typeof auth === 'object') {
			const str = `${ auth.username }:${ auth.password }`;
			header = `Basic ${ (new Buffer(str, 'utf8')).toString('base64') }`;
		}
		else { header = `Bearer ${ auth }`; }
		return { Authorization: header };
	}
}

export default Particle;
<commit_msg>Fix activateSIM.<commit_after>import request from 'superagent';
import Defaults from './Defaults';

import path from 'path';
import { parse, resolve } from 'url';

class Particle {

	constructor(options = Defaults) {
		Object.assign(this, options);
	}

	get baseUrl() { return this.__baseUrl.href; }
	set baseUrl(uri) { this.__baseUrl = parse(uri); }

	url() { return resolve(this.baseUrl, path.join.apply(null, arguments)); }

	login({ username, password, tokenDuration = this.tokenDuration }) {
		return Particle.post(this.url('oauth/token'), {
			username,
			password,
			grant_type: 'password',
			client_id: this.clientId,
			client_secret: this.clientSecret,
			expires_in: tokenDuration,
		});
	}

	createUser({ username, password }) {
		return Particle.post(this.url('v1/users'), {
			username, password,
		});
	}

	removeAccessToken({ username, password, token }) {
		return Particle.delete(this.url('v1/access_tokens', token), {
			access_token: token,
		}, { username, password });
	}

	listDevices({ auth }) {
		return Particle.get(this.url('v1/devices'), auth);
	}

	getDevice({ deviceId, auth }) {
		return Particle.get(this.url('v1/devices', deviceId), auth);
	}

	claimDevice({ deviceId, auth }) {
		return Particle.post(this.url('v1/devices'), {
			id: deviceId,
		}, auth);
	}

	removeDevice({ deviceId, auth }) {
		return Particle.delete(this.url('v1/devices', deviceId), null, auth);
	}

	renameDevice({ deviceId, name, auth }) {
		return Particle.put(this.url('v1/devices', deviceId), { name }, auth);
	}

	getClaimCode({ auth, iccid = undefined }) {
		return Particle.post(this.url('v1/device_claims'), { iccid }, auth);
	}

	changeProduct({ deviceId, productId, shouldUpdate, auth }) {
		return Particle.put(this.url('v1/devices', deviceId), {
			product_id: productId,
			update_after_claim: shouldUpdate || false,
		}, auth);
	}

	getVariable({ deviceId, name, auth }) {
		return Particle.get(this.url('v1/devices', deviceId, name), auth);
	}

	signalDevice({ deviceId, signal, auth }) {
		return Particle.put(this.url('v1/devices/', deviceId), {
			signal: ( !!signal ? 1 : 0 ),
		}, auth);
	}

	flashTinker({ deviceId, auth }) {
		return Particle.put(this.url('v1/devices', deviceId), {
			app: 'tinker',
		}, auth);
	}

	// TODO: Platform agnostic flashDevice (flashCore in SparkJS)
	// TODO: Platform agnostic compileCode
	// NOTE: use Buffer: https://github.com/feross/buffer

	sendPublicKey({ deviceId, key, auth }) {
		return Particle.post(this.url('v1/provisioning', deviceId), {
			deviceID: deviceId,
			publicKey: ( typeof key === 'string' ? key : key.toString() ),
			filename: 'particle-api',
			order: `manual_${ new Date().getTime() }`,
		}, auth);
	}

	callFunction({ deviceId, name, argument, auth }) {
		return Particle.post(this.url('v1/devices', deviceId, name), {
			args: argument,
		}, auth);
	}

	getEventStream({ deviceId, name, auth }) {
		let uri;
		if (!deviceId) { uri = 'v1/events'; }
		else if (deviceId.toLowerCase() === 'mine') { uri = 'v1/devices/events'; }
		else { uri = `v1/devices/${ deviceId }/events`; }

		if (name) { uri += `/${ name }`; }
		// TODO: Add tests for event stream?
		return Particle.get(this.url(uri), auth);
	}

	publishEvent({ name, data, auth }) {
		return Particle.post(this.url('v1/devices/events'), {
			name,
			data,
		}, auth);
	}

	createWebhook({ deviceId, name, url, auth }) {
		const form = { event: name, url };
		if (deviceId === 'mine') { form.mydevices = true; }
		else { form.deviceid = deviceId; }
		return Particle.post(this.url('v1/webhooks'), form, auth);
	}

	deleteWebhook({ hookId, auth }) {
		return Particle.delete(this.url('v1/webhooks', hookId), null, auth);
	}

	listWebhooks({ auth }) {
		return Particle.get(this.url('v1/webhooks'), auth);
	}

	getUserInfo({ auth }) {
		return Particle.get(this.url('v1/user'), auth);
	}

	setUserInfo({ stripeToken, auth }) {
		return Particle.put(this.url('v1/user'), {
			stripe_token: stripeToken,
		}, auth);
	}

	checkSIM({ iccid, auth }) {
		return Particle.head(this.url('v1/sims', iccid), auth);
	}

	activateSIM({ iccid, auth }) {
		return Particle.put(this.url('v1/sims', iccid), null, auth);
	}

	static get(uri, auth) {
		return Particle.request({ uri, auth, method: 'get' });
	}

	static head(uri, auth) {
		return Particle.request({ uri, auth, method: 'head' });
	}

	static post(uri, form, auth) {
		return Particle.request({ uri, form, auth, method: 'post' });
	}

	static put(uri, form, auth) {
		return Particle.request({ uri, form, auth, method: 'put' });
	}

	static delete(uri, form, auth) {
		return Particle.request({ uri, form, auth, method: 'delete' });
	}

	static request({ uri, method, form = undefined, auth }) {
		return new Promise((fulfill, reject) => {
			const req = request(method, uri);
			if (auth) { req.set(Particle.headers(auth)); }
			if (form) {
				if (form.username) { req.type('form'); }
				req.send(form);
			}
			req.end((error, res) => {
				const body = res && res.body;
				if (error) {
					const code = error.status;
					let errorDescription = `${ code ? 'HTTP error' : 'Network error' } ${ code } from ${ uri }`;
					if (body && body.error_description) { errorDescription += ' - ' + body.error_description; }
					reject({ code, errorDescription, error });
				}
				else {
					fulfill(body);
				}
			});
		});
	}

	static headers(auth) {
		let header;
		if (!auth) { return undefined; }
		if (typeof auth === 'object') {
			const str = `${ auth.username }:${ auth.password }`;
			header = `Basic ${ (new Buffer(str, 'utf8')).toString('base64') }`;
		}
		else { header = `Bearer ${ auth }`; }
		return { Authorization: header };
	}
}

export default Particle;
<|endoftext|>


<commit_before>var request = require('request');
var num_ligne = 3;

var info = function(num_ligne) {

  return { end : "end"};
  };

module.exports.num_ligne = num_ligne;
module.exports.info = info;
<commit_msg>Update RATP_App.js<commit_after>var request = require('request');
var num_ligne = 3;

var info = function(num_ligne) {
  var res = {end : "end"};
  return res;
  };

module.exports.num_ligne = num_ligne;
module.exports.info = info;
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import invariant from 'invariant';
import classNames from 'classnames';
import shortid from 'shortid';
import status from './constants/status';

class Receiver extends Component {
  constructor(props) {
    super(props);

    this.onDragEnter = this.onDragEnter.bind(this);
    this.onDragOver = this.onDragOver.bind(this);
    this.onDragLeave = this.onDragLeave.bind(this);
    this.onFileDrop = this.onFileDrop.bind(this);

    // this is to monitor the hierarchy
    // for window onDragEnter event
    this.state = {
      dragLevel: 0,
    };
  }

  componentDidMount() {
    invariant(
      !!window.DragEvent && !!window.DataTransfer,
      'Upload end point must be provided to upload files'
    );

    window.addEventListener('dragenter', this.onDragEnter);
    window.addEventListener('dragleave', this.onDragLeave);
    window.addEventListener('dragover', this.onDragOver);
    window.addEventListener('drop', this.onFileDrop);
  }

  componentWillUnmount() {
    window.removeEventListener('dragenter', this.onDragEnter);
    window.removeEventListener('dragleave', this.onDragLeave);
    window.removeEventListener('dragover', this.onDragOver);
    window.removeEventListener('drop', this.onFileDrop);
  }

  onDragEnter(e) {
    const dragLevel = this.state.dragLevel + 1;

    this.setState({ dragLevel });

    if (!this.props.isOpen) {
      this.props.onDragEnter(e);
    }
  }

  onDragLeave(e) {
    const dragLevel = this.state.dragLevel - 1;

    this.setState({ dragLevel });

    if (dragLevel === 0) {
      this.props.onDragLeave(e);
    }
  }

  onDragOver(e) {
    e.preventDefault();
    this.props.onDragOver(e);
  }

  onFileDrop(e) {
    // eslint-disable-next-line no-param-reassign
    e = e || window.event;
    e.preventDefault();

    const files = [];

    if (!!e.dataTransfer) {
      const fileList = e.dataTransfer.files || [];

      for (let i = 0; i < fileList.length; i ++) {
        fileList[i].id = shortid.generate();
        fileList[i].status = status.PENDING;
        fileList[i].progress = 0;
        fileList[i].src = null;
        files.push(fileList[i]);
      }
    }

    // reset drag level once dropped
    this.setState({ dragLevel: 0 });

    this.props.onFileDrop(e, files);
  }

  render() {
    const { isOpen, customClass, style, children } = this.props;

    return (
      isOpen ? (

          {children}

      ) : null
    );
  }
}

Receiver.propTypes = {
  children: PropTypes.oneOfType([
    PropTypes.element,
    PropTypes.arrayOf(PropTypes.element),
  ]),
  customClass: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.arrayOf(PropTypes.string),
  ]),
  isOpen: PropTypes.bool.isRequired,
  onDragEnter: PropTypes.func.isRequired,
  onDragOver: PropTypes.func,
  onDragLeave: PropTypes.func.isRequired,
  onFileDrop: PropTypes.func.isRequired,
  style: PropTypes.object,
};

export default Receiver;
<commit_msg>Update Receiver.js<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import invariant from 'invariant';
import classNames from 'classnames';
import shortid from 'shortid';
import status from './constants/status';

class Receiver extends Component {
  constructor(props) {
    super(props);

    this.onDragEnter = this.onDragEnter.bind(this);
    this.onDragOver = this.onDragOver.bind(this);
    this.onDragLeave = this.onDragLeave.bind(this);
    this.onFileDrop = this.onFileDrop.bind(this);

    // this is to monitor the hierarchy
    // for window onDragEnter event
    this.state = {
      dragLevel: 0,
    };
  }

  componentDidMount() {
    invariant(
      !!window.DragEvent && !!window.DataTransfer,
      'Upload end point must be provided to upload files'
    );

    (document.getElementById(this.props.wrapperId) || window).addEventListener('dragenter', this.onDragEnter);
    (document.getElementById(this.props.wrapperId) || window).addEventListener('dragleave', this.onDragLeave);
    (document.getElementById(this.props.wrapperId) || window).addEventListener('dragover', this.onDragOver);
    (document.getElementById(this.props.wrapperId) || window).addEventListener('drop', this.onFileDrop);
  }

  componentWillUnmount() {
    (document.getElementById(this.props.wrapperId) || window).removeEventListener('dragenter', this.onDragEnter);
    (document.getElementById(this.props.wrapperId) || window).removeEventListener('dragleave', this.onDragLeave);
    (document.getElementById(this.props.wrapperId) || window).removeEventListener('dragover', this.onDragOver);
    (document.getElementById(this.props.wrapperId) || window).removeEventListener('drop', this.onFileDrop);
  }

  onDragEnter(e) {
    const dragLevel = this.state.dragLevel + 1;

    this.setState({ dragLevel });

    if (!this.props.isOpen) {
      this.props.onDragEnter(e);
    }
  }

  onDragLeave(e) {
    const dragLevel = this.state.dragLevel - 1;

    this.setState({ dragLevel });

    if (dragLevel === 0) {
      this.props.onDragLeave(e);
    }
  }

  onDragOver(e) {
    e.preventDefault();
    this.props.onDragOver(e);
  }

  onFileDrop(e) {
    // eslint-disable-next-line no-param-reassign
    e = e || window.event;
    e.preventDefault();

    const files = [];

    if (!!e.dataTransfer) {
      const fileList = e.dataTransfer.files || [];

      for (let i = 0; i < fileList.length; i ++) {
        fileList[i].id = shortid.generate();
        fileList[i].status = status.PENDING;
        fileList[i].progress = 0;
        fileList[i].src = null;
        files.push(fileList[i]);
      }
    }

    // reset drag level once dropped
    this.setState({ dragLevel: 0 });

    this.props.onFileDrop(e, files);
  }

  render() {
    const { isOpen, customClass, style, children } = this.props;

    return (
      isOpen ? (

          {children}

      ) : null
    );
  }
}

Receiver.propTypes = {
  children: PropTypes.oneOfType([
    PropTypes.element,
    PropTypes.arrayOf(PropTypes.element),
  ]),
  customClass: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.arrayOf(PropTypes.string),
  ]),
  isOpen: PropTypes.bool.isRequired,
  onDragEnter: PropTypes.func.isRequired,
  onDragOver: PropTypes.func,
  onDragLeave: PropTypes.func.isRequired,
  onFileDrop: PropTypes.func.isRequired,
  style: PropTypes.object,
  wrapperId: PropTypes.string,
};

export default Receiver;
<|endoftext|>


<commit_before>function is_numeric( mixed_var ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: David
    // +   improved by: taith
    // *     example 1: is_numeric(186.31);
    // *     returns 1: true
    // *     example 2: is_numeric('Kevin van Zonneveld');
    // *     returns 2: false
    // *     example 3: is_numeric('+186.31e2');
    // *     returns 3: true

    return !isNaN(mixed_var * 1);
}<commit_msg>Many fixes<commit_after>function is_numeric( mixed_var ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: David
    // +   improved by: taith
    // +   bugfixed by: Tim de Koning
    // *     example 1: is_numeric(186.31);
    // *     returns 1: true
    // *     example 2: is_numeric('Kevin van Zonneveld');
    // *     returns 2: false
    // *     example 3: is_numeric('+186.31e2');
    // *     returns 3: true
    // *     example 4: is_numeric('');
    // *     returns 4: false

    if (mixed_var === '') {
        return false;
    }

    return !isNaN(mixed_var * 1);
}<|endoftext|>


<commit_before>'use strict';

angular
  .module('ta-maxlength', [])
  .directive('taMaxlength', function ($timeout, textAngularManager, $translate) {
    return {
      restrict: 'A',
      link: function ($scope, element, attrs) {
        var editor, editorID, editorContainer, maxLength = parseInt(attrs.taMaxlength);
        var initDone = false;

        if(isNaN(maxLength)) {
          console.warn('Invalid number for ta-maxlength, automatically set to POSITIVE_INFINITY');
          maxLength = Number.POSITIVE_INFINITY;
        }

        var parseContent = function(content, returnValue) {
          //rangy span --> should better not be manipulated
          /*var rangySpanRegex = /<\/span>/;
          var rangySpan = content.match(rangySpanRegex);*/

          //remove zero-width no break spaces
          content = content.replace(new RegExp('', 'g'), '');

          //remove empty paragraphs if existing at the beginning
          if(content.indexOf('

') == 0) {
            content = content.substr(7);
          }

          //build dom stack
          var domStack = [];

          //parse html text
          var strippedText = '';
          var printedChars = 0;
          var parseMode = 'text';
          var tagName = '';

          for(var i=0; i<content.length; i++) {
            var currentChar = content[i];
            var nextChar = (i<content.length-1) ? content.length[i+1] : '';
            strippedText += currentChar;

            if(currentChar == '<') {
              if(nextChar == '/') {
                domStack.pop();
                parseMode = 'ignoreHTML';
              } else {
                parseMode = 'findTagName';
              }
            } else {
              if(parseMode == 'text') {
                if(currentChar == '&') {
                  parseMode = 'htmlSpecialChar';
                } else {
                  printedChars++;

                  if(printedChars == maxLength) {
                    //close remaining tags and stop
                    domStack = domStack.reverse();
                    for(var domStackIndex=0; domStackIndex<domStack.length; domStackIndex++) {
                      var tag = domStack[domStackIndex];
                      strippedText += '</' + tag + '>';
                    }
                    domStack = [];

                    switch(returnValue) {
                      case 'strippedText':
                        return strippedText;
                      case 'charCount':
                        return printedChars;
                    }
                  }
                }
              } else if(parseMode == 'htmlSpecialChar') {
                if(currentChar == ';') {
                  printedChars++;
                  parseMode = 'text';
                }
                //if no semicolon, HTML special char is still parsed; do nothing
              } else if(parseMode == 'findTagName') {
                if(currentChar == '>') {
                  //tag closes
                  domStack.push(tagName);
                  tagName = '';
                  parseMode = 'text';
                } else if(currentChar == ' ') {
                  //attributes after tag name
                  domStack.push(tagName);
                  tagName = '';
                  parseMode = 'ignoreHTML';
                } else if(currentChar == '/') {
                  //self closing tags
                  tagName = '';
                  parseMode = 'ignoreHTML';
                } else {
                  //letters of tag name
                  tagName += currentChar;
                }
              } else if(parseMode == 'ignoreHTML') {
                if(currentChar == '>') {
                  parseMode = 'text';
                }
              }
            }
          }

          switch(returnValue) {
            case 'strippedText':
              return strippedText;
            case 'charCount':
              return printedChars;
          }
        };

        var stripContent = function(content) {
          return parseContent(content, 'strippedText');
        };

        var updateRemainingChars = function() {
          var charCountDiv = angular.element(document.querySelector('#taInnerCharCount'+editorID));
          var remainingChars = maxLength - getContentLength(editor.scope.html);

          //should actually never occur, but just in case...
          if(remainingChars < 0) {
            editor.scope.html = stripContent(editor.scope.html);
            remainingChars = 0;
          }

          if(remainingChars == 0) {
            charCountDiv.html('' + remainingChars + ' ' + $translate.instant('CHARACTERS_LEFT') + '');
          } else if(remainingChars <= 15) {
            charCountDiv.html('' + remainingChars + ' ' + $translate.instant('CHARACTERS_LEFT') + '');
          } else {
            charCountDiv.html(remainingChars + ' ' + $translate.instant('CHARACTERS_LEFT'));
          }
        };

        var getEditor = function() {
          return editor.scope.displayElements.text[0];
        };

        var getContentLength = function(content) {
          return parseContent(content, 'charCount');
        };

        var isNavigationKey = function(keyCode) {
          return ((keyCode >= 33) && (keyCode <= 40)) || ([8, 46].indexOf(keyCode) !== -1);
        };

        var isCopying = function(event) {
          return event.ctrlKey && ([65, 67, 88].indexOf(event.keyCode) !== -1);
        };

        $scope.$watch(function() {
          var editorInstance = textAngularManager.retrieveEditor(attrs.name);

          if((editorInstance !== undefined) && (editor === undefined)) {
            editor = editorInstance;

            if(!initDone) {
              //create DIV
              editorID = editor.scope.displayElements.text[0].id.substr(13);
              editorContainer = angular.element(document.querySelector('#taTextElement'+editorID));
              editorContainer.parent().append('

');
              initDone = true;
              updateRemainingChars();
            }

            getEditor().addEventListener('keydown', function(e) {
              if(!isNavigationKey(e.keyCode) && !isCopying(e) && (getContentLength(editor.scope.html) >= maxLength)) {
                e.preventDefault();
                return false;
              }
            });

            getEditor().addEventListener('click', function() {
              updateRemainingChars();
            });
          }

          if(editorInstance === undefined || editor.scope.html.trim() === '') {
            return '';
          } else {
            return editor.scope.html;
          }
        }, function() {
          var content = editor.scope.html;

          //check if text is too long
          var tmp = document.createElement('DIV');
          tmp.innerHTML = content;
          var contentLength = (tmp.textContent || tmp.innerText || '').length;
          if(contentLength > maxLength) {
            //strip HTML content
            editor.scope.html = stripContent(content);
          }
          updateRemainingChars();

          if(editor.scope.html.trim() == '') {
            $scope.strawberry = 'mjam';
          } else {
            $scope.strawberry = 'bäh!';
          }
        });
      }
    };
  });<commit_msg>trying to resolve promise from ta-maxlength<commit_after>'use strict';

angular
  .module('ta-maxlength', [])
  .directive('taMaxlength', function ($timeout, textAngularManager, $translate) {
    return {
      restrict: 'A',
      link: function ($scope, element, attrs) {
        var editor, editorID, editorContainer, maxLength = parseInt(attrs.taMaxlength);
        var initDone = false;

        if(isNaN(maxLength)) {
          console.warn('Invalid number for ta-maxlength, automatically set to POSITIVE_INFINITY');
          maxLength = Number.POSITIVE_INFINITY;
        }

        var parseContent = function(content, returnValue) {
          //rangy span --> should better not be manipulated
          /*var rangySpanRegex = /<\/span>/;
          var rangySpan = content.match(rangySpanRegex);*/

          //remove zero-width no break spaces
          content = content.replace(new RegExp('', 'g'), '');

          //remove empty paragraphs if existing at the beginning
          if(content.indexOf('

') == 0) {
            content = content.substr(7);
          }

          //build dom stack
          var domStack = [];

          //parse html text
          var strippedText = '';
          var printedChars = 0;
          var parseMode = 'text';
          var tagName = '';

          for(var i=0; i<content.length; i++) {
            var currentChar = content[i];
            var nextChar = (i<content.length-1) ? content.length[i+1] : '';
            strippedText += currentChar;

            if(currentChar == '<') {
              if(nextChar == '/') {
                domStack.pop();
                parseMode = 'ignoreHTML';
              } else {
                parseMode = 'findTagName';
              }
            } else {
              if(parseMode == 'text') {
                if(currentChar == '&') {
                  parseMode = 'htmlSpecialChar';
                } else {
                  printedChars++;

                  if(printedChars == maxLength) {
                    //close remaining tags and stop
                    domStack = domStack.reverse();
                    for(var domStackIndex=0; domStackIndex<domStack.length; domStackIndex++) {
                      var tag = domStack[domStackIndex];
                      strippedText += '</' + tag + '>';
                    }
                    domStack = [];

                    switch(returnValue) {
                      case 'strippedText':
                        return strippedText;
                      case 'charCount':
                        return printedChars;
                    }
                  }
                }
              } else if(parseMode == 'htmlSpecialChar') {
                if(currentChar == ';') {
                  printedChars++;
                  parseMode = 'text';
                }
                //if no semicolon, HTML special char is still parsed; do nothing
              } else if(parseMode == 'findTagName') {
                if(currentChar == '>') {
                  //tag closes
                  domStack.push(tagName);
                  tagName = '';
                  parseMode = 'text';
                } else if(currentChar == ' ') {
                  //attributes after tag name
                  domStack.push(tagName);
                  tagName = '';
                  parseMode = 'ignoreHTML';
                } else if(currentChar == '/') {
                  //self closing tags
                  tagName = '';
                  parseMode = 'ignoreHTML';
                } else {
                  //letters of tag name
                  tagName += currentChar;
                }
              } else if(parseMode == 'ignoreHTML') {
                if(currentChar == '>') {
                  parseMode = 'text';
                }
              }
            }
          }

          switch(returnValue) {
            case 'strippedText':
              return strippedText;
            case 'charCount':
              return printedChars;
          }
        };

        var stripContent = function(content) {
          return parseContent(content, 'strippedText');
        };

        var updateRemainingChars = function() {
          var charCountDiv = angular.element(document.querySelector('#taInnerCharCount'+editorID));
          var remainingChars = maxLength - getContentLength(editor.scope.html);

          //should actually never occur, but just in case...
          if(remainingChars < 0) {
            editor.scope.html = stripContent(editor.scope.html);
            remainingChars = 0;
          }

          if(remainingChars == 0) {
            charCountDiv.html('' + remainingChars + ' ' + $translate.instant('CHARACTERS_LEFT') + '');
          } else if(remainingChars <= 15) {
            charCountDiv.html('' + remainingChars + ' ' + $translate.instant('CHARACTERS_LEFT') + '');
          } else {
            charCountDiv.html(remainingChars + ' ' + $translate.instant('CHARACTERS_LEFT'));
          }
        };

        var getEditor = function() {
          return editor.scope.displayElements.text[0];
        };

        var getContentLength = function(content) {
          return parseContent(content, 'charCount');
        };

        var isNavigationKey = function(keyCode) {
          return ((keyCode >= 33) && (keyCode <= 40)) || ([8, 46].indexOf(keyCode) !== -1);
        };

        var isCopying = function(event) {
          return event.ctrlKey && ([65, 67, 88].indexOf(event.keyCode) !== -1);
        };

        $scope.$watch(function() {
          var editorInstance = textAngularManager.retrieveEditor(attrs.name);

          if((editorInstance !== undefined) && (editor === undefined)) {
            editor = editorInstance;

            if(!initDone) {
              //create DIV
              editorID = editor.scope.displayElements.text[0].id.substr(13);
              editorContainer = angular.element(document.querySelector('#taTextElement'+editorID));
              editorContainer.parent().append('

');
              initDone = true;
              updateRemainingChars();
            }

            getEditor().addEventListener('keydown', function(e) {
              if(!isNavigationKey(e.keyCode) && !isCopying(e) && (getContentLength(editor.scope.html) >= maxLength)) {
                e.preventDefault();
                return false;
              }
            });

            getEditor().addEventListener('click', function() {
              updateRemainingChars();
            });
          }

          if(editorInstance === undefined) {
            return '';
          } else if(editor.scope.html.trim() === '') {
            $scope.deferred.resolve(true);
            return '';
          } else {
            return editor.scope.html;
          }
        }, function() {
          var content = editor.scope.html;

          //check if text is too long
          var tmp = document.createElement('DIV');
          tmp.innerHTML = content;
          var contentLength = (tmp.textContent || tmp.innerText || '').length;
          if(contentLength > maxLength) {
            //strip HTML content
            editor.scope.html = stripContent(content);
          }
          updateRemainingChars();
        });
      }
    };
  });<|endoftext|>