<commit_before>//
// @route /community/domain/add
//
import { connect } from 'react-redux'
import { reduxForm } from 'redux-form'
import { injectIntl } from 'react-intl'
// import { addNotification as notify } from 'reapop'

import { isValidDomain } from 'utils/validation-helper'
import DnsControlSelectors from 'community/dns-control-selectors'
import * as dnsNotify from 'community/notifications/dns'
import {
  asyncAddHostedZone as addHostedZone,
  asyncCheckHostedZone
} from 'community/action-creators/dns-control'
import Page from './page'

const fields = ['domain_name']

const validate = (values, { intl }) => {
  const errors = {}
  if (!values.domain_name) {
    errors.domain_name = intl.formatMessage({
      id: 'page--community-domain-create.step-add.form.domain-name.validation.required',
      defaultMessage: 'Domínio é obrigatório.'
    })
  } else if (!isValidDomain(values.domain_name)) {
    errors.domain_name = intl.formatMessage({
      id: 'page--community-domain-create.step-add.form.domain-name.validation.invalid-domain-format',
      defaultMessage: 'Domínio inválido'
    })
  }
  return errors
}

const mapStateToProps = state => ({
  saving: DnsControlSelectors(state).dnsHostedZones().isSaving()
})

const mapActionsToProps = (dispatch, { intl }) => ({
  asyncAddHostedZone: (values) => {
    return dispatch(addHostedZone(values))
      // eslint-disable-next-line handle-callback-err
      .catch(err => {
        // dispatch(notify(dnsNotify.addHostedZoneFailure(intl)))
        toast.error(dnsNotify.addHostedZoneFailure(intl).message, {
          autoClose: 5000,
          hideProgressBar: true,
        })
      })
  },
  asyncCheckHostedZone: (args) => dispatch(asyncCheckHostedZone(args)),
  notify: (args) => {
    console.log(args)
    toast.error(args, {
      autoClose: 5000,
      hideProgressBar: true,
    })
    //dispatch(notify(args))
  }
})

export default injectIntl(connect(mapStateToProps, mapActionsToProps)(
  reduxForm({ form: 'createDomainForm', fields, validate })(Page))
)
<commit_msg>feat(admin): refactor notification domain page settings<commit_after>//
// @route /community/domain/add
//
import { connect } from 'react-redux'
import { reduxForm } from 'redux-form'
import { injectIntl } from 'react-intl'
// import { addNotification as notify } from 'reapop'
import { toast } from 'react-toastify'
import { isValidDomain } from 'utils/validation-helper'
import DnsControlSelectors from 'community/dns-control-selectors'
import * as dnsNotify from 'community/notifications/dns'
import {
  asyncAddHostedZone as addHostedZone,
  asyncCheckHostedZone
} from 'community/action-creators/dns-control'
import Page from './page'

const fields = ['domain_name']

const validate = (values, { intl }) => {
  const errors = {}
  if (!values.domain_name) {
    errors.domain_name = intl.formatMessage({
      id: 'page--community-domain-create.step-add.form.domain-name.validation.required',
      defaultMessage: 'Domínio é obrigatório.'
    })
  } else if (!isValidDomain(values.domain_name)) {
    errors.domain_name = intl.formatMessage({
      id: 'page--community-domain-create.step-add.form.domain-name.validation.invalid-domain-format',
      defaultMessage: 'Domínio inválido'
    })
  }
  return errors
}

const mapStateToProps = state => ({
  saving: DnsControlSelectors(state).dnsHostedZones().isSaving()
})

const mapActionsToProps = (dispatch, { intl }) => ({
  asyncAddHostedZone: (values) => {
    return dispatch(addHostedZone(values))
      // eslint-disable-next-line handle-callback-err
      .catch(err => {
        // dispatch(notify(dnsNotify.addHostedZoneFailure(intl)))
        toast.error(dnsNotify.addHostedZoneFailure(intl).message, {
          autoClose: 5000,
          hideProgressBar: true,
        })
      })
  },
  asyncCheckHostedZone: (args) => dispatch(asyncCheckHostedZone(args)),
  notify: (args) => {
    console.log(args)
    toast.error(args, {
      autoClose: 5000,
      hideProgressBar: true,
    })
    //dispatch(notify(args))
  }
})

export default injectIntl(connect(mapStateToProps, mapActionsToProps)(
  reduxForm({ form: 'createDomainForm', fields, validate })(Page))
)
<|endoftext|>


<commit_before>import React from 'react';
import { Card, CardHead, CardHeader, CardBody, CardFooter, Button } from "@patternfly/react-core";
import { ArrowRightIcon, CubesIcon, ClockIcon, RunningIcon, PuzzlePieceIcon, ChartBarIcon } from '@patternfly/react-icons';
import { NoPrefixLink } from '../noPrefixLink/noPrefixLink';
import { Location } from '@reach/router';
import { capitalize } from '../../helpers/capitalize';
import './trainingCard.css';

const getTrainingIcon = trainingType => {
  if (['htmlcss', 'react'].includes(trainingType)) {
    return <CubesIcon className="training-basics" />;
  }
  else if (trainingType === 'reactcomponents') {
    return <PuzzlePieceIcon className="training-components" />;
  }

  return <ChartBarIcon className="training-charts" />;
}

