<commit_before>const winston = require('../logger');
const artistsCache = require('../lib/artistsCache');
const { durationToHHMMSS, getRandomLatestRecordingString, sortTapes } = require('../lib/utils');

const API_ROOT = 'https://api.relisten.net/api/v2';

const IS_PRODUCTION = process.env.NODE_ENV === 'production';
const SONOS_ROOT = IS_PRODUCTION ? 'https://sonos.relisten.net' : 'http://192.168.0.101:3000';

const getRoot = (callback) => {
  fetch(`${API_ROOT}/artists`)
    .then(res => res.json())
    .then(json => {
      const artists = json.map(artist => {
        artistsCache[artist.slug] = artist;
        return {
          id: `Artist:${artist.slug}`,
          itemType: 'artist',
          displayType: 'list-sans-thumbs',
          title: artist.name,
          summary: artist.name,
          canPlay: false,
          // albumArtURI: ''
        };
      }).filter(x => x);

      const results = [
        {
          id: 'latest',
          itemType: 'container',
          displayType: 'list-sans-thumbs',
          title: getRandomLatestRecordingString(),
          summary: 'Latest recordings',
          canPlay: false,
          // albumArtURI: ''
        },
        ...artists,
      ];

      callback({
        getMetadataResult: {
          index: 0,
          count: results.length,
          total: results.length,
          mediaCollection: results,
        },
      });
    })
    .catch(err => {
      winston.error(err);
      return callback({});
    });
};

const getLatest = (id, callback) => {
  fetch(`${API_ROOT}/shows/recently-added`)
    .then(res => res.json())
    .then(json => {
      const results = json.map(item => {
        return {
          id: `Shows:${item.artist.slug}:${item.year.year}:${item.display_date}`,
          itemType: 'container',
          displayType: 'list-sans-thumbs',
          title: [
            item.artist && item.artist.name,
            item.display_date,
            item.venue && item.venue.name,
            item.venue && item.venue.location,
          ].filter(x => x).join(' '),
          summary: [
            item.artist && item.artist.name,
            item.display_date,
            item.venue && item.venue.name,
            item.venue && item.venue.location,
          ].filter(x => x).join(' '),
          canPlay: false,
          // albumArtURI: ''
        };
      });

      callback({
        getMetadataResult: {
          index: 0,
          count: results.length,
          total: results.length,
          mediaCollection: results,
        },
      });
    })
    .catch(err => {
      winston.error(err);
      return callback({});
    });
};

const getYears = (id, callback) => {
  const slug = id.replace('Artist:', '');

  fetch(`${API_ROOT}/artists/${slug}/years`)
    .then(res => res.json())
    .then(json => {
      const years = json.map(item => {
        return {
          id: `Year:${slug}:${item.year}`,
          itemType: 'container',
          displayType: 'list-sans-thumbs',
          title: item.year,
          summary: item.year,
          canPlay: false,
          // albumArtURI: ''
        };
      });

      const results = [
        {
          id: `Year:${slug}:latest`,
          itemType: 'container',
          displayType: 'list-sans-thumbs',
          title: getRandomLatestRecordingString(),
          summary: 'Most recent recordings',
          canPlay: false,
          // albumArtURI: ''
        },
        ...years,
      ];

      callback({
        getMetadataResult: {
          index: 0,
          count: results.length,
          total: results.length,
          mediaCollection: results,
        },
      });
    })
    .catch(err => {
      winston.error(err);
      return callback({});
    });
};

const getShows = (id, callback) => {
  const [regex, slug, year] = id.match(/Year:(.*):(.*)/);

  let url = `${API_ROOT}/artists/${slug}/years/${year}`;

  if (year === 'latest') {
    url = `${API_ROOT}/artists/${slug}/shows/recently-added`;
  }

  fetch(url)
    .then(res => res.json())
    .then(json => {
      if (!json) {
        winston.error('error', { regex });
        return callback({});
      }

      const arr = Array.isArray(json) ? json : json.shows;

      const shows = arr.map(show => {
        return {
          id: `Shows:${slug}:${year}:${show.display_date}`,
          itemType: 'container',
          displayType: 'list',
          title: [
            show.display_date,
            show.venue && show.venue.name,
            show.venue && show.venue.location,
          ].filter(x => x)
            .join(' - ')
           + ' ' +
           [
             `[${show.source_count}]`,
             show.has_soundboard_source && '[SBD]',
           ].filter(x => x).join(' '),
          summary: show.display_date,
          // canPlay: show.source_count === 1,
          albumArtURI: `${SONOS_ROOT}/album-art/${slug}/years/${year}/${show.display_date}/600.png`,
        };
      });

      callback({
        getMetadataResult: {
          index: 0,
          count: shows.length,
          total: shows.length,
          mediaCollection: shows,
        },
      });
    })
    .catch(err => {
      winston.error(err);
      return callback({});
    });
};

const getShow = (type, id, callback) => {
  const [regex, slug, year, date] = id.match(/Shows:(.*):(.*):(.*)/);

  fetch(`${API_ROOT}/artists/${slug}/years/${year}/${date}`)
    .then(res => res.json())
    .then(json => {
      if (!json || !json.sources) {
        winston.error('error', { regex });
        return callback({});
      }

      // if (json.sources.length === 1) return getTracks(type, `Show:${slug}:${year}:${date}:${json.sources[0].id}`, callback);

      const sources = sortTapes(json.sources).sources.filter(source => type === 'flac' ? source.flac_type !== 'Flac24Bit' : true).map(source => {
        const person = source.taper || source.transferrer;

        return {
          id: `Show:${slug}:${year}:${date}:${source.id}`,
          itemType: 'album',
          displayType: 'list',
          title: [
            source.is_soundboard ? '[SBD]' : '[AUD]',
            person ? `by ${person}` : null,
            type === 'flac' && source.flac_type === 'Flac16Bit' && json.has_streamable_flac_source && '[FLAC]',
          ].filter(x => x).join(' '),
          summary: source.description || '',
          canPlay: true,
          albumArtURI: `${SONOS_ROOT}/album-art/${slug}/years/${year}/${date}/${json.sources[0].id}/600.png`,
        };
      });

      callback({
        getMetadataResult: {
          index: 0,
          count: sources.length,
          total: sources.length,
          mediaCollection: sources,
        },
      });
    })
    .catch(err => {
      winston.error(err);
      return callback({});
    });
};

const getTracks = (type, id, callback) => {
  const [, slug, year, date, sourceId] = id.match(/Show:(.*):(.*):(.*):(.*)/);

  const artist = artistsCache[slug];
  const artistName = artist ? artist.name : '';

  fetch(`${API_ROOT}/artists/${slug}/years/${year}/${date}`)
    .then(res => res.json())
    .then(json => {
      if (!json || !json.sources) {
        winston.error('no json tracks found', { slug, year, date, sourceId });
        return callback({});
      }

      const source = json.sources.find(source => `${source.id}` === sourceId);

      if (!source || !source.sets) {
        winston.error('no source found', { slug, year, date, sourceId });
        return callback({});
      }

      let tracks = [];
      let trackIdx = 0;

      source.sets.map(set => {
        tracks = tracks.concat(
          set.tracks.map(track => {
            const [year, month, day] = date.split('-');

            return {
              id: `Track:${slug}:${year}:${date}:${source.id}:${track.id}`,
              itemType: 'track',
              mimeType: type === 'flac' && track.flac_url ? 'audio/flac' : 'audio/mp3',
              title: `${track.title} [${durationToHHMMSS(track.duration)}]`,
              trackMetadata: {
                albumId: id,
                duration: track.duration,
                artistId: `Artist:${slug}`,
                artist: artistName,
                albumArtURI: `${SONOS_ROOT}/album-art/${slug}/years/${year}/${date}/${sourceId}/600.png`,
                trackNumber: ++trackIdx,
                album: [
                  `${Number(month)}/${Number(day)}/${year.slice(2)}`,
                  json.venue ? json.venue.name : '',
                  json.venue ? json.venue.location : '',
                ].filter(x => x).join(' - '),
              },
            };
          })
        );
      });

      callback({
        getMetadataResult: {
          index: 0,
          count: tracks.length,
          total: tracks.length,
          mediaMetadata: tracks,
        },
      });
    })
    .catch(err => {
      winston.error(err);
      return callback({});
    });
};

module.exports = (type) => (args, callback) => {
  const id = args.id;

  winston.info('getMetadata', { id, args });

  if (id === 'root') {
    winston.I.increment('sonos.wsdl.getMetadata.root');
    return getRoot(callback);
  }
  else if (id === 'latest') {
    winston.I.increment('sonos.wsdl.getMetadata.Latest');
    return getLatest(id, callback);
  }
  else if (/Artist:/.test(id)) {
    winston.I.increment('sonos.wsdl.getMetadata.Artist');
    return getYears(id, callback);
  }
  else if (/Year:/.test(id)) {
    winston.I.increment('sonos.wsdl.getMetadata.Year');
    return getShows(id, callback);
  }
  else if (/Shows:/.test(id)) {
    winston.I.increment('sonos.wsdl.getMetadata.Shows');
    return getShow(type, id, callback);
  }
  else if (/Show:/.test(id)) {
    winston.I.increment('sonos.wsdl.getMetadata.Show');
    return getTracks(type, id, callback);
  }
};
<commit_msg>Re-add source which I somehow removed (the most important part)<commit_after>const winston = require('../logger');
const artistsCache = require('../lib/artistsCache');
const { durationToHHMMSS, getRandomLatestRecordingString, sortTapes } = require('../lib/utils');

const API_ROOT = 'https://api.relisten.net/api/v2';

const IS_PRODUCTION = process.env.NODE_ENV === 'production';
const SONOS_ROOT = IS_PRODUCTION ? 'https://sonos.relisten.net' : 'http://192.168.0.101:3000';

const getRoot = (callback) => {
  fetch(`${API_ROOT}/artists`)
    .then(res => res.json())
    .then(json => {
      const artists = json.map(artist => {
        artistsCache[artist.slug] = artist;
        return {
          id: `Artist:${artist.slug}`,
          itemType: 'artist',
          displayType: 'list-sans-thumbs',
          title: artist.name,
          summary: artist.name,
          canPlay: false,
          // albumArtURI: ''
        };
      }).filter(x => x);

      const results = [
        {
          id: 'latest',
          itemType: 'container',
          displayType: 'list-sans-thumbs',
          title: getRandomLatestRecordingString(),
          summary: 'Latest recordings',
          canPlay: false,
          // albumArtURI: ''
        },
        ...artists,
      ];

      callback({
        getMetadataResult: {
          index: 0,
          count: results.length,
          total: results.length,
          mediaCollection: results,
        },
      });
    })
    .catch(err => {
      winston.error(err);
      return callback({});
    });
};

const getLatest = (id, callback) => {
  fetch(`${API_ROOT}/shows/recently-added`)
    .then(res => res.json())
    .then(json => {
      const results = json.map(item => {
        return {
          id: `Shows:${item.artist.slug}:${item.year.year}:${item.display_date}`,
          itemType: 'container',
          displayType: 'list-sans-thumbs',
          title: [
            item.artist && item.artist.name,
            item.display_date,
            item.venue && item.venue.name,
            item.venue && item.venue.location,
          ].filter(x => x).join(' '),
          summary: [
            item.artist && item.artist.name,
            item.display_date,
            item.venue && item.venue.name,
            item.venue && item.venue.location,
          ].filter(x => x).join(' '),
          canPlay: false,
          // albumArtURI: ''
        };
      });

      callback({
        getMetadataResult: {
          index: 0,
          count: results.length,
          total: results.length,
          mediaCollection: results,
        },
      });
    })
    .catch(err => {
      winston.error(err);
      return callback({});
    });
};