export const TrainingCard = ({
  trainingType,
  level,
  title,
  time,
  description,
  katacodaId
}) => (
  <Card className="ws-org-training-card" isCompact>
    <CardHead>
      <Card className="small-card-icon">
        {getTrainingIcon(trainingType)}
      </Card>

        <RunningIcon className={`level-${level}`} />
        {capitalize(level)}

    </CardHead>
    <CardHeader>
      {title}
    </CardHeader>
    <CardBody>

        <ClockIcon />
        {time}

      {description}
    </CardBody>
    <CardFooter>
    <Location>
      {({ location }) => (
        <NoPrefixLink
          to={location.pathname}
          state={{ trainingType, katacodaId }} // To show embedded tutorial
        >
          <Button variant="link">
            Start
            <ArrowRightIcon />
          </Button>
        </NoPrefixLink>
      )}
    </Location>
    </CardFooter>
  </Card>
);
<commit_msg>add correct icons back to card (#1605)<commit_after>import React from 'react';
import { Card, CardHead, CardHeader, CardBody, CardFooter, Button } from "@patternfly/react-core";
import { ArrowRightIcon, CubesIcon, ClockIcon, RunningIcon, PuzzlePieceIcon, ChartBarIcon } from '@patternfly/react-icons';
import { NoPrefixLink } from '../noPrefixLink/noPrefixLink';
import { Location } from '@reach/router';
import { capitalize } from '../../helpers/capitalize';
import './trainingCard.css';

const getTrainingIcon = trainingType => {
  if (['html-css', 'react'].includes(trainingType)) {
    return <CubesIcon className="training-basics" />;
  }
  else if (trainingType === 'react-components') {
    return <PuzzlePieceIcon className="training-components" />;
  }

  return <ChartBarIcon className="training-charts" />;
}

export const TrainingCard = ({
  trainingType,
  level,
  title,
  time,
  description,
  katacodaId
}) => (
  <Card className="ws-org-training-card" isCompact>
    <CardHead>
      <Card className="small-card-icon">
        {getTrainingIcon(trainingType)}
      </Card>

        <RunningIcon className={`level-${level}`} />
        {capitalize(level)}

    </CardHead>
    <CardHeader>
      {title}
    </CardHeader>
    <CardBody>

        <ClockIcon />
        {time}

      {description}
    </CardBody>
    <CardFooter>
    <Location>
      {({ location }) => (
        <NoPrefixLink
          to={location.pathname}
          state={{ trainingType, katacodaId }} // To show embedded tutorial
        >
          <Button variant="link">
            Start
            <ArrowRightIcon />
          </Button>
        </NoPrefixLink>
      )}
    </Location>
    </CardFooter>
  </Card>
);
<|endoftext|>


<commit_before>'use strict';

var db           = require('mano').db
  , User         = require('mano-auth/model/user')(db);

User.prototype.defineProperties({
	certificates: {
		type: db.Object,
		nested: true
	}
});
<commit_msg>export user<commit_after>'use strict';

var db           = require('mano').db
  , User         = require('mano-auth/model/user')(db);

User.prototype.defineProperties({
	certificates: {
		type: db.Object,
		nested: true
	}
});

module.exports = User;
<|endoftext|>


<commit_before>//  Immediately invoked function expression is used to
//  create a pseudo-private scope for our api definition
//  a reference to the `window` object is passed into the
//  closure and referenced as `global`. This is both
//  beneficial for compressors and provides a fast
//  reference to the window context
(function(global) {

  //  Cache refs to speed up calls to native utils
  var
  forEach = Array.prototype.forEach,
  hasOwn = Object.prototype.hasOwnProperty,
  slice = Array.prototype.slice,

  //  ID string matching
  rIdExp  = /^(#([\w\-\_\.]+))$/,

  //  Declare a pseudo-private constructor
  //  This constructor returns the instance object.
  Popcorn = function( entity ) {
    //  Return new instance of
    //  Popcorn.prototype.instance constructor
    return new Popcorn.p.init( entity );
  };

  //  Declare a shortcut (Popcorn.p) to and a definition of
  //  the new prototype for our Popcorn constructor
  Popcorn.p = Popcorn.prototype = {

    init: function( entity ) {

      var elem, matches;

      matches = rIdExp.exec( entity );

      if ( matches.length && matches[2]  ) {
        elem = document.getElementById(matches[2]);
      }

      this.video = elem ? elem : null;

      this.data = {
        events: {},
        tracks: []
      };

      return this;
    }
  };

  //  This trick allows our api methods to be chained to
  //  instance references.
  Popcorn.p.init.prototype = Popcorn.p;

  Popcorn.forEach = function( obj, fn, context ) {

    if ( !obj || !fn ) {
      return {};
    }

    context = context || this;
    // Use native whenever possible
    if ( forEach && obj.forEach === forEach ) {
      return obj.forEach(fn, context);
    }

    for ( var key in obj ) {
      if ( hasOwn.call(obj, key) ) {
        fn.call(context, obj[key], key, obj);
      }
    }

    return obj;
  };

  Popcorn.extend = function( obj ) {
    var dest = obj, src = slice.call(arguments, 1);

    Popcorn.forEach( src, function( copy ) {
      for ( var prop in copy ) {
        dest[prop] = copy[prop];
      }
    });
    return dest;
  };

  // A Few reusable utils, memoized onto Popcorn
  Popcorn.extend( Popcorn, {
    guid: function() {
      return +new Date() + Math.floor(Math.random()*11);
    },
    sizeOf: function ( obj ) {
      var size = 0;

      for ( var prop in obj  ) {
        size++;
      }

      return size;
    }
  });

  //  Simple Factory pattern to implement native
  //  getters/setters and controllers
  //  as methods of the returned Popcorn instance
  //  The immediately invoked function creates
  //  and returns an object of methods
  Popcorn.extend(Popcorn.p, (function () {

      // todo: play, pause, mute should toggle
      var methods = "load play pause currentTime playbackRate mute volume duration",
          ret = {};

      //  Build methods, store in object that is returned and passed to extend
      Popcorn.forEach( methods.split(/\s+/g), function( name ) {

        ret[ name ] = function( arg ) {

          if ( typeof this.video[name] === "function" ) {
            this.video[ name ]();

            return this;
          }

          if ( arg !== false && arg !== null && typeof arg !== "undefined" ) {

            this.video[ name ] = arg;

            return this;
          }

          return this.video[ name ];
        };
      });

      return ret;

    })()
  );

  Popcorn.extend(Popcorn.p, {

    setCommand: function() {

    },
    getCommand: function() {

    },
    toTrack: function( setup ) {
      /*
      {
        in: ts,
        out: ts,
        command: f()
      }
      */
      // stores the command in a track
    }

  });

  var nativeEvents = "loadstart progress suspend emptied stalled play pause " +
                     "loadedmetadata loadeddata waiting playing canplay canplaythrough " +
                     "seeking seeked timeupdate ended ratechange durationchange volumechange";

  Popcorn.events  = {
    //todo, fix types to be custom, natives will be native only
    types: nativeEvents.split(/\s+/g),
    natives: nativeEvents.split(/\s+/g),
    custom: [ "frame" ],
    all: [ "frame" ].concat( nativeEvents.split(/\s+/g) ),
    fn: {
      trigger: function ( type, data ) {

        //  setup checks for custom event system
        if ( this.data.events[type] && Popcorn.sizeOf(this.data.events[type]) ) {

          var evt = document.createEvent("Events");
              evt.initEvent(type, true, true, window, 1);

          this.video.dispatchEvent(evt);

          /*

          TODO: implement some form of custom event system
          Popcorn.forEach(this.data.events[type], function ( obj, key ) {

            //obj.call(_target, _data);

            // update to dispatch an event

          });
          */
        }
      },
      listen: function ( type, fn ) {

        var self = this, hasEvents = true;

        if ( !this.data.events[type] ) {
          this.data.events[type] = {};
          hasEvents = false;
        }

        //  Register
        this.data.events[type][ fn.toString() + Popcorn.guid() ] = fn;

        // only attach one event of any type
        if (!hasEvents && Popcorn.events.all.indexOf( type ) > -1 ) {

          this.video.addEventListener( type, function( event ) {

            Popcorn.forEach( self.data.events[type], function ( obj, key ) {
              obj.call(self, event);
            });

            //fn.call( self, event );

          }, false);
        }
        return this;
      },
      unlisten: function( type ) {
        this.data.events[type] = null;
        return this;
      },
      special: {
        // handles timeline controllers
        play: function () {
          //  renders all of the interally stored track commands
        }
      }
    }
  };

  //  Extend listen and trigger to all Popcorn instances
  Popcorn.forEach( ["trigger", "listen", "unlisten"], function ( key ) {
    Popcorn.p[key] = Popcorn.events.fn[key];
  });

  //  Plugins are registered
  Popcorn.registry = [];
  //  An interface for extending Popcorn
  //  with plugin functionality
  Popcorn.plugin = function( name, definition ) {

    //  Provides some sugar, but ultimately extends
    //  the definition into Popcorn.p

    var plugin = {}, setup;

    if ( typeof definition === "object" ) {

      setup = definition;

      definition  = function ( options ) {

        var self = this;

        if ( !options ) {
          return this;
        }

        if ( !( "start" in options ) ) {
          options.start = 0;
        }

        if ( !( "end" in options ) ) {
          options.end = this.duration();
        }

        if ( "_setup" in setup && typeof setup._setup === "function" ) {
          setup._setup.call(self, options);
        }

        this.listen( "timeupdate", function( event ) {

          if ( ~~self.currentTime() === options.start ||
                  self.currentTime() === options.start ) {

            setup.start.call(self, event, options);
          }

          if ( self.currentTime() > options.start &&
                self.currentTime() < options.end ) {

            setup.timeupdate.call(self, event, options);

          }

          if ( ~~self.currentTime() === options.end ||
                  self.currentTime() === options.end ) {

            setup.end.call(self, event, options);
          }

        });

        return this;
      };
    }

    plugin[ name ] = definition;

    Popcorn.extend( Popcorn.p, plugin );

    Popcorn.registry.push({
      name: name,
      plugin: plugin
    });

    //  within the context of a plugin
    //  any of the events can be listened to
  };

  global.Popcorn = Popcorn;

})(window);
<commit_msg>Implements Popcorn.nop() - basic no operation reference;<commit_after>//  Immediately invoked function expression is used to
//  create a pseudo-private scope for our api definition
//  a reference to the `window` object is passed into the
//  closure and referenced as `global`. This is both
//  beneficial for compressors and provides a fast
//  reference to the window context
(function(global) {

  //  Cache refs to speed up calls to native utils
  var
  forEach = Array.prototype.forEach,
  hasOwn = Object.prototype.hasOwnProperty,
  slice = Array.prototype.slice,

  //  ID string matching
  rIdExp  = /^(#([\w\-\_\.]+))$/,

  //  Declare a pseudo-private constructor
  //  This constructor returns the instance object.
  Popcorn = function( entity ) {
    //  Return new instance of
    //  Popcorn.prototype.instance constructor
    return new Popcorn.p.init( entity );
  };

  //  Declare a shortcut (Popcorn.p) to and a definition of
  //  the new prototype for our Popcorn constructor
  Popcorn.p = Popcorn.prototype = {

    init: function( entity ) {

      var elem, matches;

      matches = rIdExp.exec( entity );

      if ( matches.length && matches[2]  ) {
        elem = document.getElementById(matches[2]);
      }

      this.video = elem ? elem : null;

      this.data = {
        events: {},
        tracks: []
      };

      return this;
    }
  };

  //  This trick allows our api methods to be chained to
  //  instance references.
  Popcorn.p.init.prototype = Popcorn.p;

  Popcorn.forEach = function( obj, fn, context ) {

    if ( !obj || !fn ) {
      return {};
    }

    context = context || this;
    // Use native whenever possible
    if ( forEach && obj.forEach === forEach ) {
      return obj.forEach(fn, context);
    }

    for ( var key in obj ) {
      if ( hasOwn.call(obj, key) ) {
        fn.call(context, obj[key], key, obj);
      }
    }

    return obj;
  };

  Popcorn.extend = function( obj ) {
    var dest = obj, src = slice.call(arguments, 1);

    Popcorn.forEach( src, function( copy ) {
      for ( var prop in copy ) {
        dest[prop] = copy[prop];
      }
    });
    return dest;
  };

  // A Few reusable utils, memoized onto Popcorn
  Popcorn.extend( Popcorn, {
    guid: function() {
      return +new Date() + Math.floor(Math.random()*11);
    },
    sizeOf: function ( obj ) {
      var size = 0;

      for ( var prop in obj  ) {
        size++;
      }

      return size;
    },
    nop: function () {}
  });

  //  Simple Factory pattern to implement native
  //  getters/setters and controllers
  //  as methods of the returned Popcorn instance
  //  The immediately invoked function creates
  //  and returns an object of methods
  Popcorn.extend(Popcorn.p, (function () {

      // todo: play, pause, mute should toggle
      var methods = "load play pause currentTime playbackRate mute volume duration",
          ret = {};

      //  Build methods, store in object that is returned and passed to extend
      Popcorn.forEach( methods.split(/\s+/g), function( name ) {

        ret[ name ] = function( arg ) {

          if ( typeof this.video[name] === "function" ) {
            this.video[ name ]();

            return this;
          }

          if ( arg !== false && arg !== null && typeof arg !== "undefined" ) {

            this.video[ name ] = arg;

            return this;
          }

          return this.video[ name ];
        };
      });

      return ret;

    })()
  );

  Popcorn.extend(Popcorn.p, {

    setCommand: function() {

    },
    getCommand: function() {

    },
    toTrack: function( setup ) {
      /*
      {
        in: ts,
        out: ts,
        command: f()
      }
      */
      // stores the command in a track
    }

  });

  var nativeEvents = "loadstart progress suspend emptied stalled play pause " +
                     "loadedmetadata loadeddata waiting playing canplay canplaythrough " +
                     "seeking seeked timeupdate ended ratechange durationchange volumechange";

  Popcorn.events  = {
    //todo, fix types to be custom, natives will be native only
    types: nativeEvents.split(/\s+/g),
    natives: nativeEvents.split(/\s+/g),
    custom: [ "frame" ],
    all: [ "frame" ].concat( nativeEvents.split(/\s+/g) ),
    fn: {
      trigger: function ( type, data ) {

        //  setup checks for custom event system
        if ( this.data.events[type] && Popcorn.sizeOf(this.data.events[type]) ) {

          var evt = document.createEvent("Events");
              evt.initEvent(type, true, true, window, 1);

          this.video.dispatchEvent(evt);

          /*

          TODO: implement some form of custom event system
          Popcorn.forEach(this.data.events[type], function ( obj, key ) {

            //obj.call(_target, _data);

            // update to dispatch an event

          });
          */
        }
      },
      listen: function ( type, fn ) {

        var self = this, hasEvents = true;

        if ( !this.data.events[type] ) {
          this.data.events[type] = {};
          hasEvents = false;
        }

        //  Register
        this.data.events[type][ fn.toString() + Popcorn.guid() ] = fn;

        // only attach one event of any type
        if (!hasEvents && Popcorn.events.all.indexOf( type ) > -1 ) {

          this.video.addEventListener( type, function( event ) {

            Popcorn.forEach( self.data.events[type], function ( obj, key ) {
              obj.call(self, event);
            });

            //fn.call( self, event );

          }, false);
        }
        return this;
      },
      unlisten: function( type ) {
        this.data.events[type] = null;
        return this;
      },
      special: {
        // handles timeline controllers
        play: function () {
          //  renders all of the interally stored track commands
        }
      }
    }
  };

  //  Extend listen and trigger to all Popcorn instances
  Popcorn.forEach( ["trigger", "listen", "unlisten"], function ( key ) {
    Popcorn.p[key] = Popcorn.events.fn[key];
  });

  //  Plugins are registered
  Popcorn.registry = [];
  //  An interface for extending Popcorn
  //  with plugin functionality
  Popcorn.plugin = function( name, definition ) {

    //  Provides some sugar, but ultimately extends
    //  the definition into Popcorn.p

    var plugin = {}, setup;

    if ( typeof definition === "object" ) {

      setup = definition;

      definition  = function ( options ) {

        var self = this;

        if ( !options ) {
          return this;
        }

        if ( !( "start" in options ) ) {
          options.start = 0;
        }

        if ( !( "end" in options ) ) {
          options.end = this.duration();
        }

        if ( "_setup" in setup && typeof setup._setup === "function" ) {
          setup._setup.call(self, options);
        }

        this.addEventListener( "timeupdate", function( event ) {

          if ( ~~self.currentTime() === options.start ||
                  self.currentTime() === options.start ) {

            setup.start.call(self, event, options);
          }

          if ( self.currentTime() > options.start &&
                self.currentTime() < options.end ) {

            setup.timeupdate.call(self, event, options);

          }

          if ( ~~self.currentTime() === options.end ||
                  self.currentTime() === options.end ) {

            setup.end.call(self, event, options);
          }

        }, false);

        return this;
      };
    }

    plugin[ name ] = definition;

    Popcorn.extend( Popcorn.p, plugin );

    Popcorn.registry.push({
      name: name,
      plugin: plugin
    });

    //  within the context of a plugin
    //  any of the events can be listened to
  };

  global.Popcorn = Popcorn;

})(window);
<|endoftext|>


<commit_before>
const RG = require('../src/rg');
const Castle = require('../data/tiles.castle');

const dwarvenCityConf = {
  outerColsRatio: 0.4,
  outerRowsRatio: 0.4,
  outerStartXRatio: 0.3
};
export {dwarvenCityConf};

const TILE_SIZE = 7;

/* Creates the level for the dwarven city. Uses mainly Castle tiles and mountain
 * walls to create the level.
 */
export default class DwarvenCity {

    constructor(cols, rows, conf = dwarvenCityConf) {
      const wallOpts = {
        meanWy: Math.floor(0.9 * rows / 2),
        stdDev: 10,
        filterW: 7
      };
      const mainLevel = RG.FACT.createLevel('wall', cols, rows, wallOpts);

      const outerColsRatio = conf.outerColsRatio || 0.35;
      const outerRowsRatio = conf.outerRowsRatio || 0.35;

      const mapGen = new RG.Map.Generator();
      const outerFortConf = {
          startRoomFunc: Castle.startFuncFourGates
      };
      let outerCols = Math.round(outerColsRatio * cols);
      let outerRows = Math.round(outerRowsRatio * rows);
      outerCols = this.adjustToTileSize(outerCols);
      outerRows = this.adjustToTileSize(outerRows);

      const outerFort = mapGen.createCastleWall(outerCols, outerRows,
        outerFortConf);

      const mainFort = mapGen.createCastleWall(outerCols, outerRows,
        outerFortConf);

      const smallFortWest = mapGen.createCastleWall(3 * 7, 3 * 7,
        {startRoomFunc: Castle.startRoomFuncEast}
      );
      const smallFortEast = mapGen.createCastleWall(3 * 7, 3 * 7,
        {startRoomFunc: Castle.startRoomFuncWest}
      );

      const outerFortLevel = new RG.Map.Level(10, 10);
      outerFortLevel.setMap(outerFort.map);

      const mainFortLevel = new RG.Map.Level(10, 10);
      mainFortLevel.setMap(mainFort.map);

      const fortWestLevel = new RG.Map.Level(10, 10);
      fortWestLevel.setMap(smallFortWest.map);
      const fortEastLevel = new RG.Map.Level(10, 10);
      fortEastLevel.setMap(smallFortEast.map);

      const subLevels = [fortWestLevel, outerFortLevel, fortEastLevel];
      const tileConf = {
        centerY: false,
        centerX: true,
        y: 10,
        // x: Math.floor((cols - outerCols) / 2)
        x: 0
      };
      const entrFortLevel = RG.Geometry.wrapAsLevel(subLevels, {centerY: true});
      RG.Geometry.tileLevels(mainLevel,
        [mainFortLevel, entrFortLevel], tileConf);

      this.level = mainLevel;
    }

    adjustToTileSize(number) {
      while (number % TILE_SIZE !== 0) {
        ++number;
      }
      if (number % 2 * TILE_SIZE === 0) {number += TILE_SIZE;}
      return number;
    }

    getLevel() {
      return this.level;
    }

}
<commit_msg>Added creation of actors.<commit_after>
const RG = require('../src/rg');
const Castle = require('../data/tiles.castle');

const dwarvenCityConf = {
  outerColsRatio: 0.4,
  outerRowsRatio: 0.4,
  outerStartXRatio: 0.3
};
export {dwarvenCityConf};

const TILE_SIZE = 7;

/* Creates the level for the dwarven city. Uses mainly Castle tiles and mountain
 * walls to create the level.
 */
export default class DwarvenCity {

    constructor(cols, rows, conf = dwarvenCityConf) {
      const wallOpts = {
        meanWy: Math.floor(0.9 * rows / 2),
        stdDev: 10,
        filterW: 7
      };
      const mainLevel = RG.FACT.createLevel('wall', cols, rows, wallOpts);

      const outerColsRatio = conf.outerColsRatio || 0.35;
      const outerRowsRatio = conf.outerRowsRatio || 0.35;

      const mapGen = new RG.Map.Generator();
      const outerFortConf = {
          startRoomFunc: Castle.startFuncFourGates
      };
      let outerCols = Math.round(outerColsRatio * cols);
      let outerRows = Math.round(outerRowsRatio * rows);
      outerCols = this.adjustToTileSize(outerCols);
      outerRows = this.adjustToTileSize(outerRows);

      const outerFort = mapGen.createCastleWall(outerCols, outerRows,
        outerFortConf);

      const mainFort = mapGen.createCastleWall(outerCols, outerRows,
        outerFortConf);

      const smallFortWest = mapGen.createCastleWall(3 * 7, 3 * 7,
        {startRoomFunc: Castle.startRoomFuncEast}
      );
      const smallFortEast = mapGen.createCastleWall(3 * 7, 3 * 7,
        {startRoomFunc: Castle.startRoomFuncWest}
      );

      const outerFortLevel = new RG.Map.Level(10, 10);
      outerFortLevel.setMap(outerFort.map);

      const mainFortLevel = new RG.Map.Level(10, 10);
      mainFortLevel.setMap(mainFort.map);

      const fortWestLevel = new RG.Map.Level(10, 10);
      fortWestLevel.setMap(smallFortWest.map);
      const fortEastLevel = new RG.Map.Level(10, 10);
      fortEastLevel.setMap(smallFortEast.map);

      const subLevels = [fortWestLevel, outerFortLevel, fortEastLevel];
      const tileConf = {
        centerY: false,
        centerX: true,
        y: 10,
        // x: Math.floor((cols - outerCols) / 2)
        x: 0
      };
      const entrFortLevel = RG.Geometry.wrapAsLevel(subLevels, {centerY: true});
      RG.Geometry.tileLevels(mainLevel,
        [mainFortLevel, entrFortLevel], tileConf);

      const parser = RG.ObjectShell.getParser();
      // Create the actors and items for this level
      const actorConf = {
          fighter: 100,
          axeman: 50,
          elite: 25,
          rifleman: 25,
          commander: 5
      };
      const actors = [];
      Object.keys(actorConf).forEach(key => {
        const name = `dwarven ${key}`;
        const num = actorConf[key];
        for (let i = 0; i < num; i++) {
            const actor = parser.createActor(name);
            actors.push(actor);
        }
      });
      RG.Factory.addPropsToFreeCells(mainLevel, actors, RG.TYPE_ACTOR);

      this.level = mainLevel;
    }

    adjustToTileSize(number) {
      while (number % TILE_SIZE !== 0) {
        ++number;
      }
      if (number % 2 * TILE_SIZE === 0) {number += TILE_SIZE;}
      return number;
    }

    getLevel() {
      return this.level;
    }

}
<|endoftext|>


<commit_before>"use strict";

function $(id){ return document.getElementById(id); }

function showElement( e ) { e.style.visibility = "visible"; }
function hideElement( e ) { e.style.visibility = "hidden"; }

function PPUtils() {}

PPUtils.log = function ( output ) {
    if (window.console ) {
      console.log(output);
    }
}

PPUtils.objectImplementsMethod = function ( obj, method ) {

  if (obj == null || !obj[method] || typeof obj[method] !== 'function') {
    return false;
  }

  return true;
}

PPUtils.objectImplementsMethods = function ( obj, methodArray ) {
  for (var i = 0; i < methodArray.length; i++) {
    if ( PPUtils.objectImplementsMethod(obj, methodArray[i]) == false) {
      return false;
    }
  }
  return true;
}

PPUtils.setElementAttributes = function ( element, attributeArray, valuesArray) {
   for( var i = 0; i < attributeArray.length; i ++ ) {
     element.setAttribute( attributeArray[i], valuesArray[i]);
   }
}

// References:
//   http://krasimirtsonev.com/blog/article/object-oriented-programming-oop-in-javascript-extending-Inheritance-classes
//   http://peter.michaux.ca/articles/class-based-inheritance-in-javascript
PPUtils.extend = function (ChildClass, ParentClass) {
    var parent = new ParentClass();
    ChildClass.prototype = parent;
    ChildClass.prototype.superclass = parent.constructor;
    ChildClass.prototype.constructor = ChildClass;
    ChildClass.superclass =  ParentClass;
    ChildClass.superproto = ParentClass.prototype;
}

// Returns the callback so that it can be removed later
PPUtils.bindTextField = function(event, element, boundObj, objCallback) {

  var callback = function receive(evt) {
    boundObj[objCallback](element, evt);
  }

  if ( typeof element.addEventListener != "undefined" ) {
    element.addEventListener(event, callback, false);
  } else if ( typeof element.attachEvent != "undefined" ) { // Supports IE < 9
    element.attachEvent(event, callback);
  }

  return callback;
}
PPUtils.bind = function(event, element, callback) {
  if ( typeof element.addEventListener != "undefined" ) {
    element.addEventListener(event, callback, false);
  } else if ( typeof element.attachEvent != "undefined" ) { // Supports IE < 9
    element.attachEvent(event, callback);
  }
}

PPUtils.isPowerOf2 = function(x) {
  return x == 1 || x == 2 || x == 4 || x == 8 || x == 16 || x == 32 ||
     x == 64 || x == 128 || x == 256 || x == 512 || x == 1024 ||
                x == 2048 || x == 4096 || x == 8192 || x == 16384 ||
                x == 32768 || x == 65536 || x == 131072 || x == 262144 ||
                x == 524288 || x == 1048576 || x == 2097152 ||
                x == 4194304 || x == 8388608 || x == 16777216 ||
                x == 33554432 || x == 67108864 || x == 134217728 ||
                x == 268435456 || x == 536870912 || x == 1073741824 ||
                x == 2147483648;
}

PPUtils.notifyListeners = function (listenersArray, listenerMethod,value ) {
  for (var i = 0 ; i < listenersArray.length; i++) {
    var obj = listenersArray[i];
    obj[listenerMethod](value);
  }
}
<commit_msg>Tweak object inheritence extend<commit_after>"use strict";

function $(id){ return document.getElementById(id); }

function showElement( e ) { e.style.visibility = "visible"; }
function hideElement( e ) { e.style.visibility = "hidden"; }

function PPUtils() {}

PPUtils.log = function ( output ) {
    if (window.console ) {
      console.log(output);
    }
}

PPUtils.objectImplementsMethod = function ( obj, method ) {

  if (obj == null || !obj[method] || typeof obj[method] !== 'function') {
    return false;
  }

  return true;
}

PPUtils.objectImplementsMethods = function ( obj, methodArray ) {
  for (var i = 0; i < methodArray.length; i++) {
    if ( PPUtils.objectImplementsMethod(obj, methodArray[i]) == false) {
      return false;
    }
  }
  return true;
}

PPUtils.setElementAttributes = function ( element, attributeArray, valuesArray) {
   for( var i = 0; i < attributeArray.length; i ++ ) {
     element.setAttribute( attributeArray[i], valuesArray[i]);
   }
}

// References:
//   http://krasimirtsonev.com/blog/article/object-oriented-programming-oop-in-javascript-extending-Inheritance-classes
//   http://peter.michaux.ca/articles/class-based-inheritance-in-javascript
PPUtils.extend = function (subclass, superclass) {
    function Dummy() {}
    Dummy.prototype = superclass.prototype;
    subclass.prototype = new Dummy();
    subclass.prototype.constructor = subclass;
    subclass.superclass = superclass;
    subclass.superproto = superclass.prototype;
    subclass.prototype.superclass = superclass.constructor;
}

// Returns the callback so that it can be removed later
PPUtils.bindTextField = function(event, element, boundObj, objCallback) {

  var callback = function receive(evt) {
    boundObj[objCallback](element, evt);
  }

  if ( typeof element.addEventListener != "undefined" ) {
    element.addEventListener(event, callback, false);
  } else if ( typeof element.attachEvent != "undefined" ) { // Supports IE < 9
    element.attachEvent(event, callback);
  }

  return callback;
}
PPUtils.bind = function(event, element, callback) {
  if ( typeof element.addEventListener != "undefined" ) {
    element.addEventListener(event, callback, false);
  } else if ( typeof element.attachEvent != "undefined" ) { // Supports IE < 9
    element.attachEvent(event, callback);
  }
}

PPUtils.isPowerOf2 = function(x) {
  return x == 1 || x == 2 || x == 4 || x == 8 || x == 16 || x == 32 ||
     x == 64 || x == 128 || x == 256 || x == 512 || x == 1024 ||
                x == 2048 || x == 4096 || x == 8192 || x == 16384 ||
                x == 32768 || x == 65536 || x == 131072 || x == 262144 ||
                x == 524288 || x == 1048576 || x == 2097152 ||
                x == 4194304 || x == 8388608 || x == 16777216 ||
                x == 33554432 || x == 67108864 || x == 134217728 ||
                x == 268435456 || x == 536870912 || x == 1073741824 ||
                x == 2147483648;
}

PPUtils.notifyListeners = function (listenersArray, listenerMethod,value ) {
  for (var i = 0 ; i < listenersArray.length; i++) {
    var obj = listenersArray[i];
    obj[listenerMethod](value);
  }
}
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');

module.exports = function(Model){
    //TODO: may be a better way to get property name
    var modelName = Model.modelName.toLowerCase();

    var load = function(id, callback){
        Model.findOne({
            _id: id
        }).exec(callback);
    };

    var ascertainUserPermissions = function(user, doc){
        var canDo = [];
        // console.log('checking permissions');
        if(user.permissions){
            // console.log('user has permissions');
            user.permissions.forEach(function(permission){
                // console.log('permission', permission);

                if(!permission.documentType){
                    // console.log('malformed permission: did not specify documentType');
                    return;
                }
                if(permission.documentType.toLowerCase() != modelName){
                    // console.log('permission documentType !=', modelName);
                    return;
                }

                var documentId = permission.documentId;
                if(documentId){
                    if(!documentId.equals(doc.id)) {
                        // console.log('documentId !=', doc.id);
                        return;
                    }
                }
                // console.log('adding permissions', permission.canDo);
                canDo = canDo.concat(permission.canDo);
            });
        }
        // console.log('returning permissions', _.uniq(canDo));
        return _.uniq(canDo);
    };

    var ascertainBasicPermissions = function(doc){
        var canDo = [];
        if(doc.published){
            canDo.push('read');
        }
        return canDo;
    };

    var ascertainPermissions = function(user, doc){
        var permissions = ascertainBasicPermissions(doc);
        if(user){
            permissions = _.uniq(permissions.concat(ascertainUserPermissions(user, doc)));
        }
        return permissions;
    };

    return {
        /**
         * Find doc by id
         */
        get: function(req, res, next, id) {
            console.log('doc by id', id);

            var callback = function(err, doc) {
                if (err) {return next(err);}
                if (!doc) {return next(new Error('Failed to load doc ' + id));}
                var permissions = ascertainPermissions(req.user, doc);
                if(!_.contains(permissions, Model.readPermission())){
                    return res.send(403, 'User does not have read access to this content');
                }

                //ex req.post = post
                req[modelName] = doc;
                // console.log('req modelName', modelName);
                next();
            };

            if(!_.isUndefined(Model.load)){
                Model.load(id, callback);
            }
            else{
                load(id, callback);
            }
        },

        /*
        * Find doc by query object
        */
        getByQuery: function(req, res, next, query){
            console.log('getByField query', query);

            Model.findOne(query).exec(function(err, doc){
                if(err){ return next(err);}
                if (!doc) {return next(new Error('Failed to load doc by query' + query));}

                var user = req.user;
                var permissions = ascertainPermissions(user, doc);

                // console.log('doc permissions', permissions);
                if(!_.contains(permissions, Model.readPermission())){
                    return res.send(403, 'User does not have read access to this content');
                }

                doc.permissions = permissions;
                req[modelName] = doc;

                next();
            });
        },

        /**
         * Create a doc
         */
        create: function(req, res) {
            var doc = new Model(req.body);
            var user = req.user;

            if(!_.isUndefined(req.user)){
                doc.createdBy = user._id;
            }

            var permissions = ascertainPermissions(req.user, doc);
            if(!_.contains(permissions, Model.createPermission())){
                return res.send(403, 'User does not have read access to this content');
            }

            doc.save(function(err) {
                if (err) {
                    var data = {errors: err.errors};
                    data[modelName] = doc;
                    return new Error('Failed to create doc. Error: ' + err);
                } else {
                    if(user){
                        user.permissions.push({
                            documentType: modelName,
                            documentId: doc.id,
                            canDo: [
                                Model.readPermission(),
                                Model.updatePermission()
                            ]
                        });

                        user.save(function (err) {
                          if (err) return new Error('Failed to update user permissions. Error: ' + err);
                          console.log('added permissions to user for doc', doc.id);
                        });
                    }

                    res.jsonp(doc);
                }
            });
        },

        /**
         * Update a doc
         */
        update: function(req, res) {
            var doc = req[modelName];
            var user = req.user;
            var permissions = ascertainPermissions(req.user, doc);

            if(!_.contains(permissions, Model.updatePermission())){
                return res.send(403, 'User does not have read access to this content');
            }

            //prevent user from updating fields to which they dont have access
            //ex prevent user from updating his/her own permissions
            for(var field in req.body) {
                if (field == '_id' || field == '__v'){
                    //can't manually update id or version
                    delete req.body[field];
                    continue;
                }
                if(req.params[field] != doc[field]){
                    console.log('DIRTY FIELD', field);

                    var requiredPermission = Model.fieldPermissions()[field];

                    if(!_.contains(permissions, requiredPermission)){
                        console.log('DONT HAVE permission', requiredPermission, 'to update', field);
                        delete req.body[field];
                    }
                    else{
                        console.log('updating field', field);
                        // doc[field] = req.params[field];
                    }
                }
            }

            doc.edit = new Date();
            doc.editedBy = user.id;
            doc = _.extend(doc, req.body);
            doc.save(function(err) {
                if (err) {
                    var data = {errors: err.errors};
                    data[modelName] = doc;
                    return new Error('Failed to update doc. Error: ' + err);
                } else {
                    res.jsonp(doc);
                }
            });
        },

        /**
         * Delete an doc
         */
        destroy: function(req, res) {
            var doc = req[modelName];
            var permissions = ascertainPermissions(req.user, doc);
            if(!_.contains(permissions, Model.deletePermission())){
                return res.send(403, 'User does not have delete access to this content');
            }

            doc.remove(function(err) {
                if (err) {
                    var data = {errors: err.errors};
                    data[modelName] = doc;
                    return new Error('Failed to destroy doc. Error: ' + err);
                } else {
                    res.jsonp(doc);
                }
            });
        },

        /**
         * Show a doc
         */
        show: function(req, res) {
            var doc = req[modelName];
            console.log('showing doc', doc);
            res.jsonp(doc);
        },

        /**
         * List of docs
         */
        all: function(req, res) {
            Model.find().sort('-created').populate('user', 'name username').exec(function(err, docs) {
                if (err) {
                    res.render('error', {
                        status: 500
                    });
                } else {

                    // TODO: determine permissions for list access
                    // var permissions = ascertainPermissions(req.user, doc);
                    // if(!_.contains(permissions, Model.readPermission())){
                        // return res.send(403, 'User does not have read access to this content');
                    // }

                    res.jsonp(docs);
                }
            });
        },

        /**
        * Publish a doc
        */
        publish: function(req, res){
            console.log('attempting to publish', modelName, req[modelName]);

            var user = req.user;
            var doc = req[modelName];
            var permissions = ascertainPermissions(user, doc);
            if(!_.contains(permissions, Model.publishPermission())){
                return res.send(403, 'User does not have permission to publish this content');
            }

            doc.published = new Date();
            doc.save(function(err) {
                if (err) {
                    var data = {errors: err.errors};
                    data[modelName] = doc;
                    return new Error('Failed to update doc. Error: ' + err);
                } else {
                    res.jsonp(doc);
                }
            });
        },
    };
};
<commit_msg>Added method to remove fields for which the user does not have read access before sending response. Said method is used in baseController.show<commit_after>'use strict';

var _ = require('lodash');

module.exports = function(Model){
    //TODO: may be a better way to get property name
    var modelName = Model.modelName.toLowerCase();

    var load = function(id, callback){
        Model.findOne({
            _id: id
        }).exec(callback);
    };

    var ascertainUserPermissions = function(user, doc){
        var canDo = [];
        // console.log('checking permissions');
        if(user.permissions){
            // console.log('user has permissions');
            user.permissions.forEach(function(permission){
                // console.log('permission', permission);

                if(!permission.documentType){
                    // console.log('malformed permission: did not specify documentType');
                    return;
                }
                if(permission.documentType.toLowerCase() != modelName){
                    // console.log('permission documentType !=', modelName);
                    return;
                }

                var documentId = permission.documentId;
                if(documentId){
                    if(!documentId.equals(doc.id)) {
                        // console.log('documentId !=', doc.id);
                        return;
                    }
                }
                // console.log('adding permissions', permission.canDo);
                canDo = canDo.concat(permission.canDo);
            });
        }
        // console.log('returning permissions', _.uniq(canDo));
        return _.uniq(canDo);
    };

    var ascertainBasicPermissions = function(doc){
        var canDo = [];
        if(doc.published){
            canDo.push('read');
        }
        return canDo;
    };

    var ascertainPermissions = function(user, doc){
        var permissions = ascertainBasicPermissions(doc);
        if(user){
            permissions = _.uniq(permissions.concat(ascertainUserPermissions(user, doc)));
        }
        return permissions;
    };

    var removeNonPermitedFields = function(permissions, doc){
        var modelFieldPermissions =  Model.fieldPermissions();
        var readPermission = Model.readPermission();

        for (var field in Model.schema.paths) {
            if (field == '_id' || field == '__v'){
                continue;
            }

            var requiredPermission = modelFieldPermissions[field][readPermission];
            if(!_.contains(permissions, requiredPermission)){
                console.log('dont have', requiredPermission, 'for field', field);
                delete doc[field];
                // doc[field] = null;

            }
        };

        return doc;
    };

    return {
        /**
         * Find doc by id
         */
        get: function(req, res, next, id) {
            console.log('doc by id', id);

            var callback = function(err, doc) {
                if (err) {return next(err);}
                if (!doc) {return next(new Error('Failed to load doc ' + id));}
                var permissions = ascertainPermissions(req.user, doc);
                if(!_.contains(permissions, Model.readPermission())){
                    return res.send(403, 'User does not have read access to this content');
                }

                //ex req.post = post
                req[modelName] = doc;
                // console.log('req modelName', modelName);
                next();
            };

            if(!_.isUndefined(Model.load)){
                Model.load(id, callback);
            }
            else{
                load(id, callback);
            }
        },

        /*
        * Find doc by query object
        */
        getByQuery: function(req, res, next, query){
            console.log('getByField query', query);

            Model.findOne(query).exec(function(err, doc){
                if(err){ return next(err);}
                if (!doc) {return next(new Error('Failed to load doc by query' + query));}

                var user = req.user;
                var permissions = ascertainPermissions(user, doc);

                // console.log('doc permissions', permissions);
                if(!_.contains(permissions, Model.readPermission())){
                    return res.send(403, 'User does not have read access to this content');
                }

                doc.permissions = permissions;
                req[modelName] = doc;

                next();
            });
        },

        /**
         * Create a doc
         */
        create: function(req, res) {
            var doc = new Model(req.body);
            var user = req.user;

            if(!_.isUndefined(req.user)){
                doc.createdBy = user._id;
            }

            var permissions = ascertainPermissions(req.user, doc);
            if(!_.contains(permissions, Model.createPermission())){
                return res.send(403, 'User does not have read access to this content');
            }

            doc.save(function(err) {
                if (err) {
                    var data = {errors: err.errors};
                    data[modelName] = doc;
                    return new Error('Failed to create doc. Error: ' + err);
                } else {
                    if(user){
                        user.permissions.push({
                            documentType: modelName,
                            documentId: doc.id,
                            canDo: [
                                Model.readPermission(),
                                Model.updatePermission()
                            ]
                        });

                        user.save(function (err) {
                          if (err) return new Error('Failed to update user permissions. Error: ' + err);
                          console.log('added permissions to user for doc', doc.id);
                        });
                    }

                    res.jsonp(doc);
                }
            });
        },

        /**
         * Update a doc
         */
        update: function(req, res) {
            var doc = req[modelName];
            var user = req.user;
            var permissions = ascertainPermissions(req.user, doc);

            if(!_.contains(permissions, Model.updatePermission())){
                return res.send(403, 'User does not have read access to this content');
            }

            //prevent user from updating fields to which they dont have access
            //ex prevent user from updating his/her own permissions
            for(var field in req.body) {
                if (field == '_id' || field == '__v'){
                    //can't manually update id or version
                    delete req.body[field];
                    continue;
                }
                if(req.params[field] != doc[field]){
                    console.log('DIRTY FIELD', field);

                    var requiredPermission = Model.fieldPermissions()[field];

                    if(!_.contains(permissions, requiredPermission)){
                        console.log('DONT HAVE permission', requiredPermission, 'to update', field);
                        delete req.body[field];
                    }
                    else{
                        console.log('updating field', field);
                        // doc[field] = req.params[field];
                    }
                }
            }

            doc.edit = new Date();
            doc.editedBy = user.id;
            doc = _.extend(doc, req.body);
            doc.save(function(err) {
                if (err) {
                    var data = {errors: err.errors};
                    data[modelName] = doc;
                    return new Error('Failed to update doc. Error: ' + err);
                } else {
                    res.jsonp(doc);
                }
            });
        },

        /**
         * Delete an doc
         */
        destroy: function(req, res) {
            var doc = req[modelName];
            var permissions = ascertainPermissions(req.user, doc);
            if(!_.contains(permissions, Model.deletePermission())){
                return res.send(403, 'User does not have delete access to this content');
            }

            doc.remove(function(err) {
                if (err) {
                    var data = {errors: err.errors};
                    data[modelName] = doc;
                    return new Error('Failed to destroy doc. Error: ' + err);
                } else {
                    res.jsonp(doc);
                }
            });
        },

        /**
         * Show a doc
         */
        show: function(req, res) {
            var doc = req[modelName];
            console.log('showing doc', doc);

            var permissions = ascertainPermissions(req.user, doc);

            //returning a POJO instead of mongoose model instance
            var _doc = doc.toObject();

            //remove all field for which the user does not have read access
             _doc = removeNonPermitedFields(permissions, _doc);

            res.jsonp(_doc);
        },

        /**
         * List of docs
         */
        all: function(req, res) {
            Model.find().sort('-created').populate('user', 'name username').exec(function(err, docs) {
                if (err) {
                    res.render('error', {
                        status: 500
                    });
                } else {

                    // TODO: determine permissions for list access
                    // var permissions = ascertainPermissions(req.user, doc);
                    // if(!_.contains(permissions, Model.readPermission())){
                        // return res.send(403, 'User does not have read access to this content');
                    // }

                    res.jsonp(docs);
                }
            });
        },

        /**
        * Publish a doc
        */
        publish: function(req, res){
            console.log('attempting to publish', modelName, req[modelName]);

            var user = req.user;
            var doc = req[modelName];
            var permissions = ascertainPermissions(user, doc);
            if(!_.contains(permissions, Model.publishPermission())){
                return res.send(403, 'User does not have permission to publish this content');
            }

            doc.published = new Date();
            doc.save(function(err) {
                if (err) {
                    var data = {errors: err.errors};
                    data[modelName] = doc;
                    return new Error('Failed to update doc. Error: ' + err);
                } else {
                    res.jsonp(doc);
                }
            });
        },
    };
};
<|endoftext|>


<commit_before>/*
 * @class Oskari.mapframework.bundle.mapanalysis.domain.AnalysisLayerModelBuilder
 * JSON-parsing for analysis layer
 */
Oskari.clazz.define('Oskari.mapframework.bundle.mapanalysis.domain.AnalysisLayerModelBuilder', function(sandbox) {
	this.localization = Oskari.getLocalization("MapAnalysis");
    this.sandbox = sandbox;
}, {
	/**
	 * parses any additional fields to model
	 * @param {Oskari.mapframework.bundle.mapanalysis.domain.AnalysisLayer} layer partially populated layer
	 * @param {Object} mapLayerJson JSON presentation of the layer
	 * @param {Oskari.mapframework.service.MapLayerService} maplayerService not really needed here
	 */
	parseLayerData : function(layer, mapLayerJson, maplayerService) {

        var me = this;

	}
});
<commit_msg>statsgrid included to ajaxurl-parameters for guest<commit_after>/*
 * @class Oskari.mapframework.bundle.mapanalysis.domain.AnalysisLayerModelBuilder
 * JSON-parsing for analysis layer
 */
Oskari.clazz.define('Oskari.mapframework.bundle.mapanalysis.domain.AnalysisLayerModelBuilder', function(sandbox) {
	this.localization = Oskari.getLocalization("MapAnalysis");
    this.sandbox = sandbox;
}, {
	/**
	 * parses any additional fields to model
	 * @param {Oskari.mapframework.bundle.mapanalysis.domain.AnalysisLayer} layer partially populated layer
	 * @param {Object} mapLayerJson JSON presentation of the layer
	 * @param {Oskari.mapframework.service.MapLayerService} maplayerService not really needed here
	 */
	parseLayerData : function(layer, mapLayerJson, maplayerService) {

        var me = this;
debugger;
	}
});
<|endoftext|>


<commit_before>
// function getPageName(url) {
//     var index = url.lastIndexOf("/") + 1;
//     var filenameWithExtension = url.substr(index);
//     var filename = filenameWithExtension.split(".")[0];
//     return filename;
// }

//   $(function(){
//      var currentPageName = getPageName(window.location.pathname);
//      $('#' + currentPageName).css('color', '#EDD0AF');
//      $('#' + currentPageName).parent().css('background-color', '#635A8E')
//   });

// $(document).ready(function() {
// 	$('.nav-highlight').hover(function(event) {
// 		link = event.target
// 		$(link).css('color', 'green');
// 	})
// 	$('.top-bar ul li').hover(function(event) {
// 		link = event.target
// 		if ($(link).hasClass('nav-highlight') ) {
// 		// debugger;
// 			$(link).children().css('color', "green");
// 			$(link).on('mouseout', function(event) {
// 				debugger;
// 			})
// 		} else {
// 			$(link).css('color', '#EDD0AF');
// 		}
// 	})
// });

  	// selected_div = event.target.closest('.face')
  	// $(selected_div).children('.vibe-name').toggleClass('show-vibe');<commit_msg>delete unused file<commit_after><|endoftext|>


<commit_before>import axios from 'axios';

import '../config';
import db from '../utils/db';

import Rss from '../models/rss';
import Article from '../models/article';

async function tryHackernewsAPI(path, retries=5) {
	const url = 'https://hacker-news.firebaseio.com/v0' + path;
	while (retries) {
		try {
			return await axios.get(url);
		} catch (_) {
			--retries;
		}
	}
	throw new Error(`Failed to perform call to '${path}'`);
}

async function hackernewsData(postID) {
	const response = await tryHackernewsAPI(`/item/${postID}.json`);
	return response.data;
}

async function hackernewsTop() {
	const response = await tryHackernewsAPI('/topstories.json');
	return response.data;
}

function commentUrl(postID) {
    return `https://news.ycombinator.com/item?id=${postID}`;
}

async function main() {
    await db;

    const ids = await hackernewsTop();
    const posts = await Promise.all(ids.map(hackernewsData));
    const urlToScore = posts.reduce((map, post) => map.set(post.url, post.score), new Map());
    const commentUrlToScore = posts.reduce((map, post) => map.set(commentUrl(post.id), post.score), new Map());
    const [urlMatch, commentUrlMatch] = await Promise.all([
        Article.find({ url: { $in: [...urlToScore.keys()] } }),
        Article.find({ commentUrl: { $in: [...commentUrlToScore.keys()] } }),
    ]);
    const batch = Article.collection.initializeUnorderedBulkOp();
    for (const match of urlMatch) {
        batch.find({ _id: match._id }).updateOne({$set: { 'socialScore.hackernews': urlToScore.get(match.url) }});
    }
    for (const match of commentUrlMatch) {
        batch.find({ _id: match._id }).updateOne({$set: { 'socialScore.hackernews': commentUrlToScore.get(match.commentUrl) }});
    }
    await batch.execute();
}

main().then(() => {
	console.info('done');
	process.exit(0);
}).catch(err => {
	console.info(`failed with err ${err.stack}`);
	process.exit(1);
});

<commit_msg>Prettify cron hackernews script<commit_after>import axios from 'axios';

import '../config';
import db from '../utils/db';

import Rss from '../models/rss';
import Article from '../models/article';

async function tryHackernewsAPI(path, retries = 5) {
	const url = 'https://hacker-news.firebaseio.com/v0' + path;
	while (retries) {
		try {
			return await axios.get(url);
		} catch (_) {
			--retries;
		}
	}
	throw new Error(`Failed to perform call to '${path}'`);
}

async function hackernewsData(postID) {
	const response = await tryHackernewsAPI(`/item/${postID}.json`);
	return response.data;
}

async function hackernewsTop() {
	const response = await tryHackernewsAPI('/topstories.json');
	return response.data;
}

function commentUrl(postID) {
	return `https://news.ycombinator.com/item?id=${postID}`;
}

async function main() {
	await db;

	const ids = await hackernewsTop();
	const posts = await Promise.all(ids.map(hackernewsData));
	const urlToScore = posts.reduce(
		(map, post) => map.set(post.url, post.score),
		new Map(),
	);
	const commentUrlToScore = posts.reduce(
		(map, post) => map.set(commentUrl(post.id), post.score),
		new Map(),
	);
	const [urlMatch, commentUrlMatch] = await Promise.all([
		Article.find({ url: { $in: [...urlToScore.keys()] } }),
		Article.find({ commentUrl: { $in: [...commentUrlToScore.keys()] } }),
	]);
	const batch = Article.collection.initializeUnorderedBulkOp();
	for (const match of urlMatch) {
		batch
			.find({ _id: match._id })
			.updateOne({ $set: { 'socialScore.hackernews': urlToScore.get(match.url) } });
	}
	for (const match of commentUrlMatch) {
		batch
			.find({ _id: match._id })
			.updateOne({
				$set: {
					'socialScore.hackernews': commentUrlToScore.get(match.commentUrl),
				},
			});
	}
	await batch.execute();
}

main()
	.then(() => {
		console.info('done');
		process.exit(0);
	})
	.catch(err => {
		console.info(`failed with err ${err.stack}`);
		process.exit(1);
	});
<|endoftext|>


<commit_before>/**
 * @license Copyright (c) CKSource - Frederico Knabben. All rights reserved.
 * For licensing, see LICENSE.html or http://ckeditor.com/license
 */

(function() {
    if (!supportsLocalStorage()) {
        CKEDITOR.plugins.add("autosave", {}); //register a dummy plugin to pass CKEditor plugin initialization process
        return;
    }

    CKEDITOR.plugins.add("autosave", {
        lang: 'ca,cs,de,en,es,fr,it,ja,nl,pl,pt-br,ru,sk,sv,zh,zh-cn', // %REMOVE_LINE_CORE%
        requires: 'notification',
        version: "0.18.0",
        init: function (editor) {
            // Default Config
            var defaultConfig = {
                delay: 10,
                messageType: "notification",
                saveDetectionSelectors: "a[href^='javascript:__doPostBack'][id*='Save'],a[id*='Cancel']",
                saveOnDestroy: false,
                NotOlderThen: 1440,
                SaveKey: 'autosave_' + window.location + "_" + $('#' + editor.name).attr('name'),
                diffType: "sideBySide",
                autoLoad: false
            };

            // Get Config & Lang
            var config = CKEDITOR.tools.extend(defaultConfig, editor.config.autosave || {}, true);

            if (editor.plugins.textselection && config.messageType == "statusbar") {
                config.messageType = "notification";
            }

            CKEDITOR.document.appendStyleSheet(CKEDITOR.getUrl(CKEDITOR.plugins.getPath('autosave') + 'css/autosave.min.css'));

            editor.on('uiSpace', function(event) {
                if (event.data.space == 'bottom' && config.messageType != null && config.messageType == "statusbar") {

                    event.data.html += '

'
                        + event.editor.lang.autosave.autoSaveMessage
                        + '

';
                }
            }, editor, null, 100);

            editor.on('instanceReady', function(){
                if (typeof (jQuery) === 'undefined') {
                    CKEDITOR.scriptLoader.load('//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js', function() {
                        jQuery.noConflict();

                        loadPlugin(editor, config);
                    });

                } else {
                    CKEDITOR.scriptLoader.load(CKEDITOR.getUrl(CKEDITOR.plugins.getPath('autosave') + 'js/extensions.min.js'), function() {
                        loadPlugin(editor, config);
                    });
                }
            }, editor, null, 100);
        }
    });

    function loadPlugin(editorInstance, config) {
        var autoSaveKey = config.SaveKey != null ? config.SaveKey : 'autosave_' + window.location + "_" + $('#' + editorInstance.name).attr('name');
        var notOlderThen = config.NotOlderThen != null ? config.NotOlderThen : 1440;
        var saveOnDestroy = config.saveOnDestroy != null ? config.saveOnDestroy : false;
        var saveDetectionSelectors =
            config.saveDetectionSelectors != null ? config.saveDetectionSelectors : "a[href^='javascript:__doPostBack'][id*='Save'],a[id*='Cancel']";

        CKEDITOR.scriptLoader.load(CKEDITOR.getUrl(CKEDITOR.plugins.getPath('autosave') + 'js/extensions.min.js'), function() {
            GenerateAutoSaveDialog(editorInstance, config, autoSaveKey);

            CheckForAutoSavedContent(editorInstance, config, autoSaveKey, notOlderThen);
        });

        jQuery(saveDetectionSelectors).click(function() {
            RemoveStorage(autoSaveKey, editorInstance);
        });

        editorInstance.on('change', function() {
            startTimer(config, editorInstance);
        });

        editorInstance.on('destroy', function() {
            if (saveOnDestroy) {
                SaveData(autoSaveKey, editorInstance, config);
            }
        });
    }

    function autoSaveMessageId(editorInstance) {
        return 'cke_autoSaveMessage_' + editorInstance.name;
    }

    var startTimer = function (configAutosave, editorInstance) {
        if (editorInstance.config.autosave_timeOutId == null) {
            var delay = configAutosave.delay != null ? configAutosave.delay : 10;
            editorInstance.config.autosave_timeOutId = setTimeout(function() {
                    onTimer(configAutosave, editorInstance);
                },
                delay * 1000);
        }
    };
    function onTimer (configAutosave, editorInstance) {
        if (editorInstance.checkDirty() || editorInstance.plugins.bbcode) {
            var editor = editorInstance,
                autoSaveKey = configAutosave.SaveKey != null
                    ? configAutosave.SaveKey
                    : 'autosave_' + window.location + "_" + $('#' + editor.name).attr('name');

            SaveData(autoSaveKey, editor, configAutosave);

            clearTimeout(editorInstance.config.autosave_timeOutId);

            editorInstance.config.autosave_timeOutId = null;
        }
    };

    // localStorage detection
    function supportsLocalStorage() {
        if (typeof (Storage) === 'undefined') {
            return false;
        }

        try {
            localStorage.getItem("___test_key");
            return true;
        } catch (e) {
            return false;
        }
    }

    function GenerateAutoSaveDialog(editorInstance, config, autoSaveKey) {
        CKEDITOR.dialog.add('autosaveDialog', function() {
            return {
                title: editorInstance.lang.autosave.title,
                minHeight: 155,
                height: 300,
                width: 800,
                onShow: function() {
                    RenderDiff(this, editorInstance, autoSaveKey);
                },
                onOk: function() {
                    if (localStorage.getItem(autoSaveKey)) {
                        var jsonSavedContent = LoadData(autoSaveKey);
                        editorInstance.setData(jsonSavedContent.data);

                        RemoveStorage(autoSaveKey, editorInstance);
                    }
                },
                onCancel: function() {
                    RemoveStorage(autoSaveKey, editorInstance);
                },
                contents: [
                    {
                        label: '',
                        id: 'general',
                        elements: [
                            {
                                type: 'radio',
                                id: 'diffType',
                                label: editorInstance.lang.autosave.diffType,
                                items: [[editorInstance.lang.autosave.sideBySide, 'sideBySide'], [editorInstance.lang.autosave.inline, 'inline']],
                                'default': config.diffType,
                                onClick: function() {
                                    RenderDiff(this._.dialog, editorInstance, autoSaveKey);
                                }
                            }, {
                                type: 'html',
                                id: 'diffContent',
                                html: ''
                            }
                        ]
                    }
                ],
                buttons: [
                    {
                        id: 'ok',
                        type: 'button',
                        label: editorInstance.lang.autosave.ok,
                        'class': 'cke_dialog_ui_button_ok cke_dialog_autosave_ok',
                        onClick: function(evt) {
                            var dialog = evt.data.dialog;
                            if (dialog.fire('ok', { hide: true }).hide !== false)
                                dialog.hide();
                        }
                    },
                    {
                        id: 'cancel',
                        type: 'button',
                        label: editorInstance.lang.autosave.no,
                        'class': 'cke_dialog_ui_button_cancel',
                        onClick: function(evt) {
                            var dialog = evt.data.dialog;
                            if (dialog.fire('cancel', { hide: true }).hide !== false)
                                dialog.hide();
                        }
                    }
                ]
            };
        });
    }

    function CheckForAutoSavedContent(editorInstance, config, autoSaveKey, notOlderThen) {
        // Checks If there is data available and load it
        if (localStorage.getItem(autoSaveKey)) {
            var jsonSavedContent = LoadData(autoSaveKey);

            var autoSavedContent = jsonSavedContent.data;
            var autoSavedContentDate = jsonSavedContent.saveTime;

            var editorLoadedContent = editorInstance.getData();

            // check if the loaded editor content is the same as the autosaved content
            if (editorLoadedContent == autoSavedContent) {
                localStorage.removeItem(autoSaveKey);
                return;
            }

            // Ignore if autosaved content is older then x minutes
            if (moment(new Date()).diff(new Date(autoSavedContentDate), 'minutes') > notOlderThen) {
                RemoveStorage(autoSaveKey, editorInstance);

                return;
            }

            if (config.autoLoad) {
                if (localStorage.getItem(autoSaveKey)) {
                    var jsonSavedContent = LoadData(autoSaveKey);
                    editorInstance.setData(jsonSavedContent.data);

                    RemoveStorage(autoSaveKey, editorInstance);
                }
            } else {
                var confirmMessage = editorInstance.lang.autosave.loadSavedContent.replace("{0}",
                    moment(autoSavedContentDate).locale(editorInstance.config.language)
                    .format(editorInstance.lang.autosave.dateFormat));

                if (confirm(confirmMessage)) {
                    // Open DIFF Dialog
                    editorInstance.openDialog('autosaveDialog');
                } else {
                    RemoveStorage(autoSaveKey, editorInstance);
                }
            }
        }
    }

    function LoadData(autoSaveKey) {
        var compressedJSON = LZString.decompressFromUTF16(localStorage.getItem(autoSaveKey));
        return JSON.parse(compressedJSON);
    }

    function SaveData(autoSaveKey, editorInstance, config) {
        var compressedJSON = LZString.compressToUTF16(JSON.stringify({ data: editorInstance.getData(), saveTime: new Date() }));

        var quotaExceeded = false;

        try {
            localStorage.setItem(autoSaveKey, compressedJSON);
        } catch (e) {
            quotaExceeded = isQuotaExceeded(e);
            if (quotaExceeded) {
                console.log(editorInstance.lang.autosave.localStorageFull);
            }
        }

        if (quotaExceeded) {
            var notificationError = new CKEDITOR.plugins.notification(editorInstance, { message: editorInstance.lang.autosave.localStorageFull, type: 'warning' });
            notificationError.show();
        } else {
            var messageType = config.messageType != null ? config.messageType : "notification";

            if (editorInstance.plugins.textselection && messageType == "statusbar") {
                messageType = "notification";
            }

            if (messageType == "statusbar") {
                var autoSaveMessage = document.getElementById(autoSaveMessageId(editorInstance));

                if (autoSaveMessage) {
                    autoSaveMessage.className = "show";

                    setTimeout(function () {
                        autoSaveMessage.className = "hidden";
                    }, 2000);
                }
            } else if (messageType == "notification") {
                var notification = new CKEDITOR.plugins.notification(editorInstance, { message: editorInstance.lang.autosave.autoSaveMessage, type: 'success' });
                notification.show();
            }
        }
    }

    function RemoveStorage(autoSaveKey, editor) {
        if (editor.config.autosave_timeOutId) {
            clearTimeout(editor.config.autosave_timeOutId);
        }

        localStorage.removeItem(autoSaveKey);
    }

    function RenderDiff(dialog, editorInstance, autoSaveKey) {
        var jsonSavedContent = LoadData(autoSaveKey);

        var base = difflib.stringAsLines(editorInstance.getData());
        var newtxt = difflib.stringAsLines(jsonSavedContent.data);
        var sm = new difflib.SequenceMatcher(base, newtxt);
        var opcodes = sm.get_opcodes();

        dialog.getContentElement('general', 'diffContent').getElement().setHtml('
' + diffview.buildView({
            baseTextLines: base,
            newTextLines: newtxt,
            opcodes: opcodes,
            baseTextName: editorInstance.lang.autosave.loadedContent,
            newTextName: editorInstance.lang.autosave.autoSavedContent + (moment(jsonSavedContent.saveTime).locale(editorInstance.config.language).format(editorInstance.lang.autosave.dateFormat)) + '\'',
            contextSize: 3,
            viewType: dialog.getContentElement('general', 'diffType').getValue() == "inline" ? 1 : 0
        }).outerHTML + '
');
    }

    function isQuotaExceeded(e) {
        var quotaExceeded = false;
        if (e) {
            if (e.code) {
                switch (e.code) {
                    case 22:
                        quotaExceeded = true;
                        break;
                    case 1014:
                        // Firefox
                        if (e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
                            quotaExceeded = true;
                        }
                        break;
                }
            } else if (e.number === -2147024882) {
                // Internet Explorer 8
                quotaExceeded = true;
            }
        }
        return quotaExceeded;
    }
})();
<commit_msg>Func for mitigating querystrings<commit_after>/**
 * @license Copyright (c) CKSource - Frederico Knabben. All rights reserved.
 * For licensing, see LICENSE.html or http://ckeditor.com/license
 */

(function() {
    if (!supportsLocalStorage()) {
        CKEDITOR.plugins.add("autosave", {}); //register a dummy plugin to pass CKEditor plugin initialization process
        return;
    }

    CKEDITOR.plugins.add("autosave", {
        lang: 'ca,cs,de,en,es,fr,it,ja,nl,pl,pt-br,ru,sk,sv,zh,zh-cn', // %REMOVE_LINE_CORE%
        requires: 'notification',
        version: "0.18.0",
        init: function (editor) {
            // Default Config
            var defaultConfig = {
                delay: 10,
                messageType: "notification",
                saveDetectionSelectors: "a[href^='javascript:__doPostBack'][id*='Save'],a[id*='Cancel']",
                saveOnDestroy: false,
                NotOlderThen: 1440,
                SaveKey: 'autosave_' + window.location + "_" + $('#' + editor.name).attr('name'),
                diffType: "sideBySide",
                autoLoad: false
            };

            // Get Config & Lang
            var config = CKEDITOR.tools.extend(defaultConfig, editor.config.autosave || {}, true);

            if (editor.plugins.textselection && config.messageType == "statusbar") {
                config.messageType = "notification";
            }

            CKEDITOR.document.appendStyleSheet(CKEDITOR.getUrl(CKEDITOR.plugins.getPath('autosave') + 'css/autosave.min.css'));

            editor.on('uiSpace', function(event) {
                if (event.data.space == 'bottom' && config.messageType != null && config.messageType == "statusbar") {

                    event.data.html += '

'
                        + event.editor.lang.autosave.autoSaveMessage
                        + '

';
                }
            }, editor, null, 100);

            editor.on('instanceReady', function(){
                if (typeof (jQuery) === 'undefined') {
                    CKEDITOR.scriptLoader.load('//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js', function() {
                        jQuery.noConflict();

                        loadPlugin(editor, config);
                    });

                } else {
                    CKEDITOR.scriptLoader.load(CKEDITOR.getUrl(CKEDITOR.plugins.getPath('autosave') + 'js/extensions.min.js'), function() {
                        loadPlugin(editor, config);
                    });
                }
            }, editor, null, 100);
        }
    });

    function loadPlugin(editorInstance, config) {
        var autoSaveKey = config.SaveKey != null ? config.SaveKey : 'autosave_' + window.location + "_" + $('#' + editorInstance.name).attr('name');
        var notOlderThen = config.NotOlderThen != null ? config.NotOlderThen : 1440;
        var saveOnDestroy = config.saveOnDestroy != null ? config.saveOnDestroy : false;
        var saveDetectionSelectors =
            config.saveDetectionSelectors != null ? config.saveDetectionSelectors : "a[href^='javascript:__doPostBack'][id*='Save'],a[id*='Cancel']";

        CKEDITOR.scriptLoader.load(CKEDITOR.getUrl(CKEDITOR.plugins.getPath('autosave') + 'js/extensions.min.js'), function() {
            GenerateAutoSaveDialog(editorInstance, config, autoSaveKey);

            CheckForAutoSavedContent(editorInstance, config, autoSaveKey, notOlderThen);
        });

        jQuery(saveDetectionSelectors).click(function() {
            RemoveStorage(autoSaveKey, editorInstance);
        });

        editorInstance.on('change', function() {
            startTimer(config, editorInstance);
        });

        editorInstance.on('destroy', function() {
            if (saveOnDestroy) {
                SaveData(autoSaveKey, editorInstance, config);
            }
        });
    }

    function autoSaveMessageId(editorInstance) {
        return 'cke_autoSaveMessage_' + editorInstance.name;
    }

    var startTimer = function (configAutosave, editorInstance) {
        if (editorInstance.config.autosave_timeOutId == null) {
            var delay = configAutosave.delay != null ? configAutosave.delay : 10;
            editorInstance.config.autosave_timeOutId = setTimeout(function() {
                    onTimer(configAutosave, editorInstance);
                },
                delay * 1000);
        }
    };
    function onTimer (configAutosave, editorInstance) {
        if (editorInstance.checkDirty() || editorInstance.plugins.bbcode) {
            var editor = editorInstance,
                autoSaveKey = configAutosave.SaveKey != null
                    ? configAutosave.SaveKey
                    : 'autosave_' + window.location + "_" + $('#' + editor.name).attr('name');

            SaveData(autoSaveKey, editor, configAutosave);

            clearTimeout(editorInstance.config.autosave_timeOutId);

            editorInstance.config.autosave_timeOutId = null;
        }
    };

    // localStorage detection
    function supportsLocalStorage() {
        if (typeof (Storage) === 'undefined') {
            return false;
        }

        try {
            localStorage.getItem("___test_key");
            return true;
        } catch (e) {
            return false;
        }
    }

    function GenerateAutoSaveDialog(editorInstance, config, autoSaveKey) {
        CKEDITOR.dialog.add('autosaveDialog', function() {
            return {
                title: editorInstance.lang.autosave.title,
                minHeight: 155,
                height: 300,
                width: 800,
                onShow: function() {
                    RenderDiff(this, editorInstance, autoSaveKey);
                },
                onOk: function() {
                    if (localStorage.getItem(autoSaveKey)) {
                        var jsonSavedContent = LoadData(autoSaveKey);
                        editorInstance.setData(jsonSavedContent.data);

                        RemoveStorage(autoSaveKey, editorInstance);
                    }
                },
                onCancel: function() {
                    RemoveStorage(autoSaveKey, editorInstance);
                },
                contents: [
                    {
                        label: '',
                        id: 'general',
                        elements: [
                            {
                                type: 'radio',
                                id: 'diffType',
                                label: editorInstance.lang.autosave.diffType,
                                items: [[editorInstance.lang.autosave.sideBySide, 'sideBySide'], [editorInstance.lang.autosave.inline, 'inline']],
                                'default': config.diffType,
                                onClick: function() {
                                    RenderDiff(this._.dialog, editorInstance, autoSaveKey);
                                }
                            }, {
                                type: 'html',
                                id: 'diffContent',
                                html: ''
                            }
                        ]
                    }
                ],
                buttons: [
                    {
                        id: 'ok',
                        type: 'button',
                        label: editorInstance.lang.autosave.ok,
                        'class': 'cke_dialog_ui_button_ok cke_dialog_autosave_ok',
                        onClick: function(evt) {
                            var dialog = evt.data.dialog;
                            if (dialog.fire('ok', { hide: true }).hide !== false)
                                dialog.hide();
                        }
                    },
                    {
                        id: 'cancel',
                        type: 'button',
                        label: editorInstance.lang.autosave.no,
                        'class': 'cke_dialog_ui_button_cancel',
                        onClick: function(evt) {
                            var dialog = evt.data.dialog;
                            if (dialog.fire('cancel', { hide: true }).hide !== false)
                                dialog.hide();
                        }
                    }
                ]
            };
        });
    }

    function CheckForAutoSavedContent(editorInstance, config, autoSaveKey, notOlderThen) {
        // Checks If there is data available and load it
        if (localStorage.getItem(autoSaveKey)) {
            var jsonSavedContent = LoadData(autoSaveKey);

            var autoSavedContent = jsonSavedContent.data;
            var autoSavedContentDate = jsonSavedContent.saveTime;

            var editorLoadedContent = editorInstance.getData();

            // check if the loaded editor content is the same as the autosaved content
            if (editorLoadedContent == autoSavedContent) {
                localStorage.removeItem(autoSaveKey);
                return;
            }

            // Ignore if autosaved content is older then x minutes
            if (moment(new Date()).diff(new Date(autoSavedContentDate), 'minutes') > notOlderThen) {
                RemoveStorage(autoSaveKey, editorInstance);

                return;
            }

            if (config.autoLoad) {
                if (localStorage.getItem(autoSaveKey)) {
                    var jsonSavedContent = LoadData(autoSaveKey);
                    editorInstance.setData(jsonSavedContent.data);

                    RemoveStorage(autoSaveKey, editorInstance);
                }
            } else {
                var confirmMessage = editorInstance.lang.autosave.loadSavedContent.replace("{0}",
                    moment(autoSavedContentDate).locale(editorInstance.config.language)
                    .format(editorInstance.lang.autosave.dateFormat));

                if (confirm(confirmMessage)) {
                    // Open DIFF Dialog
                    editorInstance.openDialog('autosaveDialog');
                } else {
                    RemoveStorage(autoSaveKey, editorInstance);
                }
            }
        }
    }

    function LoadData(autoSaveKey) {
        var compressedJSON = LZString.decompressFromUTF16(localStorage.getItem(autoSaveKey));
        return JSON.parse(compressedJSON);
    }

    function SaveData(autoSaveKey, editorInstance, config) {
        var compressedJSON = LZString.compressToUTF16(JSON.stringify({ data: editorInstance.getData(), saveTime: new Date() }));

        var quotaExceeded = false;

        try {
            localStorage.setItem(autoSaveKey, compressedJSON);
        } catch (e) {
            quotaExceeded = isQuotaExceeded(e);
            if (quotaExceeded) {
                console.log(editorInstance.lang.autosave.localStorageFull);
            }
        }

        if (quotaExceeded) {
            var notificationError = new CKEDITOR.plugins.notification(editorInstance, { message: editorInstance.lang.autosave.localStorageFull, type: 'warning' });
            notificationError.show();
        } else {
            var messageType = config.messageType != null ? config.messageType : "notification";

            if (editorInstance.plugins.textselection && messageType == "statusbar") {
                messageType = "notification";
            }

            if (messageType == "statusbar") {
                var autoSaveMessage = document.getElementById(autoSaveMessageId(editorInstance));

                if (autoSaveMessage) {
                    autoSaveMessage.className = "show";

                    setTimeout(function () {
                        autoSaveMessage.className = "hidden";
                    }, 2000);
                }
            } else if (messageType == "notification") {
                var notification = new CKEDITOR.plugins.notification(editorInstance, { message: editorInstance.lang.autosave.autoSaveMessage, type: 'success' });
                notification.show();
            }
        }
    }

    function RemoveStorage(autoSaveKey, editor) {
        if (editor.config.autosave_timeOutId) {
            clearTimeout(editor.config.autosave_timeOutId);
        }

        localStorage.removeItem(autoSaveKey);
    }

    function RenderDiff(dialog, editorInstance, autoSaveKey) {
        var jsonSavedContent = LoadData(autoSaveKey);

        var base = difflib.stringAsLines(editorInstance.getData());
        var newtxt = difflib.stringAsLines(jsonSavedContent.data);
        var sm = new difflib.SequenceMatcher(base, newtxt);
        var opcodes = sm.get_opcodes();

        dialog.getContentElement('general', 'diffContent').getElement().setHtml('
' + diffview.buildView({
            baseTextLines: base,
            newTextLines: newtxt,
            opcodes: opcodes,
            baseTextName: editorInstance.lang.autosave.loadedContent,
            newTextName: editorInstance.lang.autosave.autoSavedContent + (moment(jsonSavedContent.saveTime).locale(editorInstance.config.language).format(editorInstance.lang.autosave.dateFormat)) + '\'',
            contextSize: 3,
            viewType: dialog.getContentElement('general', 'diffType').getValue() == "inline" ? 1 : 0
        }).outerHTML + '
');
    }

    function isQuotaExceeded(e) {
        var quotaExceeded = false;
        if (e) {
            if (e.code) {
                switch (e.code) {
                    case 22:
                        quotaExceeded = true;
                        break;
                    case 1014:
                        // Firefox
                        if (e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
                            quotaExceeded = true;
                        }
                        break;
                }
            } else if (e.number === -2147024882) {
                // Internet Explorer 8
                quotaExceeded = true;
            }
        }
        return quotaExceeded;
    }
    // Querystring mitigator - Quick and dirty paste.
    // I don't know who original author is for creds.
    // https://stackoverflow.com/a/11654436/2418655
    function removeUrlParam(key, value, url) {
        if (!url) url = window.location.href;
        var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"),
            hash;

        if (re.test(url)) {
            if (typeof value !== 'undefined' && value !== null) {
                return url.replace(re, '$1' + key + "=" + value + '$2$3');
            } else {
                hash = url.split('#');
                url = hash[0].replace(re, '$1$3').replace(/(&|\?)$/, '');
                if (typeof hash[1] !== 'undefined' && hash[1] !== null) {
                    url += '#' + hash[1];
                }
                return url;
            }
        } else {
            if (typeof value !== 'undefined' && value !== null) {
                var separator = url.indexOf('?') !== -1 ? '&' : '?';
                hash = url.split('#');
                url = hash[0] + separator + key + '=' + value;
                if (typeof hash[1] !== 'undefined' && hash[1] !== null) {
                    url += '#' + hash[1];
                }
                return url;
            } else {
                return url;
            }
        }
    }
})();
<|endoftext|>