const getYears = (id, callback) => {
  const slug = id.replace('Artist:', '');

  fetch(`${API_ROOT}/artists/${slug}/years`)
    .then(res => res.json())
    .then(json => {
      const years = json.map(item => {
        return {
          id: `Year:${slug}:${item.year}`,
          itemType: 'container',
          displayType: 'list-sans-thumbs',
          title: item.year,
          summary: item.year,
          canPlay: false,
          // albumArtURI: ''
        };
      });

      const results = [
        {
          id: `Year:${slug}:latest`,
          itemType: 'container',
          displayType: 'list-sans-thumbs',
          title: getRandomLatestRecordingString(),
          summary: 'Most recent recordings',
          canPlay: false,
          // albumArtURI: ''
        },
        ...years,
      ];

      callback({
        getMetadataResult: {
          index: 0,
          count: results.length,
          total: results.length,
          mediaCollection: results,
        },
      });
    })
    .catch(err => {
      winston.error(err);
      return callback({});
    });
};

const getShows = (id, callback) => {
  const [regex, slug, year] = id.match(/Year:(.*):(.*)/);

  let url = `${API_ROOT}/artists/${slug}/years/${year}`;

  if (year === 'latest') {
    url = `${API_ROOT}/artists/${slug}/shows/recently-added`;
  }

  fetch(url)
    .then(res => res.json())
    .then(json => {
      if (!json) {
        winston.error('error', { regex });
        return callback({});
      }

      const arr = Array.isArray(json) ? json : json.shows;

      const shows = arr.map(show => {
        return {
          id: `Shows:${slug}:${year}:${show.display_date}`,
          itemType: 'container',
          displayType: 'list',
          title: [
            show.display_date,
            show.venue && show.venue.name,
            show.venue && show.venue.location,
          ].filter(x => x)
            .join(' - ')
           + ' ' +
           [
             `[${show.source_count}]`,
             show.has_soundboard_source && '[SBD]',
           ].filter(x => x).join(' '),
          summary: show.display_date,
          // canPlay: show.source_count === 1,
          albumArtURI: `${SONOS_ROOT}/album-art/${slug}/years/${year}/${show.display_date}/600.png`,
        };
      });

      callback({
        getMetadataResult: {
          index: 0,
          count: shows.length,
          total: shows.length,
          mediaCollection: shows,
        },
      });
    })
    .catch(err => {
      winston.error(err);
      return callback({});
    });
};

const getShow = (type, id, callback) => {
  const [regex, slug, year, date] = id.match(/Shows:(.*):(.*):(.*)/);

  fetch(`${API_ROOT}/artists/${slug}/years/${year}/${date}`)
    .then(res => res.json())
    .then(json => {
      if (!json || !json.sources) {
        winston.error('error', { regex });
        return callback({});
      }

      // if (json.sources.length === 1) return getTracks(type, `Show:${slug}:${year}:${date}:${json.sources[0].id}`, callback);

      const sources = sortTapes(json.sources).sources.filter(source => type === 'flac' ? source.flac_type !== 'Flac24Bit' : true).map(source => {
        const person = source.taper || source.transferrer;

        return {
          id: `Show:${slug}:${year}:${date}:${source.id}`,
          itemType: 'album',
          displayType: 'list',
          title: [
            source.is_soundboard ? '[SBD]' : '[AUD]',
            source.source || source.lineage,
            person ? `by ${person}` : null,
            type === 'flac' && source.flac_type === 'Flac16Bit' && json.has_streamable_flac_source && '[FLAC]',
          ].filter(x => x).join(' '),
          summary: source.description || '',
          canPlay: true,
          albumArtURI: `${SONOS_ROOT}/album-art/${slug}/years/${year}/${date}/${json.sources[0].id}/600.png`,
        };
      });

      callback({
        getMetadataResult: {
          index: 0,
          count: sources.length,
          total: sources.length,
          mediaCollection: sources,
        },
      });
    })
    .catch(err => {
      winston.error(err);
      return callback({});
    });
};

const getTracks = (type, id, callback) => {
  const [, slug, year, date, sourceId] = id.match(/Show:(.*):(.*):(.*):(.*)/);

  const artist = artistsCache[slug];
  const artistName = artist ? artist.name : '';

  fetch(`${API_ROOT}/artists/${slug}/years/${year}/${date}`)
    .then(res => res.json())
    .then(json => {
      if (!json || !json.sources) {
        winston.error('no json tracks found', { slug, year, date, sourceId });
        return callback({});
      }

      const source = json.sources.find(source => `${source.id}` === sourceId);

      if (!source || !source.sets) {
        winston.error('no source found', { slug, year, date, sourceId });
        return callback({});
      }

      let tracks = [];
      let trackIdx = 0;

      source.sets.map(set => {
        tracks = tracks.concat(
          set.tracks.map(track => {
            const [year, month, day] = date.split('-');

            return {
              id: `Track:${slug}:${year}:${date}:${source.id}:${track.id}`,
              itemType: 'track',
              mimeType: type === 'flac' && track.flac_url ? 'audio/flac' : 'audio/mp3',
              title: `${track.title} [${durationToHHMMSS(track.duration)}]`,
              trackMetadata: {
                albumId: id,
                duration: track.duration,
                artistId: `Artist:${slug}`,
                artist: artistName,
                albumArtURI: `${SONOS_ROOT}/album-art/${slug}/years/${year}/${date}/${sourceId}/600.png`,
                trackNumber: ++trackIdx,
                album: [
                  `${Number(month)}/${Number(day)}/${year.slice(2)}`,
                  json.venue ? json.venue.name : '',
                  json.venue ? json.venue.location : '',
                ].filter(x => x).join(' - '),
              },
            };
          })
        );
      });

      callback({
        getMetadataResult: {
          index: 0,
          count: tracks.length,
          total: tracks.length,
          mediaMetadata: tracks,
        },
      });
    })
    .catch(err => {
      winston.error(err);
      return callback({});
    });
};

module.exports = (type) => (args, callback) => {
  const id = args.id;

  winston.info('getMetadata', { id, args });

  if (id === 'root') {
    winston.I.increment('sonos.wsdl.getMetadata.root');
    return getRoot(callback);
  }
  else if (id === 'latest') {
    winston.I.increment('sonos.wsdl.getMetadata.Latest');
    return getLatest(id, callback);
  }
  else if (/Artist:/.test(id)) {
    winston.I.increment('sonos.wsdl.getMetadata.Artist');
    return getYears(id, callback);
  }
  else if (/Year:/.test(id)) {
    winston.I.increment('sonos.wsdl.getMetadata.Year');
    return getShows(id, callback);
  }
  else if (/Shows:/.test(id)) {
    winston.I.increment('sonos.wsdl.getMetadata.Shows');
    return getShow(type, id, callback);
  }
  else if (/Show:/.test(id)) {
    winston.I.increment('sonos.wsdl.getMetadata.Show');
    return getTracks(type, id, callback);
  }
};
<|endoftext|>


<commit_before>var _ = require('lodash');

/**
 * @dgService getTypeLink
 * @description Get link to type
 */
module.exports = function getTypeLink(aliasMap, log) {
    var arrayReg = /^Array\.<([^>]+)>/i;
    var nativeTypes = [
        'arguments', 'Array', 'ArrayBuffer', 'Boolean', 'DataView', 'Date', 'Error', 'EvalError', 'Float32Array',
        'Float64Array', 'Function', 'Generator', 'GeneratorFunction', 'Infinity', 'Int16Array', 'Int32Array',
        'Int8Array', 'InternalError', 'Intl', 'Intl.Collator', 'Intl.DateTimeFormat', 'Intl.NumberFormat', 'Iterator',
        'JSON', 'Map', 'Math', 'NaN', 'null', 'Number', 'Object', 'ParallelArray', 'Promise', 'Proxy', 'RangeError',
        'ReferenceError', 'Reflect', 'RegExp', 'SIMD', 'SIMD.Float32x4', 'SIMD.Float64x2', 'SIMD.Int16x8',
        'SIMD.Int32x4', 'SIMD.Int8x16', 'Set', 'StopIteration', 'String', 'Symbol', 'SyntaxError', 'TypeError',
        'TypedArray', 'URIError', 'Uint16Array', 'Uint32Array', 'Uint8Array', 'Uint8ClampedArray', 'WeakMap',
        'WeakSet', 'undefined'
    ];
    var nativeTypeRootLink = 'http://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/';

    function TypeLink (typeStr) {
        var res = '';
        if (nativeTypeRootLink) {
            // check for array types and strip them to get actual type
            if (arrayReg.test(typeStr)) {
                typeStr = typeStr.match(arrayReg)[1];
            }

            var doc = aliasMap.getDocs(typeStr);

            if (doc.length === 1) {
                doc = doc[0];
                log.debug('getTypeLink: Generating link for "%s" - "%s"', typeStr, doc.path);
                res = doc.path;
            } else if (doc.length === 0) {
                // try to match native object
                if (nativeTypes.indexOf(typeStr) > -1) {
                    res = nativeTypeRootLink + typeStr;
                } else {
                    log.warn('getTypeLink: Missing type "%s"', typeStr);
                }
            } else {
                log.warn('getTypeLink: Ambiguous type name "%s"\nMatching docs: %s', typeStr, _.reduce(doc,
                    function(msg, doc) {
                        return msg + '\n  "' + doc.id + '"';
                    }, "").toString());
            }
        }
        return res;
    };

    /**
     * @name nativeTypeRoot
     * @propertyOf getTypeLink
     * @type {String|null}
     * @description Sets/retrieves url root for native types, by default points to MDN
     *
     * Set to Boolean(false) prevents generation of native links
     */
    Object.defineProperties(TypeLink, {
        'nativeTypeRoot': {
            get: function () {
                return nativeTypeRootLink;
            },
            set: function (v) {
                nativeTypeRootLink = v;
            }
        },
        'nativeTypes': {
            value: nativeTypes
        }
    });

    return TypeLink;
};<commit_msg>Added Array<Type> as variant of Array.<Type><commit_after>var _ = require('lodash');

/**
 * @dgService getTypeLink
 * @description Get link to type
 */
module.exports = function getTypeLink(aliasMap, log) {
    var arrayReg = /^Array\.?<([^>]+)>/i;
    var nativeTypes = [
        'arguments', 'Array', 'ArrayBuffer', 'Boolean', 'DataView', 'Date', 'Error', 'EvalError', 'Float32Array',
        'Float64Array', 'Function', 'Generator', 'GeneratorFunction', 'Infinity', 'Int16Array', 'Int32Array',
        'Int8Array', 'InternalError', 'Intl', 'Intl.Collator', 'Intl.DateTimeFormat', 'Intl.NumberFormat', 'Iterator',
        'JSON', 'Map', 'Math', 'NaN', 'null', 'Number', 'Object', 'ParallelArray', 'Promise', 'Proxy', 'RangeError',
        'ReferenceError', 'Reflect', 'RegExp', 'SIMD', 'SIMD.Float32x4', 'SIMD.Float64x2', 'SIMD.Int16x8',
        'SIMD.Int32x4', 'SIMD.Int8x16', 'Set', 'StopIteration', 'String', 'Symbol', 'SyntaxError', 'TypeError',
        'TypedArray', 'URIError', 'Uint16Array', 'Uint32Array', 'Uint8Array', 'Uint8ClampedArray', 'WeakMap',
        'WeakSet', 'undefined'
    ];
    var nativeTypeRootLink = 'http://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/';

    function TypeLink (typeStr) {
        var res = '';
        if (nativeTypeRootLink) {
            // check for array types and strip them to get actual type
            if (arrayReg.test(typeStr)) {
                typeStr = typeStr.match(arrayReg)[1];
            }

            var doc = aliasMap.getDocs(typeStr);
console.log(typeStr, doc);
            if (doc.length === 1) {
                doc = doc[0];
                log.debug('getTypeLink: Generating link for "%s" - "%s"', typeStr, doc.path);
                res = doc.path;
            } else if (doc.length === 0) {
                // try to match native object
                if (nativeTypes.indexOf(typeStr) > -1) {
                    res = nativeTypeRootLink + typeStr;
                } else {
                    log.warn('getTypeLink: Missing type "%s"', typeStr);
                }
            } else {
                log.warn('getTypeLink: Ambiguous type name "%s"\nMatching docs: %s', typeStr, _.reduce(doc,
                    function(msg, doc) {
                        return msg + '\n  "' + doc.id + '"';
                    }, "").toString());
            }
        }
        return res;
    };

    /**
     * @name nativeTypeRoot
     * @propertyOf getTypeLink
     * @type {String|null}
     * @description Sets/retrieves url root for native types, by default points to MDN
     *
     * Set to Boolean(false) prevents generation of native links
     */
    Object.defineProperties(TypeLink, {
        'nativeTypeRoot': {
            get: function () {
                return nativeTypeRootLink;
            },
            set: function (v) {
                nativeTypeRootLink = v;
            }
        },
        'nativeTypes': {
            value: nativeTypes
        }
    });

    return TypeLink;
};<|endoftext|>


<commit_before>goog.provide('ngeo.LayerHelper');

goog.require('ngeo');
goog.require('ol.Collection');
goog.require('ol.format.WMTSCapabilities');
goog.require('ol.layer.Group');
goog.require('ol.layer.Image');
goog.require('ol.layer.Tile');
goog.require('ol.source.ImageWMS');
goog.require('ol.source.WMTS');

/**
 * Provides help functions that helps you to create and manage layers.
 * @param {angular.$q} $q Angular promises/deferred service.
 * @param {angular.$http} $http Angular http service.
 * @constructor
 * @ngdoc service
 * @ngname ngeoLayerHelper
 * @ngInject
 */
ngeo.LayerHelper = function($q, $http) {

  /**
   * @type {angular.$q}
   * @private
   */
  this.$q_ = $q;

  /**
   * @type {angular.$http}
   * @private
   */
  this.$http_ = $http;
};

/**
 * @const {string}
 * @export
 */
ngeo.LayerHelper.prototype.helperID = 'helperID';

/**
 * Add a HelperID to the given layer. Layers with this ID can be
 * managed by this sevice.
 * @param {ol.layer.Layer} layer The layer that needs an ID.
 * @param {string} layerURL Part of the ID.
 * @param {string} layerName Part of the ID.
 * @export
 */
ngeo.LayerHelper.prototype.setHelperID = function(layer, layerURL, layerName) {
  layer.set(this.helperID, this.makeHelperID(layerURL, layerName));
};

/**
 * Return an ID based on two strings ('layerURL_layerName');
 * @param {string} layerURL Part of the ID.
 * @param {string} layerName Part of the ID.
 * @return {string}
 * @export
 */
ngeo.LayerHelper.prototype.makeHelperID = function(layerURL, layerName) {
  return layerURL + '_' + layerName;
};

/**
 * Create and return a basic WMS layer with only a source URL and a dot
 * separated layers names (see {@link ol.source.ImageWMS}).
 * This layer will be tagged by a a helperID.
 * @param {string} sourceURL The source URL.
 * @param {string} sourceLayersName A dot separated names string.
 * @return {ol.layer.Image}
 * @export
 */
ngeo.LayerHelper.prototype.createBasicWMSLayer = function(sourceURL,
    sourceLayersName) {
  var layer = new ol.layer.Image({
    source: new ol.source.ImageWMS({
      url: sourceURL,
      params: {'LAYERS': sourceLayersName}
    })
  });
  this.setHelperID(layer, sourceURL, sourceLayersName);
  return layer;
};

/**
 * Create and return a promise that provides a WMTS layer with source on
 * success, no layer else.
 * The WMTS layer source will be configured by the capabilities that are
 * loaded from the given capabilitiesUrl.
 * The style object described in the capabilities for this layer will be added
 * as key 'capabilitiesStyles' as param of the new layer.
 * This layer will be tagged by a helperID.
 * @param {string} capabilitiesURL The getCapabilities url.
 * @param {string} layerName The name of the layer.
 * @return {angular.$q.Promise} A Promise with a layer (with source) on success,
 *     no layer else.
 * @export
 */
ngeo.LayerHelper.prototype.createWMTSLayerFromCapabilitites = function(
    capabilitiesURL, layerName) {
  var parser = new ol.format.WMTSCapabilities();
  var layer = new ol.layer.Tile();
  this.setHelperID(layer, capabilitiesURL, layerName);
  var $q = this.$q_;

  return this.$http_.get(capabilitiesURL).then(function(response) {
    var result;
    if (response.data) {
      result = parser.read(response.data);
    }
    if (goog.isDef(result)) {
      var options = ol.source.WMTS.optionsFromCapabilities(result,
          {layer: layerName, requestEncoding: 'REST'});
      layer.setSource(new ol.source.WMTS(options));

      // Add styles from capabilities as param of the layer
      var layers = result['Contents']['Layer'];
      var l = goog.array.find(layers, function(elt, index, array) {
        return elt['Identifier'] == layerName;
      });
      layer.set('capabilitiesStyles', l['Style']);

      return $q.resolve(layer);
    }
    return $q.reject();
  });
};

/**
 * Create and return an ol.layer.Group. You can pass a collection of layers to
 * directly add them in the returned group.
 * @param {ol.Collection.<ol.layer.Base>=} opt_layers The layer to add to the
 * returned Group.
 * @return {ol.layer.Group}
 * @export
 */
ngeo.LayerHelper.prototype.createBasicGroup = function(opt_layers) {
  var group = new ol.layer.Group();
  if (goog.isDefAndNotNull(opt_layers)) {
    group.setLayers(opt_layers);
  }
  return group;
};

/**
 * Get the position of the layer in the map's layers array or -1 if the layer
 * can't be found.
 * The layer must be tagged by a helperID (return -1 else).
 * @param {ol.Map} map The concerned map.
 * @param {ol.layer.Layer} layer The concerned layer.
 * @return {number} index or -1 if not found.
 * @export
 */
ngeo.LayerHelper.prototype.getLayerIndex = function(map, layer) {
  var layerId = layer.get(this.helperID);
  if (!goog.isDef(layerId)) {
    return -1;
  }

  var i, layers = /** @type {Array.<ol.layer.Layer>} */
      (map.getLayers().getArray());
  for (i = 0; i < layers.length; i++) {
    if (layers[i].get(this.helperID) === layerId) {
      return i;
    }
  }
  return -1;
};

/**
 * Retrieve a layer from the given array of layers and based on the given
 * layers's helperID. Return null if no layer match.
 * @param {Array.<ol.layer.Layer>} layers An array of layers.
 * @param {string} layerID an ID like one created by the setHelperID methode
 *   in this service
 * @return {ol.layer.Layer?} layer or null;
 * @export
 */
ngeo.LayerHelper.prototype.findLayer = function(layers, layerID) {
  var i, layer;
  for (i = 0; i < layers.length; i++) {
    layer = layers[i];
    if (layer.get(this.helperID) === layerID) {
      return layer;
    }
  }
  return null;
};

/**
 * Add the given layer on the map if it doesn't already exists and if the layer
 * has a source.
 * The layer must be tagged by a helperID.
 * @param {ol.Map} map The map where add the layer.
 * @param {ol.layer.Layer} layer The concerned layer.
 * @return {boolean} true if added, false else.
 * @export
 */
ngeo.LayerHelper.prototype.addLayerToMap = function(map, layer) {
  var added = false;
  if (layer.getSource()) {
    var layerIndex = this.getLayerIndex(map, layer);
    if (layerIndex < 0) {
      map.addLayer(layer);
      added = true;
    }
  }
  return added;
};

/**
 * Remove the given layer from the map if it exists.
 * The layer must be tagged by a helperID.
 * @param {ol.Map} map The map on which to remove the layer.
 * @param {ol.layer.Layer} layer The concerned layer.
 * @return {boolean} true if removed, false else.
 * @export
 */
ngeo.LayerHelper.prototype.removeLayerFromMap = function(map, layer) {
  var removed = false;
  var layerToRemove;
  var layerIndex = this.getLayerIndex(map, layer);
  if (layerIndex >= 0) {
    layerToRemove = map.getLayers().getArray()[layerIndex];
    map.removeLayer(layerToRemove);
    removed = true;
  }
  return removed;
};

/**
 * Add or remove some layers from the map.
 * The layer must be tagged by a helperID.
 * @param {ol.Map} map The concerned map.
 * @param {Array.<ol.layer.Layer>} layers An array of layers.
 * @param {boolean} add True to add the layers, False to remove them.
 * @export
 */
ngeo.LayerHelper.prototype.moveInOutLayers = function(map, layers, add) {
  var i, layer;
  for (i = 0; i < layers.length; i++) {
    layer = layers[i];
    if (add) {
      this.addLayerToMap(map, layer);
    } else {
      this.removeLayerFromMap(map, layer);
    }
  }
};

/**
 * Get an array of all layers in a group. The group can contain multiple levels
 * of others groups.
 * @param {ol.layer.Base} layer The base layer, mostly a group of layers.
 * @return {Array.<ol.layer.Layer>}
 * @export
 */
ngeo.LayerHelper.prototype.getFlatLayers = function(layer) {
  return this.getFlatLayers_(layer, []);
};

/**
 * Get an array of all layers in a group. The group can contain multiple levels
 * of others groups.
 * @param {ol.layer.Base} layer The base layer, mostly a group of layers.
 * @param {Array.<ol.layer.Base>} array An array to add layers.
 * @return {Array.<ol.layer.Layer>}
 * @private
 */
ngeo.LayerHelper.prototype.getFlatLayers_ = function(layer, array) {
  if (layer instanceof ol.layer.Group) {
    var sublayers = layer.getLayers();
    sublayers.forEach(function(l) {
      this.getFlatLayers_(l, array);
    }, this);
  } else {
    if (array.indexOf(layer) < 0) {
      array.push(layer);
    }
  }
  return array;
};

ngeoModule.service('ngeoLayerHelper', ngeo.LayerHelper);
<commit_msg>Add error message on failure<commit_after>goog.provide('ngeo.LayerHelper');

goog.require('ngeo');
goog.require('ol.Collection');
goog.require('ol.format.WMTSCapabilities');
goog.require('ol.layer.Group');
goog.require('ol.layer.Image');
goog.require('ol.layer.Tile');
goog.require('ol.source.ImageWMS');
goog.require('ol.source.WMTS');

/**
 * Provides help functions that helps you to create and manage layers.
 * @param {angular.$q} $q Angular promises/deferred service.
 * @param {angular.$http} $http Angular http service.
 * @constructor
 * @ngdoc service
 * @ngname ngeoLayerHelper
 * @ngInject
 */
ngeo.LayerHelper = function($q, $http) {

  /**
   * @type {angular.$q}
   * @private
   */
  this.$q_ = $q;

  /**
   * @type {angular.$http}
   * @private
   */
  this.$http_ = $http;
};

/**
 * @const {string}
 * @export
 */
ngeo.LayerHelper.prototype.helperID = 'helperID';

/**
 * Add a HelperID to the given layer. Layers with this ID can be
 * managed by this sevice.
 * @param {ol.layer.Layer} layer The layer that needs an ID.
 * @param {string} layerURL Part of the ID.
 * @param {string} layerName Part of the ID.
 * @export
 */
ngeo.LayerHelper.prototype.setHelperID = function(layer, layerURL, layerName) {
  layer.set(this.helperID, this.makeHelperID(layerURL, layerName));
};

/**
 * Return an ID based on two strings ('layerURL_layerName');
 * @param {string} layerURL Part of the ID.
 * @param {string} layerName Part of the ID.
 * @return {string}
 * @export
 */
ngeo.LayerHelper.prototype.makeHelperID = function(layerURL, layerName) {
  return layerURL + '_' + layerName;
};

/**
 * Create and return a basic WMS layer with only a source URL and a dot
 * separated layers names (see {@link ol.source.ImageWMS}).
 * This layer will be tagged by a a helperID.
 * @param {string} sourceURL The source URL.
 * @param {string} sourceLayersName A dot separated names string.
 * @return {ol.layer.Image}
 * @export
 */
ngeo.LayerHelper.prototype.createBasicWMSLayer = function(sourceURL,
    sourceLayersName) {
  var layer = new ol.layer.Image({
    source: new ol.source.ImageWMS({
      url: sourceURL,
      params: {'LAYERS': sourceLayersName}
    })
  });
  this.setHelperID(layer, sourceURL, sourceLayersName);
  return layer;
};

/**
 * Create and return a promise that provides a WMTS layer with source on
 * success, no layer else.
 * The WMTS layer source will be configured by the capabilities that are
 * loaded from the given capabilitiesUrl.
 * The style object described in the capabilities for this layer will be added
 * as key 'capabilitiesStyles' as param of the new layer.
 * This layer will be tagged by a helperID.
 * @param {string} capabilitiesURL The getCapabilities url.
 * @param {string} layerName The name of the layer.
 * @return {angular.$q.Promise} A Promise with a layer (with source) on success,
 *     no layer else.
 * @export
 */
ngeo.LayerHelper.prototype.createWMTSLayerFromCapabilitites = function(
    capabilitiesURL, layerName) {
  var parser = new ol.format.WMTSCapabilities();
  var layer = new ol.layer.Tile();
  this.setHelperID(layer, capabilitiesURL, layerName);
  var $q = this.$q_;

  return this.$http_.get(capabilitiesURL).then(function(response) {
    var result;
    if (response.data) {
      result = parser.read(response.data);
    }
    if (goog.isDef(result)) {
      var options = ol.source.WMTS.optionsFromCapabilities(result,
          {layer: layerName, requestEncoding: 'REST'});
      layer.setSource(new ol.source.WMTS(options));

      // Add styles from capabilities as param of the layer
      var layers = result['Contents']['Layer'];
      var l = goog.array.find(layers, function(elt, index, array) {
        return elt['Identifier'] == layerName;
      });
      layer.set('capabilitiesStyles', l['Style']);

      return $q.resolve(layer);
    }
    return $q.reject('Failed to get WMTS capabilities from ' +
        capabilitiesURL);
  });
};

/**
 * Create and return an ol.layer.Group. You can pass a collection of layers to
 * directly add them in the returned group.
 * @param {ol.Collection.<ol.layer.Base>=} opt_layers The layer to add to the
 * returned Group.
 * @return {ol.layer.Group}
 * @export
 */
ngeo.LayerHelper.prototype.createBasicGroup = function(opt_layers) {
  var group = new ol.layer.Group();
  if (goog.isDefAndNotNull(opt_layers)) {
    group.setLayers(opt_layers);
  }
  return group;
};

/**
 * Get the position of the layer in the map's layers array or -1 if the layer
 * can't be found.
 * The layer must be tagged by a helperID (return -1 else).
 * @param {ol.Map} map The concerned map.
 * @param {ol.layer.Layer} layer The concerned layer.
 * @return {number} index or -1 if not found.
 * @export
 */
ngeo.LayerHelper.prototype.getLayerIndex = function(map, layer) {
  var layerId = layer.get(this.helperID);
  if (!goog.isDef(layerId)) {
    return -1;
  }

  var i, layers = /** @type {Array.<ol.layer.Layer>} */
      (map.getLayers().getArray());
  for (i = 0; i < layers.length; i++) {
    if (layers[i].get(this.helperID) === layerId) {
      return i;
    }
  }
  return -1;
};

/**
 * Retrieve a layer from the given array of layers and based on the given
 * layers's helperID. Return null if no layer match.
 * @param {Array.<ol.layer.Layer>} layers An array of layers.
 * @param {string} layerID an ID like one created by the setHelperID methode
 *   in this service
 * @return {ol.layer.Layer?} layer or null;
 * @export
 */
ngeo.LayerHelper.prototype.findLayer = function(layers, layerID) {
  var i, layer;
  for (i = 0; i < layers.length; i++) {
    layer = layers[i];
    if (layer.get(this.helperID) === layerID) {
      return layer;
    }
  }
  return null;
};

/**
 * Add the given layer on the map if it doesn't already exists and if the layer
 * has a source.
 * The layer must be tagged by a helperID.
 * @param {ol.Map} map The map where add the layer.
 * @param {ol.layer.Layer} layer The concerned layer.
 * @return {boolean} true if added, false else.
 * @export
 */
ngeo.LayerHelper.prototype.addLayerToMap = function(map, layer) {
  var added = false;
  if (layer.getSource()) {
    var layerIndex = this.getLayerIndex(map, layer);
    if (layerIndex < 0) {
      map.addLayer(layer);
      added = true;
    }
  }
  return added;
};

/**
 * Remove the given layer from the map if it exists.
 * The layer must be tagged by a helperID.
 * @param {ol.Map} map The map on which to remove the layer.
 * @param {ol.layer.Layer} layer The concerned layer.
 * @return {boolean} true if removed, false else.
 * @export
 */
ngeo.LayerHelper.prototype.removeLayerFromMap = function(map, layer) {
  var removed = false;
  var layerToRemove;
  var layerIndex = this.getLayerIndex(map, layer);
  if (layerIndex >= 0) {
    layerToRemove = map.getLayers().getArray()[layerIndex];
    map.removeLayer(layerToRemove);
    removed = true;
  }
  return removed;
};

/**
 * Add or remove some layers from the map.
 * The layer must be tagged by a helperID.
 * @param {ol.Map} map The concerned map.
 * @param {Array.<ol.layer.Layer>} layers An array of layers.
 * @param {boolean} add True to add the layers, False to remove them.
 * @export
 */
ngeo.LayerHelper.prototype.moveInOutLayers = function(map, layers, add) {
  var i, layer;
  for (i = 0; i < layers.length; i++) {
    layer = layers[i];
    if (add) {
      this.addLayerToMap(map, layer);
    } else {
      this.removeLayerFromMap(map, layer);
    }
  }
};

/**
 * Get an array of all layers in a group. The group can contain multiple levels
 * of others groups.
 * @param {ol.layer.Base} layer The base layer, mostly a group of layers.
 * @return {Array.<ol.layer.Layer>}
 * @export
 */
ngeo.LayerHelper.prototype.getFlatLayers = function(layer) {
  return this.getFlatLayers_(layer, []);
};

/**
 * Get an array of all layers in a group. The group can contain multiple levels
 * of others groups.
 * @param {ol.layer.Base} layer The base layer, mostly a group of layers.
 * @param {Array.<ol.layer.Base>} array An array to add layers.
 * @return {Array.<ol.layer.Layer>}
 * @private
 */
ngeo.LayerHelper.prototype.getFlatLayers_ = function(layer, array) {
  if (layer instanceof ol.layer.Group) {
    var sublayers = layer.getLayers();
    sublayers.forEach(function(l) {
      this.getFlatLayers_(l, array);
    }, this);
  } else {
    if (array.indexOf(layer) < 0) {
      array.push(layer);
    }
  }
  return array;
};

ngeoModule.service('ngeoLayerHelper', ngeo.LayerHelper);
<|endoftext|>


<commit_before>/* Copyright 2017 Mozilla Foundation
 *
 * 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.
 */
/* globals __non_webpack_require__ */

import { isNodeJS } from "./is_node.js";

// Skip compatibility checks for modern builds and if we already ran the module.
if (
  (typeof PDFJSDev === "undefined" || !PDFJSDev.test("SKIP_BABEL")) &&
  !globalThis._pdfjsCompatibilityChecked
) {
  globalThis._pdfjsCompatibilityChecked = true;

  // Support: Node.js
  (function checkNodeBtoa() {
    if (globalThis.btoa || !isNodeJS) {
      return;
    }
    globalThis.btoa = function (chars) {
      // eslint-disable-next-line no-undef
      return Buffer.from(chars, "binary").toString("base64");
    };
  })();

  // Support: Node.js
  (function checkNodeAtob() {
    if (globalThis.atob || !isNodeJS) {
      return;
    }
    globalThis.atob = function (input) {
      // eslint-disable-next-line no-undef
      return Buffer.from(input, "base64").toString("binary");
    };
  })();

  // Support: Node.js
  (function checkDOMMatrix() {
    if (globalThis.DOMMatrix || !isNodeJS) {
      return;
    }
    globalThis.DOMMatrix = __non_webpack_require__(
      "dommatrix/dist/dommatrix.js"
    );
  })();

  // Provides support for *recent* additions to the Promise specification,
  // however basic Promise support is assumed to be available natively.
  // Support: Firefox<71, Chrome<76, Safari<13, Node.js<12.9.0
  (function checkPromise() {
    if (typeof PDFJSDev !== "undefined" && PDFJSDev.test("IMAGE_DECODERS")) {
      // The current image decoders are synchronous, hence `Promise` shouldn't
      // need to be polyfilled for the IMAGE_DECODERS build target.
      return;
    }
    if (globalThis.Promise.allSettled) {
      return;
    }
    globalThis.Promise = require("core-js/es/promise/index.js");
  })();

  // Support: Node.js
  (function checkReadableStream() {
    if (globalThis.ReadableStream || !isNodeJS) {
      return;
    }
    globalThis.ReadableStream = __non_webpack_require__(
      "web-streams-polyfill/dist/ponyfill.js"
    ).ReadableStream;
  })();

  // Support: Firefox<94, Chrome<98, Safari<15.4, Node.js<17.0.0
  (function checkStructuredClone() {
    if (typeof PDFJSDev !== "undefined" && PDFJSDev.test("IMAGE_DECODERS")) {
      // The current image decoders are synchronous, hence `structuredClone`
      // shouldn't need to be polyfilled for the IMAGE_DECODERS build target.
      return;
    }
    if (globalThis.structuredClone) {
      return;
    }
    require("core-js/web/structured-clone.js");
  })();
}
<commit_msg>Polyfill `Array.prototype.at` with core-js (PR 14976 follow-up)<commit_after>/* Copyright 2017 Mozilla Foundation
 *
 * 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.
 */
/* globals __non_webpack_require__ */

import { isNodeJS } from "./is_node.js";

// Skip compatibility checks for modern builds and if we already ran the module.
if (
  (typeof PDFJSDev === "undefined" || !PDFJSDev.test("SKIP_BABEL")) &&
  !globalThis._pdfjsCompatibilityChecked
) {
  globalThis._pdfjsCompatibilityChecked = true;

  // Support: Node.js
  (function checkNodeBtoa() {
    if (globalThis.btoa || !isNodeJS) {
      return;
    }
    globalThis.btoa = function (chars) {
      // eslint-disable-next-line no-undef
      return Buffer.from(chars, "binary").toString("base64");
    };
  })();

  // Support: Node.js
  (function checkNodeAtob() {
    if (globalThis.atob || !isNodeJS) {
      return;
    }
    globalThis.atob = function (input) {
      // eslint-disable-next-line no-undef
      return Buffer.from(input, "base64").toString("binary");
    };
  })();

  // Support: Node.js
  (function checkDOMMatrix() {
    if (globalThis.DOMMatrix || !isNodeJS) {
      return;
    }
    globalThis.DOMMatrix = __non_webpack_require__(
      "dommatrix/dist/dommatrix.js"
    );
  })();

  // Provides support for *recent* additions to the Promise specification,
  // however basic Promise support is assumed to be available natively.
  // Support: Firefox<71, Chrome<76, Safari<13, Node.js<12.9.0
  (function checkPromise() {
    if (typeof PDFJSDev !== "undefined" && PDFJSDev.test("IMAGE_DECODERS")) {
      // The current image decoders are synchronous, hence `Promise` shouldn't
      // need to be polyfilled for the IMAGE_DECODERS build target.
      return;
    }
    if (globalThis.Promise.allSettled) {
      return;
    }
    globalThis.Promise = require("core-js/es/promise/index.js");
  })();

  // Support: Node.js
  (function checkReadableStream() {
    if (globalThis.ReadableStream || !isNodeJS) {
      return;
    }
    globalThis.ReadableStream = __non_webpack_require__(
      "web-streams-polyfill/dist/ponyfill.js"
    ).ReadableStream;
  })();

  // Support: Firefox<90, Chrome<92, Safari<15.4, Node.js<16.6.0
  (function checkArrayAt() {
    if (Array.prototype.at) {
      return;
    }
    require("core-js/es/array/at.js");
  })();

  // Support: Firefox<94, Chrome<98, Safari<15.4, Node.js<17.0.0
  (function checkStructuredClone() {
    if (typeof PDFJSDev !== "undefined" && PDFJSDev.test("IMAGE_DECODERS")) {
      // The current image decoders are synchronous, hence `structuredClone`
      // shouldn't need to be polyfilled for the IMAGE_DECODERS build target.
      return;
    }
    if (globalThis.structuredClone) {
      return;
    }
    require("core-js/web/structured-clone.js");
  })();
}
<|endoftext|>


<commit_before>import React from 'react';
import ConstellationsComponent from '../components/constellations';

export default class Constellations {

  static componentWithData(constellations) {
    return <ConstellationsComponent constellations={constellations} />;
  }

  static fromRawData(rawData) {
    return rawData.map(raw => Constellation.fromRawData(raw))
  }

}

class Constellation {

  static fromRawData(raw) {
    const item = new Constellation();
    item.name = raw.itemname;
    item.latinName = raw.itemname2;
    item.shortName = raw.itemname4;
    item.wikipediaUrl = raw.itemurl;
    item.imageUrl = raw.itemimgurl;
    item.imageSrc = raw.itemimgsrc;
    item.author = Author.fromRawData(raw);
    item.brightestStar = Star.fromRawData(raw);
    item.year = raw.itemdateyear;
    item.sphere = raw.itemproperty;
    item.visibleFrom = raw.itemproperty2; // TODO better name please!!!
    item.visibleTo = raw.itemproperty3; // TODO better name please!!!
    item.squareDegrees = raw.itemproperty4; // TODO better name please!!!
    item.starsOver3Mag = raw['itemproperty5'];
    item.highestBrightness = raw.itemproperty6;
    return item;
  }

}

class Author {

  static fromRawData(raw) {
    const author = new Author();
    author.name = raw.itemparent;
    author.wikipediaUrl = raw.itemparenturl;
    return author;
  }

}

class Star {

  static fromRawData(raw) {
    const star = new Star();
    star.name = raw.itemproperty7;
    star.wikipediaUrl = raw.itemproperty8;
    return star;
  }

}

/*
{
    "itemname": "Achterdeck des Schiffs",
    "itemname2": "Puppis",
    "itemname3": "Puppis",
    "itemname4": "Pup",
    "itemurl": "https://de.wikipedia.org/wiki/Puppis_%28Sternbild%29",
    "itemurl2": "http://vizier.u-strasbg.fr/viz-bin/VizieR-4?-source=IV%2F27%2Fcatalog&-out.max=200&-out.all=1&-sort=Vmag&-order=I&Cst=%2APup",
    "itemimgurl": "https://de.wikipedia.org/wiki/Datei:Puppis_constellation_map.png",
    "itemimgsrc": "Torsten Bronger",
    "itemimglicence": "CC by-sa 3.0",
    "itemimglicenceurl": "https://creativecommons.org/licenses/by-sa/3.0/deed.en",
    "itemdateyear": 1763,
    "itemparent": "Lacaille",
    "itemparenturl": "https://de.wikipedia.org/wiki/Nicolas_Louis_de_Lacaille",
    "itemrightascension": "07h 15m 28,8s",
    "itemdeclination": "−31° 10' 38,4\"",
    "itemproperty": "S",
    "itemproperty2": "39° N",
    "itemproperty3": "90° S",
    "itemproperty4": 673.434,
    "itemproperty5": 4,
    "itemproperty6": 2.06,
    "itemproperty7": "Naos",
    "itemproperty8": "https://de.wikipedia.org/wiki/Naos_%28Stern%29"
},
*/
<commit_msg>new item properties according to new json<commit_after>import React from 'react';
import ConstellationsComponent from '../components/constellations';

export default class Constellations {

  static componentWithData(constellations) {
    return <ConstellationsComponent constellations={constellations} />;
  }

  static fromRawData(rawData) {
    return rawData.map(raw => Constellation.fromRawData(raw))
  }

}

class Constellation {

  static fromRawData(raw) {
    const item = new Constellation();
    item.name = raw.itemname;
    item.latinName = raw.itemname2;
    item.shortName = raw.itemname4;
    item.wikipediaUrl = raw.itemurl;
    item.imageSmallUrl = raw.itemurl2;
    item.imageLargeUrl = raw.itemimgurl;
    item.imageSrc = raw.itemimgsrc;
    item.imageLicence = raw.itemimglicence;
    item.imageLicenceUrl = raw.itemimglicenceurl;
    item.named = raw.itemdateyear;
    item.astronomer = raw.itemparent;
    item.rightAscension = raw.itemrightascension;
    item.declination = raw.itemdeclination;
    item.author = Author.fromRawData(raw);
    item.brightestStar = Star.fromRawData(raw);
    item.year = raw.itemdateyear;
    item.visibility = raw.itemproperty;
    item.visibleFrom = raw.itemproperty2;
    item.visibleTo = raw.itemproperty3;
    item.squareDegrees = raw.itemproperty4;
    item.starsOver3Mag = raw['itemproperty5'];
    item.highestBrightness = raw.itemproperty6;
    return item;
  }

}

class Author {

  static fromRawData(raw) {
    const author = new Author();
    author.name = raw.itemparent;
    author.wikipediaUrl = raw.itemparenturl;
    return author;
  }

}

class Star {

  static fromRawData(raw) {
    const star = new Star();
    star.name = raw.itemproperty7;
    star.wikipediaUrl = raw.itemproperty8;
    return star;
  }

}

/*
{
    "itemname": "Achterdeck des Schiffs",
    "itemname2": "Puppis",
    "itemname3": "Puppis",
    "itemname4": "Pup",
    "itemurl": "https://de.wikipedia.org/wiki/Puppis_%28Sternbild%29",
    "itemurl2": "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e2/Puppis_IAU.svg/191px-Puppis_IAU.svg.png",
    "itemimgurl": "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e2/Puppis_IAU.svg/610px-Puppis_IAU.svg.png",
    "itemimgsrc": "IAU and Sky & Telescope magazine (Roger Sinnott & Rick Fienberg)",
    "itemimglicence": "CC by-sa 3.0",
    "itemimglicenceurl": "https://creativecommons.org/licenses/by-sa/3.0/deed.en",
    "itemdateyear": 1763,
    "itemparent": "Lacaille",
    "itemparenturl": "https://de.wikipedia.org/wiki/Nicolas_Louis_de_Lacaille",
    "itemrightascension": "07h 15m 28,8s",
    "itemdeclination": "−31° 10' 38,4\"",
    "itemproperty": "S",
    "itemproperty2": "39° N",
    "itemproperty3": "90° S",
    "itemproperty4": 673.434,
    "itemproperty5": 4,
    "itemproperty6": 2.06,
    "itemproperty7": "Naos",
    "itemproperty8": "https://de.wikipedia.org/wiki/Naos_%28Stern%29"
},
*/
<|endoftext|>


<commit_before>$.register({
  rule: [
    {
      host: /^emptypix\.com|overdream\.cz$/,
      path: /^\/image\//,
    },
    {
      host: /^10\.imageleon\.com$/,
      path: /^\/img-(.+)\.html$/,
    },
    {
      host: /^sexyxpixels\.com$/,
      query: /^\?v=/,
    },
  ],
  ready: function () {
    'use strict';

    var img = $('#full_image');
    $.openImage(img.src);
  },
});

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<commit_msg>sexseeimage.com<commit_after>$.register({
  rule: [
    {
      host: [
        /^emptypix\.com|overdream\.cz$/,
        /^www\.sexseeimage\.com$/,
      ],
      path: /^\/image\//,
    },
    {
      host: /^10\.imageleon\.com$/,
      path: /^\/img-(.+)\.html$/,
    },
    {
      host: /^sexyxpixels\.com$/,
      query: /^\?v=/,
    },
  ],
  ready: function () {
    'use strict';

    var img = $('#full_image');
    $.openImage(img.src);
  },
});

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<|endoftext|>


<commit_before>define(['collections/base', 'models/machine'], function(Base, Machine) {
    return Base.extend({
        model: Machine,
    });
});
<commit_msg>reformat machines collection<commit_after>define(
  [
    'collections/base',
    'models/machine'
  ],
  function (Base, Machine) {

    return Base.extend({
      model: Machine
    });

  });
<|endoftext|>


<commit_before>define(function (require) {

  return {
    create: require('./project/create').create,
    destroy: require('./project/destroy').destroy,
    explainProjectDeleteConditions: require('./project/explainProjectDeleteConditions').explainProjectDeleteConditions
  };

});
<commit_msg>added moveResources to ProjectModals.js<commit_after>define(function (require) {

  return {
    create: require('./project/create').create,
    destroy: require('./project/destroy').destroy,
    explainProjectDeleteConditions: require('./project/explainProjectDeleteConditions').explainProjectDeleteConditions,
    moveResources: require('./project/moveResources').moveResources

  };

});
<|endoftext|>


<commit_before>/* @flow */
import React from 'react';
import { StyleSheet, TouchableOpacity } from 'react-native';
import { Icon } from 'react-native-elements';
import type { Event } from '../../types';
import { colors } from '../../styles';

type Props = {
  active: boolean,
  onPress?: Function,
  size?: number,
  containerStyle?: any
};

const Bookmark = ({ active, onPress, containerStyle, size }: Props) => {
  return (
    <TouchableOpacity
      style={[styles.container, containerStyle]}
      onPress={onPress}
    >
      <Icon
        name={active ? 'bookmark' : 'bookmark-o'}
        type="font-awesome"
        color={active ? colors.highlight : colors.dark}
        size={size}
        underlayColor="transparent"
      />
    </TouchableOpacity>
  );
};

const styles = StyleSheet.create({
  container: {
    paddingHorizontal: 20,
    paddingBottom: 20,
    zIndex: 99
  }
});

export default Bookmark;
<commit_msg>remove unused import<commit_after>/* @flow */
import React from 'react';
import { StyleSheet, TouchableOpacity } from 'react-native';
import { Icon } from 'react-native-elements';
import { colors } from '../../styles';

type Props = {
  active: boolean,
  onPress?: Function,
  size?: number,
  containerStyle?: any
};

const Bookmark = ({ active, onPress, containerStyle, size }: Props) => {
  return (
    <TouchableOpacity
      style={[styles.container, containerStyle]}
      onPress={onPress}
    >
      <Icon
        name={active ? 'bookmark' : 'bookmark-o'}
        type="font-awesome"
        color={active ? colors.highlight : colors.dark}
        size={size}
        underlayColor="transparent"
      />
    </TouchableOpacity>
  );
};

const styles = StyleSheet.create({
  container: {
    paddingHorizontal: 20,
    paddingBottom: 20,
    zIndex: 99
  }
});

export default Bookmark;
<|endoftext|>


<commit_before>import React from 'react';
import AddBusinessForm from './AddBusinessForm';

class Business extends React.Component {
  render() {
    return (

Add a new business

        <AddBusinessForm addBusiness={this.props.addBusiness} />

    );
  }
};

export default Business;
<commit_msg>Fixing linting errors / proptypes<commit_after>import React from 'react';
import AddBusinessForm from './AddBusinessForm';

class Business extends React.Component {
  render() {
    return (

Add a new business

        <AddBusinessForm addBusiness={this.props.addBusiness} />

    );
  }
}

Business.propTypes = {
  addBusiness: React.PropTypes.func.isRequired
};

export default Business;
<|endoftext|>


<commit_before>/**
 * This code is mostly from the old Etherpad. Please help us to comment this code.
 * This helps other people to understand this code better and helps them to improve it.
 * TL;DR COMMENTS ON THIS FILE ARE HIGHLY APPRECIATED
 */

/**
 * Copyright 2009 Google Inc.
 *
 * 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.
 */

const padimpexp = (function () {
  // /// import
  let currentImportTimer = null;

  function addImportFrames() {
    $('#import .importframe').remove();
    const iframe = $('');
    $('#import').append(iframe);
  }

  function fileInputUpdated() {
    $('#importsubmitinput').addClass('throbbold');
    $('#importformfilediv').addClass('importformenabled');
    $('#importsubmitinput').removeAttr('disabled');
    $('#importmessagefail').fadeOut('fast');
  }

  function fileInputSubmit() {
    $('#importmessagefail').fadeOut('fast');
    const ret = window.confirm(html10n.get('pad.impexp.confirmimport'));
    if (ret) {
      currentImportTimer = window.setTimeout(() => {
        if (!currentImportTimer) {
          return;
        }
        currentImportTimer = null;
        importFailed('Request timed out.');
        importDone();
      }, 25000); // time out after some number of seconds
      $('#importsubmitinput').attr(
          {
            disabled: true,
          }).val(html10n.get('pad.impexp.importing'));

      window.setTimeout(() => {
        $('#importfileinput').attr(
            {
              disabled: true,
            });
      }, 0);
      $('#importarrow').stop(true, true).hide();
      $('#importstatusball').show();
    }
    return ret;
  }

  function importFailed(msg) {
    importErrorMessage(msg);
  }

  function importDone() {
    $('#importsubmitinput').removeAttr('disabled').val(html10n.get('pad.impexp.importbutton'));
    window.setTimeout(() => {
      $('#importfileinput').removeAttr('disabled');
    }, 0);
    $('#importstatusball').hide();
    importClearTimeout();
    addImportFrames();
  }

  function importClearTimeout() {
    if (currentImportTimer) {
      window.clearTimeout(currentImportTimer);
      currentImportTimer = null;
    }
  }

  function importErrorMessage(status) {
    let msg = '';

    if (status === 'convertFailed') {
      msg = html10n.get('pad.impexp.convertFailed');
    } else if (status === 'uploadFailed') {
      msg = html10n.get('pad.impexp.uploadFailed');
    } else if (status === 'padHasData') {
      msg = html10n.get('pad.impexp.padHasData');
    } else if (status === 'maxFileSize') {
      msg = html10n.get('pad.impexp.maxFileSize');
    } else if (status === 'permission') {
      msg = html10n.get('pad.impexp.permission');
    }

    function showError(fade) {
      $('#importmessagefail').html(`<strong style="color: red">${html10n.get('pad.impexp.importfailed')}:</strong> ${msg || html10n.get('pad.impexp.copypaste', '')}`)[(fade ? 'fadeIn' : 'show')]();
    }

    if ($('#importexport .importmessage').is(':visible')) {
      $('#importmessagesuccess').fadeOut('fast');
      $('#importmessagefail').fadeOut('fast', () => {
        showError(true);
      });
    } else {
      showError();
    }
  }

  function importSuccessful(token) {
    $.ajax(
        {
          type: 'post',
          url: '/ep/pad/impexp/import2',
          data: {
            token,
            padId: pad.getPadId(),
          },
          success: importApplicationSuccessful,
          error: importApplicationFailed,
          timeout: 25000,
        });
    addImportFrames();
  }

  function importApplicationFailed(xhr, textStatus, errorThrown) {
    importErrorMessage('Error during conversion.');
    importDone();
  }

  // /// export

  function cantExport() {
    let type = $(this);
    if (type.hasClass('exporthrefpdf')) {
      type = 'PDF';
    } else if (type.hasClass('exporthrefdoc')) {
      type = 'Microsoft Word';
    } else if (type.hasClass('exporthrefodt')) {
      type = 'OpenDocument';
    } else {
      type = 'this file';
    }
    alert(html10n.get('pad.impexp.exportdisabled', {type}));
    return false;
  }

  // ///
  var pad = undefined;
  const self = {
    init(_pad) {
      pad = _pad;

      // get /p/padname
      // if /p/ isn't available due to a rewrite we use the clientVars padId
      const pad_root_path = new RegExp(/.*\/p\/[^\/]+/).exec(document.location.pathname) || clientVars.padId;
      // get http://example.com/p/padname without Params
      const pad_root_url = `${document.location.protocol}//${document.location.host}${document.location.pathname}`;

      // i10l buttom import
      $('#importsubmitinput').val(html10n.get('pad.impexp.importbutton'));
      html10n.bind('localized', () => {
        $('#importsubmitinput').val(html10n.get('pad.impexp.importbutton'));
      });

      // build the export links
      $('#exporthtmla').attr('href', `${pad_root_path}/export/html`);
      $('#exportetherpada').attr('href', `${pad_root_path}/export/etherpad`);
      $('#exportplaina').attr('href', `${pad_root_path}/export/txt`);

      // activate action to import in the form
      $('#importform').attr('action', `${pad_root_url}/import`);

      // hide stuff thats not avaible if abiword/soffice is disabled
      if (clientVars.exportAvailable == 'no') {
        $('#exportworda').remove();
        $('#exportpdfa').remove();
        $('#exportopena').remove();

        $('#importmessageabiword').show();
      } else if (clientVars.exportAvailable == 'withoutPDF') {
        $('#exportpdfa').remove();

        $('#exportworda').attr('href', `${pad_root_path}/export/doc`);
        $('#exportopena').attr('href', `${pad_root_path}/export/odt`);

        $('#importexport').css({height: '142px'});
        $('#importexportline').css({height: '142px'});
      } else {
        $('#exportworda').attr('href', `${pad_root_path}/export/doc`);
        $('#exportpdfa').attr('href', `${pad_root_path}/export/pdf`);
        $('#exportopena').attr('href', `${pad_root_path}/export/odt`);
      }

      addImportFrames();
      $('#importfileinput').change(fileInputUpdated);
      $('#importform').unbind('submit').submit(fileInputSubmit);
      $('.disabledexport').click(cantExport);
    },
    handleFrameCall(directDatabaseAccess, status) {
      if (directDatabaseAccess === 'undefined') directDatabaseAccess = false;
      if (status !== 'ok') {
        importFailed(status);
      } else {
        $('#import_export').removeClass('popup-show');
      }

      if (directDatabaseAccess) {
        // Switch to the pad without redrawing the page
        pad.switchToPad(clientVars.padId);
        $('#import_export').removeClass('popup-show');
      }

      importDone();
    },
    disable() {
      $('#impexp-disabled-clickcatcher').show();
      $('#import').css('opacity', 0.5);
      $('#impexp-export').css('opacity', 0.5);
    },
    enable() {
      $('#impexp-disabled-clickcatcher').hide();
      $('#import').css('opacity', 1);
      $('#impexp-export').css('opacity', 1);
    },
  };
  return self;
}());

exports.padimpexp = padimpexp;
<commit_msg>pad import/export: Delete dead functions<commit_after>/**
 * This code is mostly from the old Etherpad. Please help us to comment this code.
 * This helps other people to understand this code better and helps them to improve it.
 * TL;DR COMMENTS ON THIS FILE ARE HIGHLY APPRECIATED
 */

/**
 * Copyright 2009 Google Inc.
 *
 * 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.
 */

const padimpexp = (function () {
  // /// import
  let currentImportTimer = null;

  function addImportFrames() {
    $('#import .importframe').remove();
    const iframe = $('');
    $('#import').append(iframe);
  }

  function fileInputUpdated() {
    $('#importsubmitinput').addClass('throbbold');
    $('#importformfilediv').addClass('importformenabled');
    $('#importsubmitinput').removeAttr('disabled');
    $('#importmessagefail').fadeOut('fast');
  }

  function fileInputSubmit() {
    $('#importmessagefail').fadeOut('fast');
    const ret = window.confirm(html10n.get('pad.impexp.confirmimport'));
    if (ret) {
      currentImportTimer = window.setTimeout(() => {
        if (!currentImportTimer) {
          return;
        }
        currentImportTimer = null;
        importFailed('Request timed out.');
        importDone();
      }, 25000); // time out after some number of seconds
      $('#importsubmitinput').attr(
          {
            disabled: true,
          }).val(html10n.get('pad.impexp.importing'));

      window.setTimeout(() => {
        $('#importfileinput').attr(
            {
              disabled: true,
            });
      }, 0);
      $('#importarrow').stop(true, true).hide();
      $('#importstatusball').show();
    }
    return ret;
  }

  function importFailed(msg) {
    importErrorMessage(msg);
  }

  function importDone() {
    $('#importsubmitinput').removeAttr('disabled').val(html10n.get('pad.impexp.importbutton'));
    window.setTimeout(() => {
      $('#importfileinput').removeAttr('disabled');
    }, 0);
    $('#importstatusball').hide();
    importClearTimeout();
    addImportFrames();
  }

  function importClearTimeout() {
    if (currentImportTimer) {
      window.clearTimeout(currentImportTimer);
      currentImportTimer = null;
    }
  }

  function importErrorMessage(status) {
    let msg = '';

    if (status === 'convertFailed') {
      msg = html10n.get('pad.impexp.convertFailed');
    } else if (status === 'uploadFailed') {
      msg = html10n.get('pad.impexp.uploadFailed');
    } else if (status === 'padHasData') {
      msg = html10n.get('pad.impexp.padHasData');
    } else if (status === 'maxFileSize') {
      msg = html10n.get('pad.impexp.maxFileSize');
    } else if (status === 'permission') {
      msg = html10n.get('pad.impexp.permission');
    }

    function showError(fade) {
      $('#importmessagefail').html(`<strong style="color: red">${html10n.get('pad.impexp.importfailed')}:</strong> ${msg || html10n.get('pad.impexp.copypaste', '')}`)[(fade ? 'fadeIn' : 'show')]();
    }

    if ($('#importexport .importmessage').is(':visible')) {
      $('#importmessagesuccess').fadeOut('fast');
      $('#importmessagefail').fadeOut('fast', () => {
        showError(true);
      });
    } else {
      showError();
    }
  }

  // /// export

  function cantExport() {
    let type = $(this);
    if (type.hasClass('exporthrefpdf')) {
      type = 'PDF';
    } else if (type.hasClass('exporthrefdoc')) {
      type = 'Microsoft Word';
    } else if (type.hasClass('exporthrefodt')) {
      type = 'OpenDocument';
    } else {
      type = 'this file';
    }
    alert(html10n.get('pad.impexp.exportdisabled', {type}));
    return false;
  }

  // ///
  var pad = undefined;
  const self = {
    init(_pad) {
      pad = _pad;

      // get /p/padname
      // if /p/ isn't available due to a rewrite we use the clientVars padId
      const pad_root_path = new RegExp(/.*\/p\/[^\/]+/).exec(document.location.pathname) || clientVars.padId;
      // get http://example.com/p/padname without Params
      const pad_root_url = `${document.location.protocol}//${document.location.host}${document.location.pathname}`;

      // i10l buttom import
      $('#importsubmitinput').val(html10n.get('pad.impexp.importbutton'));
      html10n.bind('localized', () => {
        $('#importsubmitinput').val(html10n.get('pad.impexp.importbutton'));
      });

      // build the export links
      $('#exporthtmla').attr('href', `${pad_root_path}/export/html`);
      $('#exportetherpada').attr('href', `${pad_root_path}/export/etherpad`);
      $('#exportplaina').attr('href', `${pad_root_path}/export/txt`);

      // activate action to import in the form
      $('#importform').attr('action', `${pad_root_url}/import`);

      // hide stuff thats not avaible if abiword/soffice is disabled
      if (clientVars.exportAvailable == 'no') {
        $('#exportworda').remove();
        $('#exportpdfa').remove();
        $('#exportopena').remove();

        $('#importmessageabiword').show();
      } else if (clientVars.exportAvailable == 'withoutPDF') {
        $('#exportpdfa').remove();

        $('#exportworda').attr('href', `${pad_root_path}/export/doc`);
        $('#exportopena').attr('href', `${pad_root_path}/export/odt`);

        $('#importexport').css({height: '142px'});
        $('#importexportline').css({height: '142px'});
      } else {
        $('#exportworda').attr('href', `${pad_root_path}/export/doc`);
        $('#exportpdfa').attr('href', `${pad_root_path}/export/pdf`);
        $('#exportopena').attr('href', `${pad_root_path}/export/odt`);
      }

      addImportFrames();
      $('#importfileinput').change(fileInputUpdated);
      $('#importform').unbind('submit').submit(fileInputSubmit);
      $('.disabledexport').click(cantExport);
    },
    handleFrameCall(directDatabaseAccess, status) {
      if (directDatabaseAccess === 'undefined') directDatabaseAccess = false;
      if (status !== 'ok') {
        importFailed(status);
      } else {
        $('#import_export').removeClass('popup-show');
      }

      if (directDatabaseAccess) {
        // Switch to the pad without redrawing the page
        pad.switchToPad(clientVars.padId);
        $('#import_export').removeClass('popup-show');
      }

      importDone();
    },
    disable() {
      $('#impexp-disabled-clickcatcher').show();
      $('#import').css('opacity', 0.5);
      $('#impexp-export').css('opacity', 0.5);
    },
    enable() {
      $('#impexp-disabled-clickcatcher').hide();
      $('#import').css('opacity', 1);
      $('#impexp-export').css('opacity', 1);
    },
  };
  return self;
}());

exports.padimpexp = padimpexp;
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import styled from 'styled-components'
import TextField from 'material-ui/TextField'
import MenuItem from 'material-ui/MenuItem'
import Avatar from 'material-ui/Avatar'
import RaisedButton from 'material-ui/RaisedButton'
import FlatButton from 'material-ui/FlatButton'
import SelectField from 'material-ui/SelectField'
import Snackbar from 'material-ui/Snackbar'
import { connect } from 'react-redux'
import { firebase, helpers } from 'react-redux-firebase'
import Paper from 'material-ui/Paper'
const { dataToJS } = helpers
import Dropzone from 'react-dropzone'

// Path within Database for metadata (also used for file Storage path)
const filesPath = 'uploadedFiles'

const Main = styled.div`
  display: flex;
  flexWrap: wrap;
  justify-content: space-around;
`

const FormContainer = styled.div`
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  padding: 10px 10px 10px 10px;
`

const categories = [
  'None',
  'Video & Film',
  'Podcasts',
  'Comics',
  'Comedy',
  'Crafts & DIY',
  'Music',
  'Drawing & Painting',
  'Games',
  'Science',
  'Dance & Theater',
  'Writing',
  'Animation',
  'Photography',
  'Education',
  'Other'
]

class Uploader extends Component {
  render() {
    let dropzoneRef
    return (

        <Dropzone
          ref={node => {
            dropzoneRef = node
          }}
          onDrop={this.props.onDrop}
          style={{ display: 'hidden' }}
        />
        <FlatButton
          label="Change Profile Picture"
          onTouchTap={() => {
            dropzoneRef.open()
          }}
        />

    )
  }
}

class CategoryDropDown extends Component {
  render() {
    return (

        <SelectField
          floatingLabelText="Category"
          value={this.props.value}
          onChange={this.props.onChange}
          maxHeight={200}
        >
          {categories.map((category, index) => <MenuItem key={index} value={category} primaryText={category} />)}
        </SelectField>

    )
  }
}

class EditProfile extends Component {
  constructor(props) {
    super(props)
    this.state = {
      firstName: '',
      lastName: '',
      emailAddress: '',
      category: 'None',
      content: '',
      biography: '',
      ethereumAddress: '',
      openSnackbar: false,
      snackbarMessage: ''
    }
  }

  handleSave = event => {
    const myAddress = this.props.addresses[0]
    const userProfile = {
      firstName: this.state.firstName,
      lastName: this.state.lastName,
      emailAddress: this.state.emailAddress,
      category: this.state.category,
      content: this.state.content,
      biography: this.state.biography,
      photoURL: this.state.photoURL,
      ethereumAddress: myAddress // get address from app state so there is no danger of being manipulated from front-end
    }
    if (this.state.firstName && this.state.lastName && this.state.emailAddress && myAddress) {
      this.props.firebase.set(`/users/${myAddress}`, userProfile).then((success, error) => {
        if (error) {
          console.error(error)
          this.setState({ openSnackbar: true, snackbarMessage: 'Error: Profile not saved' })
        } else {
          this.setState({ openSnackbar: true, snackbarMessage: 'Profile saved' })
        }
      })
    }
  }

  handleCategoryChange = (event, index, value) => {
    this.setState({ category: value })
  }

  handleFieldChange = (stateKey, event, newValue) => {
    const obj = {}
    obj[stateKey] = newValue // so key can be programatically assigned
    this.setState(obj)
  }
  handleFullNameChange = (event, newValue) => {
    if (!newValue) {
      this.setState({ fullNameError: 'Full name is required' })
    } else {
      this.setState({ fullNameError: false })
      this.setState({ fullName: newValue })
    }
  }

  handleBiographyChange = (event, newValue) => {
    this.setState({ biography: newValue })
  }

  onFilesDrop = files => {
    // Uploads files and push's objects containing metadata to database at dbPath
    // uploadFiles(storagePath, files, dbPath)
    this.props.firebase.uploadFiles(filesPath, files, filesPath).then((resolve, reject) => {
      console.log(resolve)
      const photoURL = resolve[0].File.downloadURL
      this.setState({ photoURL: photoURL })
    })
  }

  componentWillReceiveProps() {
    const myAddress = this.props.addresses[0]
    if (this.props.users && this.props.users[myAddress]) {
      const myProfile = this.props.users[myAddress]
      this.setState({
        firstName: myProfile.firstName,
        lastName: myProfile.lastName,
        emailAddress: myProfile.emailAddress,
        category: myProfile.category,
        content: myProfile.content,
        biography: myProfile.biography,
        photoURL: myProfile.photoURL
      })
    }
  }

  render() {
    return (

        <Paper>
          <FormContainer>
            <Avatar src={this.state.photoURL} size={150} />
            <Uploader onDrop={this.onFilesDrop} />
            <TextField
              floatingLabelText="First Name"
              onChange={(event, newValue) => this.handleFieldChange('firstName', event, newValue)}
              errorText={!this.state.firstName ? 'First Name is Required' : null}
              value={this.state.firstName}
            />
            <TextField
              floatingLabelText="Last Name"
              onChange={(event, newValue) => this.handleFieldChange('lastName', event, newValue)}
              errorText={!this.state.lastName ? 'Last Name is Required' : null}
              value={this.state.lastName}
            />
            <TextField
              floatingLabelText="Email Address"
              onChange={(event, newValue) => this.handleFieldChange('emailAddress', event, newValue)}
              errorText={!this.state.emailAddress ? 'Email Address is Required' : null}
              value={this.state.emailAddress}
            />
            <CategoryDropDown onChange={this.handleCategoryChange} value={this.state.category} />
            <TextField
              floatingLabelText="Biography"
              onChange={(event, newValue) => this.handleFieldChange('biography', event, newValue)}
              value={this.state.biography}
            />
            <TextField
              floatingLabelText="Content I'm Creating"
              onChange={(event, newValue) => this.handleFieldChange('content', event, newValue)}
              value={this.state.content}
            />
            Ethereum Address
            {this.props.addresses[0]}
            <RaisedButton label="Save Profile" primary={true} onTouchTap={this.handleSave} />
            <Snackbar
              open={this.state.openSnackbar}
              message={this.state.snackbarMessage}
              autoHideDuration={4000}
              onRequestClose={this.handleRequestClose}
            />
          </FormContainer>
        </Paper>

    )
  }
}

EditProfile.defaultProps = {
  userProfile: {}
}

const fbWrappedComponent = firebase([{ type: 'once', path: '/users' }, 'uploadedFiles'])(EditProfile)
export default connect(({ firebase }) => ({
  users: dataToJS(firebase, 'users'),
  uploadedFiles: dataToJS(firebase, 'uploadedFiles')
}))(fbWrappedComponent)
<commit_msg>Make db keys consistent with explore profiles work.<commit_after>import React, { Component } from 'react'
import styled from 'styled-components'
import TextField from 'material-ui/TextField'
import MenuItem from 'material-ui/MenuItem'
import Avatar from 'material-ui/Avatar'
import RaisedButton from 'material-ui/RaisedButton'
import FlatButton from 'material-ui/FlatButton'
import SelectField from 'material-ui/SelectField'
import Snackbar from 'material-ui/Snackbar'
import { connect } from 'react-redux'
import { firebase, helpers } from 'react-redux-firebase'
import Paper from 'material-ui/Paper'
const { dataToJS } = helpers
import Dropzone from 'react-dropzone'

// Path within Database for metadata (also used for file Storage path)
const filesPath = 'uploadedFiles'

const Main = styled.div`
  display: flex;
  flexWrap: wrap;
  justify-content: space-around;
`

const FormContainer = styled.div`
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  padding: 10px 10px 10px 10px;
`

const categories = [
  'None',
  'Video & Film',
  'Podcasts',
  'Comics',
  'Comedy',
  'Crafts & DIY',
  'Music',
  'Drawing & Painting',
  'Games',
  'Science',
  'Dance & Theater',
  'Writing',
  'Animation',
  'Photography',
  'Education',
  'Other'
]

class Uploader extends Component {
  render() {
    let dropzoneRef
    return (

        <Dropzone
          ref={node => {
            dropzoneRef = node
          }}
          onDrop={this.props.onDrop}
          style={{ display: 'hidden' }}
        />
        <FlatButton
          label="Change Profile Picture"
          onTouchTap={() => {
            dropzoneRef.open()
          }}
        />

    )
  }
}

class CategoryDropDown extends Component {
  render() {
    return (

        <SelectField
          floatingLabelText="Category"
          value={this.props.value}
          onChange={this.props.onChange}
          maxHeight={200}
        >
          {categories.map((category, index) => <MenuItem key={index} value={category} primaryText={category} />)}
        </SelectField>

    )
  }
}

class EditProfile extends Component {
  constructor(props) {
    super(props)
    this.state = {
      first_name: '',
      last_name: '',
      email: '',
      category: 'None',
      content: '',
      biography: '',
      eth_address: '',
      photo_url: '',
      openSnackbar: false,
      snackbarMessage: ''
    }
  }

  handleSave = event => {
    const myAddress = this.props.addresses[0]
    const userProfile = {
      first_name: this.state.first_name,
      last_name: this.state.last_name,
      email: this.state.email,
      category: this.state.category,
      content: this.state.content,
      biography: this.state.biography,
      photo_url: this.state.photo_url,
      eth_address: myAddress // get address from app state so there is no danger of being manipulated from front-end
    }
    if (this.state.first_name && this.state.last_name && this.state.email && myAddress) {
      this.props.firebase.set(`/users/${myAddress}`, userProfile).then((success, error) => {
        if (error) {
          console.error(error)
          this.setState({ openSnackbar: true, snackbarMessage: 'Error: Profile not saved' })
        } else {
          this.setState({ openSnackbar: true, snackbarMessage: 'Profile saved' })
        }
      })
    }
  }

  handleCategoryChange = (event, index, value) => {
    this.setState({ category: value })
  }

  handleFieldChange = (stateKey, event, newValue) => {
    const obj = {}
    obj[stateKey] = newValue // so key can be programatically assigned
    this.setState(obj)
  }

  onFilesDrop = files => {
    // Uploads files and push's objects containing metadata to database at dbPath
    // uploadFiles(storagePath, files, dbPath)
    this.props.firebase.uploadFiles(filesPath, files, filesPath).then((resolve, reject) => {
      console.log(resolve)
      const photoURL = resolve[0].File.downloadURL
      this.setState({ photo_url: photoURL })
    })
  }

  componentWillReceiveProps() {
    const myAddress = this.props.addresses[0]
    if (this.props.users && this.props.users[myAddress]) {
      const myProfile = this.props.users[myAddress]
      this.setState({
        first_name: myProfile.first_name,
        last_name: myProfile.last_name,
        email: myProfile.email,
        category: myProfile.category,
        content: myProfile.content,
        biography: myProfile.biography,
        photo_url: myProfile.photo_url
      })
    }
  }

  render() {
    return (

        <Paper>
          <FormContainer>
            <Avatar src={this.state.photo_url} size={150} />
            <Uploader onDrop={this.onFilesDrop} />
            <TextField
              floatingLabelText="First Name"
              onChange={(event, newValue) => this.handleFieldChange('first_name', event, newValue)}
              errorText={!this.state.first_name ? 'First Name is Required' : null}
              value={this.state.first_name || ''}
            />
            <TextField
              floatingLabelText="Last Name"
              onChange={(event, newValue) => this.handleFieldChange('last_name', event, newValue)}
              errorText={!this.state.last_name ? 'Last Name is Required' : null}
              value={this.state.last_name || ''}
            />
            <TextField
              floatingLabelText="Email Address"
              onChange={(event, newValue) => this.handleFieldChange('email', event, newValue)}
              errorText={!this.state.email ? 'Email Address is Required' : null}
              value={this.state.email || ''}
            />
            <CategoryDropDown onChange={this.handleCategoryChange} value={this.state.category} />
            <TextField
              floatingLabelText="Biography"
              onChange={(event, newValue) => this.handleFieldChange('biography', event, newValue)}
              value={this.state.biography}
            />
            <TextField
              floatingLabelText="Content I'm Creating"
              onChange={(event, newValue) => this.handleFieldChange('content', event, newValue)}
              value={this.state.content}
            />
            Ethereum Address
            {this.props.addresses[0]}
            <RaisedButton label="Save Profile" primary={true} onTouchTap={this.handleSave} />
            <Snackbar
              open={this.state.openSnackbar}
              message={this.state.snackbarMessage}
              autoHideDuration={4000}
              onRequestClose={this.handleRequestClose}
            />
          </FormContainer>
        </Paper>

    )
  }
}

EditProfile.defaultProps = {
  userProfile: {}
}

const fbWrappedComponent = firebase([{ type: 'once', path: '/users' }, 'uploadedFiles'])(EditProfile)
export default connect(({ firebase }) => ({
  users: dataToJS(firebase, 'users'),
  uploadedFiles: dataToJS(firebase, 'uploadedFiles')
}))(fbWrappedComponent)
<|endoftext|>


<commit_before>import rootReducer          from '../reducers';
import thunk                from 'redux-thunk';
import DevTools             from 'containers/DevTools';
import {
  applyMiddleware,
  compose,
  createStore
} from 'redux';

export default function configureStore (initialState, debug = false) {
  let createStoreWithMiddleware;

  const middleware = applyMiddleware(thunk);

  if (debug) {
    createStoreWithMiddleware = compose(
      middleware,
      DevTools.instrument()
    );
  }

  const store = createStoreWithMiddleware(createStore)(
    rootReducer, initialState
  );
  if (module.hot) {
    module.hot.accept('../reducers', () => {
      const nextRootReducer = require('../reducers/index');

      store.replaceReducer(nextRootReducer);
    });
  }
  return store;
}
<commit_msg>Fixed a breakage while creating the store<commit_after>import rootReducer          from '../reducers';
import thunk                from 'redux-thunk';
import DevTools             from 'containers/DevTools';
import {
  applyMiddleware,
  compose,
  createStore
} from 'redux';

export default function configureStore (initialState, debug = false) {
  let createStoreWithMiddleware;

  const middleware = applyMiddleware(thunk);

  if (debug) {
    createStoreWithMiddleware = compose(
      middleware,
      DevTools.instrument()
    );
  }else{
    createStoreWithMiddleware = compose(middleware);
  }

  const store = createStoreWithMiddleware(createStore)(
    rootReducer, initialState
  );
  if (module.hot) {
    module.hot.accept('../reducers', () => {
      const nextRootReducer = require('../reducers/index');

      store.replaceReducer(nextRootReducer);
    });
  }
  return store;
}
<|endoftext|>


<commit_before>var im=function(){function e(e){c=e}function t(e){"manual"==e&&(v=!1,n())}function n(){if(window.getComputedStyle&&""!=window.getComputedStyle(c,"::after").content){var e=window.getComputedStyle(c,"::after").content;try{f=JSON.parse(i(e))}catch(t){}}}function a(e){return v&&n(),f.hasOwnProperty(e)&&f[e].hasOwnProperty("active")&&f[e].active}function r(e){return!a(e)}function o(){v&&n();var e={name:!1,value:0};for(var t in f)if(f.hasOwnProperty(t)&&f[t].hasOwnProperty("active")){var a=parseFloat(f[t].value);f[t].active&&a>e.value&&(e={name:t,value:a})}return e.name}function u(e,t){return v&&n(),f&&f.hasOwnProperty(e)?t?parseFloat(f[e].value):f[e].value:!1}function i(e){return("string"==typeof e||e instanceof String)&&(e=e.replace(/^['"]+|\s+|\\|(;\s?})+|['"]$/g,"")),e}var c=document.body,v=!0,f=!1;return{setElement:e,setUpdateMode:t,greaterThan:a,lessThan:r,getActive:o,getValue:u,update:n}}();<commit_msg>update minified version<commit_after>var im=function(){function e(e){c=e}function t(e){"manual"==e&&(l=!1,n())}function n(){if(window.getComputedStyle&&""!==window.getComputedStyle(c,"::after").content){var e=window.getComputedStyle(c,"::after").content;try{v=JSON.parse(i(e))}catch(t){}}}function a(e){return l&&n(),v.hasOwnProperty(e)&&v[e].hasOwnProperty("active")&&v[e].active}function r(e){return!a(e)}function o(){l&&n();var e={name:!1,value:0};for(var t in v)if(v.hasOwnProperty(t)&&v[t].hasOwnProperty("active")){var a=parseFloat(v[t].value);v[t].active&&a>e.value&&(e={name:t,value:a})}return e.name}function u(e,t){return l&&n(),v&&v.hasOwnProperty(e)?t?parseFloat(v[e].value):v[e].value:!1}function i(e){return("string"==typeof e||e instanceof String)&&(e=e.replace(/[']/g,'"').replace(/\\|^[\s\S]{0,1}|[\s\S]$/g,"")),e}var c=document.body,l=!0,v=!1;return{setElement:e,setUpdateMode:t,greaterThan:a,lessThan:r,getActive:o,getValue:u,update:n}}();<|endoftext|>