<commit_before>angular.module('starter.directives', [])

.directive('cardboardGl', ['Planets', function(Planets) {

  return {
    'restrict': 'E',
    'scope': {
      'stereoEffect':'='
    },
    'link': link
  };

  function link($scope, $element, $attr) {
    var scene, camera, renderer, element, container, effect, controls, clock;
    var StarfieldSize = 20000;
    var StarFighter;
    init();
    function init() {
      // Main Scene
      scene = new THREE.Scene();
      camera = new THREE.PerspectiveCamera(90, window.innerWidth / window.innerHeight, 0.001, StarfieldSize + 100);
      camera.position.set(0, 500, 0);
      scene.add(camera);
      renderer = new THREE.WebGLRenderer({antialias: true});
      element = renderer.domElement;
      container = $element[0];
      container.appendChild(element);
      effect = new THREE.StereoEffect(renderer);
      // Controls
      controls = new THREE.OrbitControls(camera, element);
      controls.target.set(camera.position.x + 0.15, camera.position.y, camera.position.z);
      controls.noPan = true;
      controls.noZoom = true;
      function setOrientationControls(e) {
        if (!e.alpha) {
          return;
        }
        controls = new THREE.DeviceOrientationControls(camera, true);
        controls.connect();
        controls.update();
        element.addEventListener('click', fullscreen, false);
        window.removeEventListener('deviceorientation', setOrientationControls, true);
      };
      window.addEventListener('deviceorientation', setOrientationControls, true);
      // Lighting
      light = new THREE.AmbientLight(0xd9d9d9);
      scene.add(light);
      // Loaders
      var manager = new THREE.LoadingManager();
      manager.onProgress = function(item, loaded, total){
        console.log("Loading: " + loaded + "/" + total);
        if(loaded == total) {
          console.log("Load Finished");
        }
      };
      var Loader_Texture = new THREE.TextureLoader(manager);
      var Loader_OBJ = new THREE.OBJLoader(manager);
      // Textures
      Planets.Loader.load(Planets.baseURL + 'galaxy_starfield.png', function(texture) {
        Planets.Starfield.material = new THREE.MeshPhongMaterial({map: texture, side: THREE.BackSide});
        scene.add(Planets.Starfield);
      });
      Planets.Loader.load(Planets.baseURL + 'sunmap.jpg', function(texture) {
        Planets.Sun.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Sun);
      });
      Planets.Loader.load(Planets.baseURL + 'mercurymap.jpg', function(texture) {
        Planets.Mercury.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Mercury);
      });
      Planets.Loader.load(Planets.baseURL + 'venusmap.jpg', function(texture) {
        Planets.Venus.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Venus);
      });
      Planets.Loader.load(Planets.baseURL + 'earthmap1k.jpg', function(texture) {
        Planets.Earth.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Earth);
      });
      Planets.Loader.load(Planets.baseURL + 'moonmap1k.jpg', function(texture) {
        Planets.EarthMoon.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.EarthMoon);
      });
      Planets.Loader.load(Planets.baseURL + 'marsmap1k.jpg', function(texture) {
        Planets.Mars.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Mars);
      });
      Planets.Loader.load(Planets.baseURL + 'jupitermap.jpg', function(texture) {
        Planets.Jupiter.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Jupiter);
      });
      Planets.Loader.load(Planets.baseURL + 'saturnmap.jpg', function(texture) {
        Planets.Saturn.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Saturn);
      });
      Planets.Loader.load(Planets.baseURL + 'saturn-rings.png', function(texture) {
        Planets.SaturnRing.material = new THREE.MeshBasicMaterial({map: texture, side: THREE.DoubleSide, transparent: true, opacity: 0.6});
        Planets.SaturnRing.rotation.x = -45 * (Math.PI / 180);
        scene.add(Planets.SaturnRing);
      });
      Planets.Loader.load(Planets.baseURL + 'uranusmap.jpg', function(texture) {
        Planets.Uranus.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Uranus);
      });
      Planets.Loader.load(Planets.baseURL + 'saturn-rings.png', function(texture) {
        Planets.UranusRing.material = new THREE.MeshBasicMaterial({map: texture, side: THREE.DoubleSide, transparent: true, opacity: 0.6});
        Planets.UranusRing.rotation.x = -80 * (Math.PI / 180);
        scene.add(Planets.UranusRing);
      });
      Planets.Loader.load(Planets.baseURL + 'neptunemap.jpg', function(texture) {
        Planets.Neptune.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Neptune);
      });
      Planets.Loader.load(Planets.baseURL + 'plutomap1k.jpg', function(texture) {
        Planets.Pluto.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Pluto);
      });
      scene.add(
        Planets.MercuryOrbit,
        Planets.VenusOrbit,
        Planets.EarthOrbit,
        Planets.MoonOrbit,
        Planets.MarsOrbit,
        Planets.JupiterOrbit,
        Planets.SaturnOrbit,
        Planets.UranusOrbit,
        Planets.NeptuneOrbit,
        Planets.PlutoOrbit
      );

      Loader_OBJ.load( 'obj/StarFighter/StarFighter.obj', function (object) {
        object.traverse(function (child) {
          if (child instanceof THREE.Mesh) {
            child.material.map = THREE.ImageUtils.loadTexture('obj/StarFighter/StarFighter.png');
          }
        });
        object.scale.x = 0.3;
        object.scale.y = 0.3;
        object.scale.z = 0.3;
        object.rotation.y = -90 * (Math.PI / 180);
        object.rotation.z = -0 * (Math.PI / 180);
        object.position.set(0, -2, -17);
        StarFighter = object.clone();
        camera.add(StarFighter);
      });

      clock = new THREE.Clock();
      animate();
    };
    function animate() {
      var elapsedSeconds = clock.getElapsedTime();
      requestAnimationFrame(animate);
      update(clock.getDelta());
      render(clock.getDelta());
    };
    function update(dt) {
      resize();
      camera.updateProjectionMatrix();
      controls.update(dt);
    };
    var t = 0;
    function render(dt) {
      /* Magic Zone */
      t += 0.001;
      // Planets Rotation
      Planets.Mercury.rotation.y += 0.005;
      Planets.Venus.rotation.y += 0.005;
      Planets.Earth.rotation.y += 0.005;
      Planets.Mars.rotation.y += 0.005;
      Planets.Jupiter.rotation.y += 0.005;
      Planets.Saturn.rotation.y += 0.005;
      Planets.Uranus.rotation.y += 0.005;
      Planets.Neptune.rotation.y += 0.005;
      Planets.Pluto.rotation.y += 0.005;
      // Planets Translation
      var MathCos = Math.cos(t), MathSin = Math.sin(t);
      Planets.Mercury.position.x = 200 * MathCos;
      Planets.Mercury.position.z = 200 * MathSin;
      Planets.Venus.position.x = 400 * MathCos;
      Planets.Venus.position.z = 400 * MathSin;
      Planets.Earth.position.x = 600 * MathCos;
      Planets.Earth.position.z = 600 * MathSin;
      Planets.MoonOrbit.position.x = Planets.Earth.position.x;
      Planets.MoonOrbit.position.z = Planets.Earth.position.z;
      Planets.EarthMoon.position.x = Planets.MoonOrbit.position.x + (200 * Math.cos(t*10));
      Planets.EarthMoon.position.z = Planets.MoonOrbit.position.z + (200 * Math.sin(t*10));
      Planets.Mars.position.x = 800 * MathCos;
      Planets.Mars.position.z = 800 * MathSin;
      Planets.Jupiter.position.x = 1000 * MathCos;
      Planets.Jupiter.position.z = 1000 * MathSin;
      Planets.Saturn.position.x = 1200 * MathCos;
      Planets.Saturn.position.z = 1200 * MathSin;
      Planets.SaturnRing.position.x = 1200 * MathCos;
      Planets.SaturnRing.position.z = 1200 * MathSin;
      Planets.Uranus.position.x = 1400 * MathCos;
      Planets.Uranus.position.z = 1400 * MathSin;
      Planets.UranusRing.position.x = 1400 * MathCos;
      Planets.UranusRing.position.z = 1400 * MathSin;
      Planets.Neptune.position.x = 1600 * MathCos;
      Planets.Neptune.position.z = 1600 * MathSin;
      Planets.Pluto.position.x = 1800 * MathCos;
      Planets.Pluto.position.z = 1800 * MathSin;
      /* Magic Zone */
      if($scope.stereoEffect == true) {
        effect.render(scene, camera);
      } else {
        renderer.render(scene, camera);
      }
    };
    function resize() {
      var width = container.offsetWidth;
      var height = container.offsetHeight;
      camera.aspect = width / height;
      camera.updateProjectionMatrix();
      if($scope.stereoEffect == true) {
        effect.setSize(width, height);
      } else {
        renderer.setSize(width, height);
      }
    };
    function fullscreen() {
      if (container.requestFullscreen) {
        container.requestFullscreen();
      } else if (container.msRequestFullscreen) {
        container.msRequestFullscreen();
      } else if (container.mozRequestFullScreen) {
        container.mozRequestFullScreen();
      } else if (container.webkitRequestFullscreen) {
        container.webkitRequestFullscreen();
      }
    };
    function PlanetOrbit(Position0, Position1) {
      var deltaX = Position1.X - Position0.X;
      var deltaY = Position1.Y - Position0.Y;
      var deltaZ = Position1.Z - Position0.Z;
      var distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ);
      var Curve = new THREE.EllipseCurve(0, 0, distance, distance, 0, 2 * Math.PI, false, 2);
      var CurvePath = new THREE.Path(Curve.getPoints(50));
      var CurveGeometry = CurvePath.createPointsGeometry(50);
      var CurveMaterial = new THREE.LineBasicMaterial({color: 0x004890});
      var CurveEllipse = new THREE.Line(CurveGeometry, CurveMaterial);
      CurveEllipse.rotation.x = 90 * (Math.PI / 180);
      CurveEllipse.position.set(Position0.X, Position0.Y, Position0.Z);
      return CurveEllipse;
    };
  };
}])
<commit_msg>Removed orbit function from directive<commit_after>angular.module('starter.directives', [])

.directive('cardboardGl', ['Planets', function(Planets) {

  return {
    'restrict': 'E',
    'scope': {
      'stereoEffect':'='
    },
    'link': link
  };

  function link($scope, $element, $attr) {
    var scene, camera, renderer, element, container, effect, controls, clock;
    var StarfieldSize = 20000;
    var StarFighter;
    init();
    function init() {
      // Main Scene
      scene = new THREE.Scene();
      camera = new THREE.PerspectiveCamera(90, window.innerWidth / window.innerHeight, 0.001, StarfieldSize + 100);
      camera.position.set(0, 500, 0);
      scene.add(camera);
      renderer = new THREE.WebGLRenderer({antialias: true});
      element = renderer.domElement;
      container = $element[0];
      container.appendChild(element);
      effect = new THREE.StereoEffect(renderer);
      // Controls
      controls = new THREE.OrbitControls(camera, element);
      controls.target.set(camera.position.x + 0.15, camera.position.y, camera.position.z);
      controls.noPan = true;
      controls.noZoom = true;
      function setOrientationControls(e) {
        if (!e.alpha) {
          return;
        }
        controls = new THREE.DeviceOrientationControls(camera, true);
        controls.connect();
        controls.update();
        element.addEventListener('click', fullscreen, false);
        window.removeEventListener('deviceorientation', setOrientationControls, true);
      };
      window.addEventListener('deviceorientation', setOrientationControls, true);
      // Lighting
      light = new THREE.AmbientLight(0xd9d9d9);
      scene.add(light);
      // Loaders
      var manager = new THREE.LoadingManager();
      manager.onProgress = function(item, loaded, total){
        console.log("Loading: " + loaded + "/" + total);
        if(loaded == total) {
          console.log("Load Finished");
        }
      };
      var Loader_Texture = new THREE.TextureLoader(manager);
      var Loader_OBJ = new THREE.OBJLoader(manager);
      // Textures
      Planets.Loader.load(Planets.baseURL + 'galaxy_starfield.png', function(texture) {
        Planets.Starfield.material = new THREE.MeshPhongMaterial({map: texture, side: THREE.BackSide});
        scene.add(Planets.Starfield);
      });
      Planets.Loader.load(Planets.baseURL + 'sunmap.jpg', function(texture) {
        Planets.Sun.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Sun);
      });
      Planets.Loader.load(Planets.baseURL + 'mercurymap.jpg', function(texture) {
        Planets.Mercury.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Mercury);
      });
      Planets.Loader.load(Planets.baseURL + 'venusmap.jpg', function(texture) {
        Planets.Venus.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Venus);
      });
      Planets.Loader.load(Planets.baseURL + 'earthmap1k.jpg', function(texture) {
        Planets.Earth.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Earth);
      });
      Planets.Loader.load(Planets.baseURL + 'moonmap1k.jpg', function(texture) {
        Planets.EarthMoon.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.EarthMoon);
      });
      Planets.Loader.load(Planets.baseURL + 'marsmap1k.jpg', function(texture) {
        Planets.Mars.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Mars);
      });
      Planets.Loader.load(Planets.baseURL + 'jupitermap.jpg', function(texture) {
        Planets.Jupiter.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Jupiter);
      });
      Planets.Loader.load(Planets.baseURL + 'saturnmap.jpg', function(texture) {
        Planets.Saturn.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Saturn);
      });
      Planets.Loader.load(Planets.baseURL + 'saturn-rings.png', function(texture) {
        Planets.SaturnRing.material = new THREE.MeshBasicMaterial({map: texture, side: THREE.DoubleSide, transparent: true, opacity: 0.6});
        Planets.SaturnRing.rotation.x = -45 * (Math.PI / 180);
        scene.add(Planets.SaturnRing);
      });
      Planets.Loader.load(Planets.baseURL + 'uranusmap.jpg', function(texture) {
        Planets.Uranus.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Uranus);
      });
      Planets.Loader.load(Planets.baseURL + 'saturn-rings.png', function(texture) {
        Planets.UranusRing.material = new THREE.MeshBasicMaterial({map: texture, side: THREE.DoubleSide, transparent: true, opacity: 0.6});
        Planets.UranusRing.rotation.x = -80 * (Math.PI / 180);
        scene.add(Planets.UranusRing);
      });
      Planets.Loader.load(Planets.baseURL + 'neptunemap.jpg', function(texture) {
        Planets.Neptune.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Neptune);
      });
      Planets.Loader.load(Planets.baseURL + 'plutomap1k.jpg', function(texture) {
        Planets.Pluto.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Pluto);
      });
      scene.add(
        Planets.MercuryOrbit,
        Planets.VenusOrbit,
        Planets.EarthOrbit,
        Planets.MoonOrbit,
        Planets.MarsOrbit,
        Planets.JupiterOrbit,
        Planets.SaturnOrbit,
        Planets.UranusOrbit,
        Planets.NeptuneOrbit,
        Planets.PlutoOrbit
      );

      Loader_OBJ.load( 'obj/StarFighter/StarFighter.obj', function (object) {
        object.traverse(function (child) {
          if (child instanceof THREE.Mesh) {
            child.material.map = THREE.ImageUtils.loadTexture('obj/StarFighter/StarFighter.png');
          }
        });
        object.scale.x = 0.3;
        object.scale.y = 0.3;
        object.scale.z = 0.3;
        object.rotation.y = -90 * (Math.PI / 180);
        object.rotation.z = -0 * (Math.PI / 180);
        object.position.set(0, -2, -17);
        StarFighter = object.clone();
        camera.add(StarFighter);
      });

      clock = new THREE.Clock();
      animate();
    };
    function animate() {
      var elapsedSeconds = clock.getElapsedTime();
      requestAnimationFrame(animate);
      update(clock.getDelta());
      render(clock.getDelta());
    };
    function update(dt) {
      resize();
      camera.updateProjectionMatrix();
      controls.update(dt);
    };
    var t = 0;
    function render(dt) {
      /* Magic Zone */
      t += 0.001;
      // Planets Rotation
      Planets.Mercury.rotation.y += 0.005;
      Planets.Venus.rotation.y += 0.005;
      Planets.Earth.rotation.y += 0.005;
      Planets.Mars.rotation.y += 0.005;
      Planets.Jupiter.rotation.y += 0.005;
      Planets.Saturn.rotation.y += 0.005;
      Planets.Uranus.rotation.y += 0.005;
      Planets.Neptune.rotation.y += 0.005;
      Planets.Pluto.rotation.y += 0.005;
      // Planets Translation
      var MathCos = Math.cos(t), MathSin = Math.sin(t);
      Planets.Mercury.position.x = 200 * MathCos;
      Planets.Mercury.position.z = 200 * MathSin;
      Planets.Venus.position.x = 400 * MathCos;
      Planets.Venus.position.z = 400 * MathSin;
      Planets.Earth.position.x = 600 * MathCos;
      Planets.Earth.position.z = 600 * MathSin;
      Planets.MoonOrbit.position.x = Planets.Earth.position.x;
      Planets.MoonOrbit.position.z = Planets.Earth.position.z;
      Planets.EarthMoon.position.x = Planets.MoonOrbit.position.x + (200 * Math.cos(t*10));
      Planets.EarthMoon.position.z = Planets.MoonOrbit.position.z + (200 * Math.sin(t*10));
      Planets.Mars.position.x = 800 * MathCos;
      Planets.Mars.position.z = 800 * MathSin;
      Planets.Jupiter.position.x = 1000 * MathCos;
      Planets.Jupiter.position.z = 1000 * MathSin;
      Planets.Saturn.position.x = 1200 * MathCos;
      Planets.Saturn.position.z = 1200 * MathSin;
      Planets.SaturnRing.position.x = 1200 * MathCos;
      Planets.SaturnRing.position.z = 1200 * MathSin;
      Planets.Uranus.position.x = 1400 * MathCos;
      Planets.Uranus.position.z = 1400 * MathSin;
      Planets.UranusRing.position.x = 1400 * MathCos;
      Planets.UranusRing.position.z = 1400 * MathSin;
      Planets.Neptune.position.x = 1600 * MathCos;
      Planets.Neptune.position.z = 1600 * MathSin;
      Planets.Pluto.position.x = 1800 * MathCos;
      Planets.Pluto.position.z = 1800 * MathSin;
      /* Magic Zone */
      if($scope.stereoEffect == true) {
        effect.render(scene, camera);
      } else {
        renderer.render(scene, camera);
      }
    };
    function resize() {
      var width = container.offsetWidth;
      var height = container.offsetHeight;
      camera.aspect = width / height;
      camera.updateProjectionMatrix();
      if($scope.stereoEffect == true) {
        effect.setSize(width, height);
      } else {
        renderer.setSize(width, height);
      }
    };
    function fullscreen() {
      if (container.requestFullscreen) {
        container.requestFullscreen();
      } else if (container.msRequestFullscreen) {
        container.msRequestFullscreen();
      } else if (container.mozRequestFullScreen) {
        container.mozRequestFullScreen();
      } else if (container.webkitRequestFullscreen) {
        container.webkitRequestFullscreen();
      }
    };
  };
}])
<|endoftext|>


<commit_before>/*
 * Copyright 2014-2015 Fabian Tollenaar <fabian@starting-point.nl>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var Transform = require('stream').Transform;

function FromJson() {
  Transform.call(this, {
    objectMode: true
  });
}

require('util').inherits(FromJson, Transform);

FromJson.prototype._transform = function(chunk, encoding, done) {
  var parsed = null;
  try {
    parsed = JSON.parse(chunk.toString());
  } catch (ex) {
    console.error("Could not parse JSON:" + chunk.toString());
  }
  if (parsed) {
    this.push(parsed)
  }
  done();
}

module.exports = FromJson;<commit_msg>Reformat<commit_after>/*
 * Copyright 2014-2015 Fabian Tollenaar <fabian@starting-point.nl>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var Transform = require('stream').Transform;

function FromJson() {
  Transform.call(this, {
    objectMode: true
  });
}

require('util').inherits(FromJson, Transform);

FromJson.prototype._transform = function(chunk, encoding, done) {
  var parsed = null;
  try {
    parsed = JSON.parse(chunk.toString());
  } catch (ex) {
    console.error("Could not parse JSON:" + chunk.toString());
  }
  if (parsed) {
    this.push(parsed)
  }
  done();
}

module.exports = FromJson;
<|endoftext|>


<commit_before>var Url = require('url');
var http = require('http');
var Buffer = require('buffer').Buffer;
var sessionBridge = require('./../sessionBridge');

var timeout = {
    'GET': 30000,
    'POST': 60000
}
var sendRequest = function(conf){
    var method = conf.method || 'GET';

    var request = http.request({
        host: conf.host,
        port: conf.port,
        method: method,
        path: conf.path || '/',
        headers: conf.headers || {}
    },function(res){
        clearTimeout(requestTimeout);
        var responseTimeout = setTimeout(function(){
            request.abort();
            conf.callback({error: 'response timeout'});
        }, timeout[method]);

        var buffers = [];
        res.on('data', function(chunk){
            buffers.push(chunk);
        });

        res.on('end', function(){
            res.removeAllListeners('data');
            res.removeAllListeners('end');
            clearTimeout(responseTimeout);
            conf.callback({
                res: res,
                content: Buffer.concat(buffers)
            });
        });
    });

    if(conf.method === 'POST' && conf.data){
        request.write(conf.data);
    }

    var requestTimeout = setTimeout(function(){
        request.abort();
        conf.callback({error: 'request timeout'});
    },timeout[method]);

    request.on('error',function(err){
        clearTimeout(requestTimeout);
        request.abort();
        conf.callback({error: 'internal error'});
    });

    request.end();
};

exports.process = function(req, res){
    var conf = {
        host: req._parsedUrl.hostname,
        port: req._parsedUrl.port,
        path: req._parsedUrl.path,
        method: req.method,
        headers: req.headers,
        data: req.postData || null,
        callback: function(resp){
            if(resp.error){
                res.writeHead(500,{});
                res.end();
            }else{
                res.writeHead(resp.res.statusCode, resp.res.headers);
                res.end(resp.content);
            }
            sessionBridge.addSession(req, res || {});
        }
    };

    sendRequest(conf);
    return true;
};

exports.processDefaultReturn = function(req, res, status){
    res.setStatus(status);
    res.end();
    sessionBridge.addSession(req,res || {});
};

exports.processAnotherUrl = function(req, res, url){
    var _parsed = Url.parse(url);
    var conf = {
        host: _parsed.hostname,
        port: _parsed.port || 80,
        path: _parsed.path || '/',
        method: req.method,
        headers: req.headers,
        data: req.postData || null,
        callback: function(resp){
            if(resp.error){
                exports.process(req, res);
            }else{
                res.writeHead(resp.res.statusCode, resp.res.headers);
                res.end(resp.content);
                sessionBridge.addSession(req, res || {});
            }
        }
    };
    conf.headers['host'] = conf.host;
    sendRequest(conf);
    return true;
};

exports.getDataFromUrl = function(url, callback){
    var _parsed = Url.parse(url);
    var conf = {
        host: _parsed.hostname,
        port: _parsed.port || 80,
        path: _parsed.path || '/',
        method: 'GET',
        headers: [],
        data: null,
        callback: function(resp){
            if(resp.error || resp.res.statusCode >= 400 || !resp.content.length){
                callback(null);
            }else{
                callback(resp.content);
            }
        }
    };
    conf.headers['host'] = conf.host;
    sendRequest(conf);
}<commit_msg>host rule highlight bug fix<commit_after>var Url = require('url');
var http = require('http');
var Buffer = require('buffer').Buffer;
var sessionBridge = require('./../sessionBridge');

var timeout = {
    'GET': 30000,
    'POST': 60000
}
var sendRequest = function(conf){
    var method = conf.method || 'GET';

    var request = http.request({
        host: conf.host,
        port: conf.port,
        method: method,
        path: conf.path || '/',
        headers: conf.headers || {}
    },function(res){
        clearTimeout(requestTimeout);
        var responseTimeout = setTimeout(function(){
            request.abort();
            conf.callback({error: 'response timeout'});
        }, timeout[method]);

        var buffers = [];
        res.on('data', function(chunk){
            buffers.push(chunk);
        });

        res.on('end', function(){
            res.removeAllListeners('data');
            res.removeAllListeners('end');
            clearTimeout(responseTimeout);
            conf.callback({
                res: res,
                content: Buffer.concat(buffers)
            });
        });
    });

    if(conf.method === 'POST' && conf.data){
        request.write(conf.data);
    }

    var requestTimeout = setTimeout(function(){
        request.abort();
        conf.callback({error: 'request timeout'});
    },timeout[method]);

    request.on('error',function(err){
        clearTimeout(requestTimeout);
        request.abort();
        conf.callback({error: 'internal error'});
    });

    request.end();
};

exports.process = function(req, res){
    var conf = {
        host: req._parsedUrl.hostname,
        port: req._parsedUrl.port,
        path: req._parsedUrl.path,
        method: req.method,
        headers: req.headers,
        data: req.postData || null,
        callback: function(resp){
            if(resp.error){
                res.writeHead(500,{});
                res.end();
            }else{
                res.writeHead(resp.res.statusCode, resp.res.headers);
                res.end(resp.content);
            }
            sessionBridge.addSession(req, res || {},res && res.matched);
        }
    };

    sendRequest(conf);
    return true;
};

exports.processDefaultReturn = function(req, res, status){
    res.setStatus(status);
    res.end();
    sessionBridge.addSession(req,res || {},res && res.matched);
};

exports.processAnotherUrl = function(req, res, url){
    var _parsed = Url.parse(url);
    var conf = {
        host: _parsed.hostname,
        port: _parsed.port || 80,
        path: _parsed.path || '/',
        method: req.method,
        headers: req.headers,
        data: req.postData || null,
        callback: function(resp){
            if(resp.error){
                exports.process(req, res);
            }else{
                res.writeHead(resp.res.statusCode, resp.res.headers);
                res.end(resp.content);
                sessionBridge.addSession(req, res || {}, res && res.matched);
            }
        }
    };
    conf.headers['host'] = conf.host;
    sendRequest(conf);
    return true;
};

exports.getDataFromUrl = function(url, callback){
    var _parsed = Url.parse(url);
    var conf = {
        host: _parsed.hostname,
        port: _parsed.port || 80,
        path: _parsed.path || '/',
        method: 'GET',
        headers: [],
        data: null,
        callback: function(resp){
            if(resp.error || resp.res.statusCode >= 400 || !resp.content.length){
                callback(null);
            }else{
                callback(resp.content);
            }
        }
    };
    conf.headers['host'] = conf.host;
    sendRequest(conf);
}<|endoftext|>


<commit_before>/*
 * grunt-contrib-coffee
 * http://gruntjs.com/
 *
 * Copyright (c) 2014 Eric Woroshow, contributors
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {
  var path = require('path');
  var chalk = require('chalk');
  var _ = require('lodash');

  grunt.registerMultiTask('coffee', 'Compile CoffeeScript files into JavaScript', function() {
    var options = this.options({
      bare: false,
      join: false,
      sourceMap: false,
      joinExt: '.src.coffee',
      separator: grunt.util.linefeed
    });
    var actionCounts = {
      createdFile: 0,
      createdMap: 0
    };

    options.separator = grunt.util.normalizelf(options.separator);

    this.files.forEach(function(f) {
      var validFiles = removeInvalidFiles(f);

      if (options.sourceMap === true) {
        var paths = createOutputPaths(f.dest);
        // add sourceMapDir to options object
        var fileOptions = _.extend({ sourceMapDir: paths.destDir }, options);
        var writeResult = writeFileAndMap(paths, compileWithMaps(validFiles, fileOptions, paths), fileOptions);
        actionCounts.createdFile += writeResult.createdFile;
        actionCounts.createdMap += writeResult.createdMap;
      } else if (options.join === true) {
        actionCounts.createdFile += writeCompiledFile(f.dest, concatInput(validFiles, options));
      } else {
        actionCounts.createdFile += writeCompiledFile(f.dest, concatOutput(validFiles, options));
      }
    });

    grunt.log.ok(actionCounts.createdFile + ' files created.');
    if (actionCounts.createdMap > 0) {
      grunt.log.ok(actionCounts.createdMap + ' source map files created.');
    }
  });

  var isLiterate = function(ext) {
    return (ext === '.litcoffee' || ext === '.md');
  };

  var removeInvalidFiles = function(files) {
    return files.src.filter(function(filepath) {
      if (!grunt.file.exists(filepath)) {
        grunt.log.warn('Source file "' + filepath + '" not found.');
        return false;
      } else {
        return true;
      }
    });
  };

  var createOutputPaths = function(destination) {
    var fileName = path.basename(destination, path.extname(destination));
    return {
      dest: destination,
      destName: fileName,
      destDir: appendTrailingSlash(path.dirname(destination)),
      mapFileName: fileName + '.js.map'
    };
  };

  var appendTrailingSlash = function(dirname) {
    if (dirname.length > 0 && dirname.slice(-1) !== path.sep) {
      return dirname + path.sep;
    } else {
      return dirname;
    }
  };

  var compileWithMaps = function(files, options, paths) {
    if (!hasUniformExtensions(files)) {
      return;
    }

    var mapOptions, filepath;

    if (files.length > 1) {
      mapOptions = createOptionsForJoin(files, paths, options.separator, options.joinExt);
    } else {
      mapOptions = createOptionsForFile(files[0], paths);
      filepath = files[0];
    }

    options = _.extend({
      generatedFile: path.basename(paths.dest),
      sourceRoot: mapOptions.sourceRoot,
      sourceFiles: mapOptions.sourceFiles
    }, options);

    var output = compileCoffee(mapOptions.code, options, filepath);
    appendFooter(output, paths, options);
    return output;
  };

  var hasUniformExtensions = function(files) {
    // get all extensions for input files
    var extensions = _.uniq(files.map(path.extname));

    if (extensions.length > 1) {
      grunt.fail.warn('Join and sourceMap options require input files share the same extension (found ' + extensions.join(', ') + ').');
      return false;
    } else {
      return true;
    }
  };

  var createOptionsForJoin = function (files, paths, separator, joinExt) {
    var code = concatFiles(files, separator);
    var targetFileName = paths.destName + joinExt;
    grunt.file.write(paths.destDir + targetFileName, code);

    return {
      code: code,
      sourceFiles: [targetFileName],
      sourceRoot: ''
    };
  };

  var concatFiles = function(files, separator) {
    return files.map(grunt.file.read).join(separator);
  };

  var createOptionsForFile = function(file, paths) {
    return {
      code: grunt.file.read(file),
      sourceFiles: [path.basename(file)],
      sourceRoot: appendTrailingSlash(path.relative(paths.destDir, path.dirname(file)))
    };
  };

  var appendFooter = function(output, paths, options) {
    // We need the sourceMappingURL to be relative to the JS path
    var sourceMappingDir = appendTrailingSlash(path.relative(paths.destDir, options.sourceMapDir));
    // Add sourceMappingURL to file footer
    output.js = output.js + '\n//# sourceMappingURL=' + sourceMappingDir + paths.mapFileName + '\n';
  };

  var concatInput = function(files, options) {
    if (hasUniformExtensions(files)) {
      var code = concatFiles(files, options.separator);
      return compileCoffee(code, options);
    }
  };

  var concatOutput = function(files, options) {
    return files.map(function(filepath) {
      var code = grunt.file.read(filepath);
      return compileCoffee(code, options, filepath);
    }).join(options.separator);
  };

  var compileCoffee = function(code, options, filepath) {
    var coffeeOptions = _.clone(options);
    if (filepath) {
      coffeeOptions.filename = filepath;
      coffeeOptions.literate = isLiterate(path.extname(filepath));
    }

    try {
      return require('coffee-script').compile(code, coffeeOptions);
    } catch (e) {
      if (e.location == null ||
          e.location.first_column == null ||
          e.location.first_line == null) {
        grunt.log.error('Got an unexpected exception ' +
                        'from the coffee-script compiler. ' +
                        'The original exception was: ' +
                        e);
        grunt.log.error('(The coffee-script compiler should not raise *unexpected* exceptions. ' +
                        'You can file this error as an issue of the coffee-script compiler: ' +
                        'https://github.com/jashkenas/coffee-script/issues)');
      } else {
        var firstColumn = e.location.first_column;
        var firstLine = e.location.first_line;
        var codeLine = code.split('\n')[firstLine];
        var errorArrows = chalk.red('>>') + ' ';
        var offendingCharacter;

        if (firstColumn < codeLine.length) {
          offendingCharacter = chalk.red(codeLine[firstColumn]);
        } else {
          offendingCharacter = '';
        }

        grunt.log.error(e);
        grunt.log.error('In file: ' + filepath);
        grunt.log.error('On line: ' + firstLine);
        // log erroneous line and highlight offending character
        // grunt.log.error trims whitespace so we have to use grunt.log.writeln
        grunt.log.writeln(errorArrows + codeLine.substring(0, firstColumn) +
                          offendingCharacter + codeLine.substring(firstColumn + 1));
        grunt.log.writeln(errorArrows + grunt.util.repeat(firstColumn, ' ') +
                          chalk.red('^'));
      }
      grunt.fail.warn('CoffeeScript failed to compile.');
    }
  };

  var writeFileAndMap = function(paths, output, options) {
    if (!output || output.js.length === 0) {
      warnOnEmptyFile(paths.dest);
      return;
    }

    var createdFile = writeCompiledFile(paths.dest, output.js);
    options.sourceMapDir = appendTrailingSlash(options.sourceMapDir);
    var createdMap = writeSourceMapFile(options.sourceMapDir + paths.mapFileName, output.v3SourceMap);

    return {
      createdFile: createdFile,
      createdMap: createdMap
    };
  };

  var warnOnEmptyFile = function(path) {
    grunt.log.warn('Destination "' + path + '" not written because compiled files were empty.');
  };

  var writeFile = function(path, output) {
    if (output.length < 1) {
      warnOnEmptyFile(path);
      return false;
    } else {
      grunt.file.write(path, output);
      return true;
    }
  };

  var writeCompiledFile = function(path, output) {
    if (writeFile(path, output)) {
      grunt.verbose.writeln('File ' + chalk.cyan(path) + ' created.');
      return 1;
    } else {
      return 0;
    }
  };
  var writeSourceMapFile = function(path, output) {
    if (writeFile(path, output)) {
      grunt.verbose.writeln('File ' + chalk.cyan(path) + ' created (source map).');
      return 1;
    } else {
      return 0;
    }
  };
};
<commit_msg>Support inline source maps<commit_after>/*
 * grunt-contrib-coffee
 * http://gruntjs.com/
 *
 * Copyright (c) 2014 Eric Woroshow, contributors
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {
  var path = require('path');
  var chalk = require('chalk');
  var _ = require('lodash');
  var convert = require("convert-source-map");

  grunt.registerMultiTask('coffee', 'Compile CoffeeScript files into JavaScript', function() {
    var options = this.options({
      bare: false,
      join: false,
      sourceMap: false,
      inline: false,
      joinExt: '.src.coffee',
      separator: grunt.util.linefeed
    });
    var actionCounts = {
      createdFile: 0,
      createdMap: 0
    };

    options.separator = grunt.util.normalizelf(options.separator);

    this.files.forEach(function(f) {
      var validFiles = removeInvalidFiles(f);

      if (options.sourceMap === true) {
        var paths = createOutputPaths(f.dest);
        // add sourceMapDir to options object
        var fileOptions = _.extend({ sourceMapDir: paths.destDir }, options);
        var writeResult = writeFileAndMap(paths, compileWithMaps(validFiles, fileOptions, paths), fileOptions);
        actionCounts.createdFile += writeResult.createdFile;
        if (writeResult.createdMap != null) {
          actionCounts.createdMap += writeResult.createdMap;
        }
      } else if (options.join === true) {
        actionCounts.createdFile += writeCompiledFile(f.dest, concatInput(validFiles, options));
      } else {
        actionCounts.createdFile += writeCompiledFile(f.dest, concatOutput(validFiles, options));
      }
    });

    grunt.log.ok(actionCounts.createdFile + ' files created.');
    if (actionCounts.createdMap > 0) {
      grunt.log.ok(actionCounts.createdMap + ' source map files created.');
    }
  });

  var isLiterate = function(ext) {
    return (ext === '.litcoffee' || ext === '.md');
  };

  var removeInvalidFiles = function(files) {
    return files.src.filter(function(filepath) {
      if (!grunt.file.exists(filepath)) {
        grunt.log.warn('Source file "' + filepath + '" not found.');
        return false;
      } else {
        return true;
      }
    });
  };

  var createOutputPaths = function(destination) {
    var fileName = path.basename(destination, path.extname(destination));
    return {
      dest: destination,
      destName: fileName,
      destDir: appendTrailingSlash(path.dirname(destination)),
      mapFileName: fileName + '.js.map'
    };
  };

  var appendTrailingSlash = function(dirname) {
    if (dirname.length > 0 && dirname.slice(-1) !== path.sep) {
      return dirname + path.sep;
    } else {
      return dirname;
    }
  };

  var compileWithMaps = function(files, options, paths) {
    if (!hasUniformExtensions(files)) {
      return;
    }

    var mapOptions, filepath;

    if (files.length > 1) {
      mapOptions = createOptionsForJoin(files, paths, options.separator, options.joinExt);
    } else {
      mapOptions = createOptionsForFile(files[0], paths);
      filepath = files[0];
    }

    options = _.extend({
      generatedFile: path.basename(paths.dest),
      sourceRoot: mapOptions.sourceRoot,
      sourceFiles: mapOptions.sourceFiles
    }, options);

    var output = compileCoffee(mapOptions.code, options, filepath);
    appendFooter(output, paths, options);
    return output;
  };

  var hasUniformExtensions = function(files) {
    // get all extensions for input files
    var extensions = _.uniq(files.map(path.extname));

    if (extensions.length > 1) {
      grunt.fail.warn('Join and sourceMap options require input files share the same extension (found ' + extensions.join(', ') + ').');
      return false;
    } else {
      return true;
    }
  };

  var createOptionsForJoin = function (files, paths, separator, joinExt) {
    var code = concatFiles(files, separator);
    var targetFileName = paths.destName + joinExt;
    grunt.file.write(paths.destDir + targetFileName, code);

    return {
      code: code,
      sourceFiles: [targetFileName],
      sourceRoot: ''
    };
  };

  var concatFiles = function(files, separator) {
    return files.map(grunt.file.read).join(separator);
  };

  var createOptionsForFile = function(file, paths) {
    return {
      code: grunt.file.read(file),
      sourceFiles: [path.basename(file)],
      sourceRoot: appendTrailingSlash(path.relative(paths.destDir, path.dirname(file)))
    };
  };

  var appendFooter = function(output, paths, options) {
    if (!options.inline) {
      // We need the sourceMappingURL to be relative to the JS path
      var sourceMappingDir = appendTrailingSlash(path.relative(paths.destDir, options.sourceMapDir));
      // Add sourceMappingURL to file footer
      output.js = output.js + '\n//# sourceMappingURL=' + sourceMappingDir + paths.mapFileName + '\n';
    }
  };

  var concatInput = function(files, options) {
    if (hasUniformExtensions(files)) {
      var code = concatFiles(files, options.separator);
      return compileCoffee(code, options);
    }
  };

  var concatOutput = function(files, options) {
    return files.map(function(filepath) {
      var code = grunt.file.read(filepath);
      return compileCoffee(code, options, filepath);
    }).join(options.separator);
  };

  var compileCoffee = function(code, options, filepath) {
    var coffeeOptions = _.clone(options);
    if (filepath) {
      coffeeOptions.filename = filepath;
      coffeeOptions.literate = isLiterate(path.extname(filepath));
    }

    try {
      return require('coffee-script').compile(code, coffeeOptions);
    } catch (e) {
      if (e.location == null ||
          e.location.first_column == null ||
          e.location.first_line == null) {
        grunt.log.error('Got an unexpected exception ' +
                        'from the coffee-script compiler. ' +
                        'The original exception was: ' +
                        e);
        grunt.log.error('(The coffee-script compiler should not raise *unexpected* exceptions. ' +
                        'You can file this error as an issue of the coffee-script compiler: ' +
                        'https://github.com/jashkenas/coffee-script/issues)');
      } else {
        var firstColumn = e.location.first_column;
        var firstLine = e.location.first_line;
        var codeLine = code.split('\n')[firstLine];
        var errorArrows = chalk.red('>>') + ' ';
        var offendingCharacter;

        if (firstColumn < codeLine.length) {
          offendingCharacter = chalk.red(codeLine[firstColumn]);
        } else {
          offendingCharacter = '';
        }

        grunt.log.error(e);
        grunt.log.error('In file: ' + filepath);
        grunt.log.error('On line: ' + firstLine);
        // log erroneous line and highlight offending character
        // grunt.log.error trims whitespace so we have to use grunt.log.writeln
        grunt.log.writeln(errorArrows + codeLine.substring(0, firstColumn) +
                          offendingCharacter + codeLine.substring(firstColumn + 1));
        grunt.log.writeln(errorArrows + grunt.util.repeat(firstColumn, ' ') +
                          chalk.red('^'));
      }
      grunt.fail.warn('CoffeeScript failed to compile.');
    }
  };

  var writeFileAndMap = function(paths, output, options) {
    if (!output || output.js.length === 0) {
      warnOnEmptyFile(paths.dest);
      return;
    }

    if (!options.inline) {
      var createdFile = writeCompiledFile(paths.dest, output.js);
      options.sourceMapDir = appendTrailingSlash(options.sourceMapDir);
      var createdMap = writeSourceMapFile(options.sourceMapDir + paths.mapFileName, output.v3SourceMap);

      return {
        createdFile: createdFile,
        createdMap: createdMap
      };
    } else {
      var comment = convert.fromObject(output.v3SourceMap).toComment();
      output.js += "\n" + comment;
      var createdFile = writeCompiledFile(paths.dest, output.js);

      return {
        createdFile: createdFile
      };
    }

  };

  var warnOnEmptyFile = function(path) {
    grunt.log.warn('Destination "' + path + '" not written because compiled files were empty.');
  };

  var writeFile = function(path, output) {
    if (output.length < 1) {
      warnOnEmptyFile(path);
      return false;
    } else {
      grunt.file.write(path, output);
      return true;
    }
  };

  var writeCompiledFile = function(path, output) {
    if (writeFile(path, output)) {
      grunt.verbose.writeln('File ' + chalk.cyan(path) + ' created.');
      return 1;
    } else {
      return 0;
    }
  };
  var writeSourceMapFile = function(path, output) {
    if (writeFile(path, output)) {
      grunt.verbose.writeln('File ' + chalk.cyan(path) + ' created (source map).');
      return 1;
    } else {
      return 0;
    }
  };
};
<|endoftext|>


<commit_before>(function () {
    'use strict';

    var userData, taggle;
    var newUserData = {};
    var ITEM_PER_PAGE = 20;
    var keyword = 'All';
    var clipId = null;
    var pageNum = 0;
    var isCompleteLoading = false;
    var isLoading = false;
    var container = '#feed_list_panel';
    var $loaderCircle = $('#loaderCircle');
    var wookmark = undefined;
    var options = {
        offset: 12, // Optional, the distance between grid items
        itemWidth: 251 // Optional, the width of a grid item
    };

    var button = $('', {
        src: '/images/card_delete_icon.png',
        class: 'site-delete-btn'
    });

    function init() {
        userData = g_data.user;

        taggle = new Taggle('keyword-box', {
            tags: userData.keywords,
            placeholder: '태그 입력',
            duplicateTagClass: 'bounce'
        });

        $(".board").click(function(){
            $(".myclip_title").text($(this).data('title'));
            $('.myclip_title').attr('data-id', $(this).data('id'));
            clearBoardList();
            clipId = $(this).data('id');
            $('#board_feed_list_container').removeClass('hide');
            initWookmark();
        });

        $('.board-setting-btn').click(function () {

            if ( $('.board_delete_btn').css('display') == 'none'){
                $(this).text("종료하기");
                $('.board_delete_btn').show();
            }
            else{
                $('.board_delete_btn').hide();
                $(this).text("보드관리");
            }
        });

        $(".myclip-bar-title-box").click(function(){
            location.reload(true);
        });

        $(".board_delete_btn").click(function(){
            var boardId = $(this).parent().parent().data('id');
            console.log(boardId);
            if(confirm("정말 삭제하시겠습니까?")){
                console.log("삭제됨");
                var params = {};
                HttpUtil.deleteData('/clip/delete/id/'+boardId, params, function(err, data) {
                    if(err != null){
                        alert(data);
                        return false;
                    }
                    location.reload(true);
                    return false;
                });
            }
            else{
                console.log("삭제되지않음");
                return false;
            }
        });

        $('#keyword_setting_btn').click(function() {
            $('#setting_modal').modal('show');
            initModal();
        });

        $('.sidebar-setting-icon').click(function() {
            $('#profile_modal').modal('show');
            initUserSettingModal();
        });

        if (userData.feeds.length === 0) {
            alert("등록된 사이트가 없습니다. 키워드 관리로 이동합니다.");
            $('#keyword_setting_btn').trigger('click');
        }
        if (userData.feeds.length > 0 && userData.keywords.length === 0) {
            alert("등록된 키워드가 없습니다. 키워드 관리로 이동합니다.");
            $('#keyword_setting_btn').trigger('click');
        }
    }

    function initModalSiteItems() {
        $('.site_list').empty();
        $.unique($('.site_list'));
        for (var i=0; i<newUserData.feeds.length; i++) {
            $('.site_list').append('
' + newUserData.feeds[i] + '
');

        }
        $('.site_list > li').append(button);
    }

    function initModal() {
        $.extend(true, newUserData, userData);

        initModalSiteItems();

        $('#modal_add_btn').unbind('click').click(function() {
            HttpUtil.postData('/feed/check', {feed: $('#modal_input_site').val()}, function(err, result) {
                if (err) return alert('등록할 수 없는 사이트입니다.(RSS를 지원하는 사이트만 추가 가능합니다.)');
                alert("추가되었습니다.");
                newUserData.feeds.push(result);
                initModal();
                $('#modal_input_site').val('');
            });
        });

        $('.site-delete-btn').unbind('click').click(function() {
            var feedIndex = newUserData.feeds.indexOf($(this).parent().text());
            newUserData.feeds.splice(feedIndex, 1);
            $(this).parent().remove();
            console.log(newUserData.feeds);
            console.log('성공');
        });

        $('#modal_key_btn').unbind('click').click(function() {
            newUserData.keywords = taggle.getTagValues();
            HttpUtil.putData('/user/id/'+newUserData._id, {feeds: newUserData.feeds, keywords: newUserData.keywords},
                function(err, result) {
                if (err) return alert(err);
                alert("등록되었습니다.");
                location.reload(true);
            });
        });
    }

    //프로필 설정 모달
    function initUserSettingModal() {

        $('#logout_btn').click(function() {
            HttpUtil.postData('/user/logout', {}, function (err) {
                if (err || null) return alert('로그아웃 실패!');
                alert("로그아웃 되었습니다!");
                location.href = "/signin";
            });
        });

        $('#fileupload').fileupload({
            dataType: 'json',
            done: function (e, data) {
                var result = data.result;
                var image = result.data;
                $('.profile-image-box').attr('src', image);
                $('#fileupload').attr('value',image);
                console.log(image);
            }
        });

        $('#profile_name_input').val(userData.name);
        $(document).ready(function() {

            $("#profile_name_input").keyup(function(event){
                if (!(event.keyCode >=37 && event.keyCode<=40)) {
                    var inputVal = $(this).val();
                    $(this).val(inputVal.replace(/[^a-z0-9]/gi,''));
                }

            });
        });

        $('#change_pw_input').val(userData.pw);
        $('#change_pw_confirm').val(userData.pw);

        $('#modal_save_btn').click(function() {
            var minLength = 6;
            var $textarea = $('#change_pw_input');
            var userId = userData._id;
            var params = {
                name: $('#profile_name_input').val() ,
                pw : $('#change_pw_input').val(),
                profileUrl: $('#fileupload').attr('value')
            };
            var name = $('#profile_name_input').val();
            var passwordVal = $('#change_pw_input').val();
            var checkVal = $('#change_pw_confirm').val();
            var hasError = false;
            var image = $('#fileupload').val();
            //HttpUtil.putData('/upload/'+image, params, function (err) {
            //    if (err) return alert('사진 변경 실패');
            //});

            HttpUtil.putData('/user/id/'+userId, params, function (err) {
                if (err || null) return alert('저장 실패!');

                var blank_pattern = /[\s]/g;
                if( blank_pattern.test(name) == true){
                    alert(' 공백은 사용할 수 없습니다.');
                    return false;
                }

                if(name == "") return alert('이름을 입력해주세요.');

                if($textarea.val().length < minLength) {
                    alert('비밀번호를 6자 이상으로 입력해 주세요.');
                    return false;
                }

                if(checkVal.length < minLength) {
                    alert('비밀번호를 6자 이상으로 입력해 주세요.');
                    return false;
                }

                if (passwordVal != checkVal ) {
                    $("#change_pw_input").after(function() {
                        alert('비밀번호가 다릅니다.');
                        $("#change_pw_input").focus();
                        return false;
                    });
                    hasError = true;
                }
                else{
                    alert("저장되었습니다.");
                    location.href = "/user";
                    return true;
                }
            });
        });

    }

    function initWookmark() {
        /**
         * When scrolled all the way to the bottom, add more tiles.
         */
        function onScroll(event) {
            // Only check when we're not still waiting for data.
            if(!isLoading) {
                // Check if we're within 100 pixels of the bottom edge of the broser window.
                var closeToBottom = ($(window).scrollTop() + $(window).height() > $(document).height() - 100);
                if (closeToBottom) {
                    loadData();
                }
            }
        }
        /**
         * Refreshes the layout after all images have loaded
         */
        function applyLayout() {
            imagesLoaded(container, function () {
                if (wookmark === undefined) {
                    wookmark = new Wookmark(container, options);
                } else {
                    wookmark.initItems();
                    wookmark.layout(true);
                }
                $loaderCircle.hide();
            });

        }

        /**
         * Loads data from the API.
         */
        function loadData() {
            if (isCompleteLoading) return;
            var params = {
                pageNum: pageNum,
                perPage: ITEM_PER_PAGE
            };
            if (keyword !== 'All') {
                params.keyword = keyword;
            }
            if (clipId !== null) {
                params.clipId = clipId;
            }
            isLoading = true;
            $loaderCircle.show();

            HttpUtil.getData('/feed/user', params, function(err, data) {
                onLoadData(data);
                bindEvent();
            });
        }

        /**
         * Receives data from the API, creates HTML for images and updates the layout
         */
        function onLoadData(feedData) {
            isLoading = false;
            // Increment pageNum index for future calls.
            pageNum++;
            var length = feedData && feedData.length;
            var html = '';
            var i;

            if (!length) {
                isCompleteLoading = true;
                $loaderCircle.hide();
                return;
            }

            // Create HTML for the images.
            for(i=0; i<length; i++) {
                feedData[i].image = getFeedBoxImageSrc(feedData[i].description);
                html += getFeedBoxHtml(feedData[i]);
            }

            // Add image HTML to the pageNum.
            $(container).append(html);
            // Apply layout.
            applyLayout();
        }

        // Capture scroll event.
        $(document).unbind('scroll').bind('scroll', onScroll);
        // Load first data from the API.
        loadData();
    }

    function bindEvent() {
        $('#feed_list_panel > li > .clip-icon-circle').unbind('click').click(function() {
            var $feedItem = $(this).parent();
            var clipId = $('.myclip_title').data('id');
            var feed = { feed: $feedItem.data('id') };

            if ($(this).hasClass('on')) {
                $(this).removeClass('on');
                HttpUtil.putData('/clip/update/id/'+clipId+'/remove/feed', feed, function(err, result) {
                    if (err) return alert(err);
                    console.log("success");
                });
            } else {
                $(this).addClass('on');
                HttpUtil.putData('/clip/update/id/'+clipId+'/add/feed', feed, function(err, result) {
                    if (err) return alert(err);
                    console.log("success");
                });
            }
            return false;
        });
    }

    function getFeedBoxImageSrc(description) {
        var defaultImageSrc = '/images/card_no_image.png';
        if (!description) return defaultImageSrc;
        return $(description).find('img').first().attr('src') || defaultImageSrc;
    }

    function getFeedBoxHtml(feed) {
        var html =
            '
'+
            ''+
            ''+
            ''+
            '
'+
            ''+
            '
'+
            '
'+
            '
'+feed.title+'
'+
            '
'+
            '
'+
            '
'+
            ''+
            ''+feed.keywordString+
            ''+
            '
'+
            '
';
        if (feed.isCliped) {
            html += '';
        }
        html += '
'+
            '
'+
            '
';
        return html;
    }

    function resetWookmark() {
        pageNum = 0;
        isCompleteLoading = false;
        isLoading = false;
        $(container).empty();
        initWookmark();
    }

    function clearBoardList() {
        $('.boards > .board').remove();
    }

    $(document).ready(function() {
        init();
    });
}());

<commit_msg>Update<commit_after>(function () {
    'use strict';

    var userData, taggle;
    var newUserData = {};
    var ITEM_PER_PAGE = 20;
    var keyword = 'All';
    var clipId = null;
    var pageNum = 0;
    var isCompleteLoading = false;
    var isLoading = false;
    var container = '#feed_list_panel';
    var $loaderCircle = $('#loaderCircle');
    var wookmark = undefined;
    var options = {
        offset: 12, // Optional, the distance between grid items
        itemWidth: 251 // Optional, the width of a grid item
    };

    var button = $('', {
        src: '/images/card_delete_icon.png',
        class: 'site-delete-btn'
    });

    function init() {
        userData = g_data.user;

        taggle = new Taggle('keyword-box', {
            tags: userData.keywords,
            placeholder: '태그 입력',
            duplicateTagClass: 'bounce'
        });

        $(".board").click(function(){
            $(".myclip_title").text($(this).data('title'));
            $('.myclip_title').attr('data-id', $(this).data('id'));
            clearBoardList();
            clipId = $(this).data('id');
            $('#board_feed_list_container').removeClass('hide');
            $('.board-setting-btn').hide();
            initWookmark();

        });

        $('.board-setting-btn').click(function () {

            if ( $('.board_delete_btn').css('display') == 'none'){
                $(this).text("종료하기");
                $('.board_delete_btn').show();
            }
            else{
                $('.board_delete_btn').hide();
                $(this).text("보드관리");
            }
        });

        $(".myclip-bar-title-box").click(function(){
            location.reload(true);
        });

        $(".board_delete_btn").click(function(){
            var boardId = $(this).parent().parent().data('id');
            console.log(boardId);
            if(confirm("정말 삭제하시겠습니까?")){
                console.log("삭제됨");
                var params = {};
                HttpUtil.deleteData('/clip/delete/id/'+boardId, params, function(err, data) {
                    if(err != null){
                        alert(data);
                        return false;
                    }
                    location.reload(true);
                    return false;
                });
            }
            else{
                console.log("삭제되지않음");
                return false;
            }
        });

        $('#keyword_setting_btn').click(function() {
            $('#setting_modal').modal('show');
            initModal();
        });

        $('.sidebar-setting-icon').click(function() {
            $('#profile_modal').modal('show');
            initUserSettingModal();
        });

        if (userData.feeds.length === 0) {
            alert("등록된 사이트가 없습니다. 키워드 관리로 이동합니다.");
            $('#keyword_setting_btn').trigger('click');
        }
        if (userData.feeds.length > 0 && userData.keywords.length === 0) {
            alert("등록된 키워드가 없습니다. 키워드 관리로 이동합니다.");
            $('#keyword_setting_btn').trigger('click');
        }
    }

    function initModalSiteItems() {
        $('.site_list').empty();
        $.unique($('.site_list'));
        for (var i=0; i<newUserData.feeds.length; i++) {
            $('.site_list').append('
' + newUserData.feeds[i] + '
');

        }
        $('.site_list > li').append(button);
    }

    function initModal() {
        $.extend(true, newUserData, userData);

        initModalSiteItems();

        $('#modal_add_btn').unbind('click').click(function() {
            HttpUtil.postData('/feed/check', {feed: $('#modal_input_site').val()}, function(err, result) {
                if (err) return alert('등록할 수 없는 사이트입니다.(RSS를 지원하는 사이트만 추가 가능합니다.)');
                alert("추가되었습니다.");
                newUserData.feeds.push(result);
                initModal();
                $('#modal_input_site').val('');
            });
        });

        $('.site-delete-btn').unbind('click').click(function() {
            var feedIndex = newUserData.feeds.indexOf($(this).parent().text());
            newUserData.feeds.splice(feedIndex, 1);
            $(this).parent().remove();
            console.log(newUserData.feeds);
            console.log('성공');
        });

        $('#modal_key_btn').unbind('click').click(function() {
            newUserData.keywords = taggle.getTagValues();
            HttpUtil.putData('/user/id/'+newUserData._id, {feeds: newUserData.feeds, keywords: newUserData.keywords},
                function(err, result) {
                if (err) return alert(err);
                alert("등록되었습니다.");
                location.reload(true);
            });
        });
    }

    //프로필 설정 모달
    function initUserSettingModal() {

        $('#logout_btn').click(function() {
            HttpUtil.postData('/user/logout', {}, function (err) {
                if (err || null) return alert('로그아웃 실패!');
                alert("로그아웃 되었습니다!");
                location.href = "/signin";
            });
        });

        $('#fileupload').fileupload({
            dataType: 'json',
            done: function (e, data) {
                var result = data.result;
                var image = result.data;
                $('.profile-image-box').attr('src', image);
                $('#fileupload').attr('value',image);
                console.log(image);
            }
        });

        $('#profile_name_input').val(userData.name);
        $(document).ready(function() {

            $("#profile_name_input").keyup(function(event){
                if (!(event.keyCode >=37 && event.keyCode<=40)) {
                    var inputVal = $(this).val();
                    $(this).val(inputVal.replace(/[^a-z0-9]/gi,''));
                }

            });
        });

        $('#change_pw_input').val(userData.pw);
        $('#change_pw_confirm').val(userData.pw);

        $('#modal_save_btn').click(function() {
            var minLength = 6;
            var $textarea = $('#change_pw_input');
            var userId = userData._id;
            var params = {
                name: $('#profile_name_input').val() ,
                pw : $('#change_pw_input').val(),
                profileUrl: $('#fileupload').attr('value')
            };
            var name = $('#profile_name_input').val();
            var passwordVal = $('#change_pw_input').val();
            var checkVal = $('#change_pw_confirm').val();
            var hasError = false;
            var image = $('#fileupload').val();
            //HttpUtil.putData('/upload/'+image, params, function (err) {
            //    if (err) return alert('사진 변경 실패');
            //});

            HttpUtil.putData('/user/id/'+userId, params, function (err) {
                if (err || null) return alert('저장 실패!');

                var blank_pattern = /[\s]/g;
                if( blank_pattern.test(name) == true){
                    alert(' 공백은 사용할 수 없습니다.');
                    return false;
                }

                if(name == "") return alert('이름을 입력해주세요.');

                if($textarea.val().length < minLength) {
                    alert('비밀번호를 6자 이상으로 입력해 주세요.');
                    return false;
                }

                if(checkVal.length < minLength) {
                    alert('비밀번호를 6자 이상으로 입력해 주세요.');
                    return false;
                }

                if (passwordVal != checkVal ) {
                    $("#change_pw_input").after(function() {
                        alert('비밀번호가 다릅니다.');
                        $("#change_pw_input").focus();
                        return false;
                    });
                    hasError = true;
                }
                else{
                    alert("저장되었습니다.");
                    location.href = "/user";
                    return true;
                }
            });
        });

    }

    function initWookmark() {
        /**
         * When scrolled all the way to the bottom, add more tiles.
         */
        function onScroll(event) {
            // Only check when we're not still waiting for data.
            if(!isLoading) {
                // Check if we're within 100 pixels of the bottom edge of the broser window.
                var closeToBottom = ($(window).scrollTop() + $(window).height() > $(document).height() - 100);
                if (closeToBottom) {
                    loadData();
                }
            }
        }
        /**
         * Refreshes the layout after all images have loaded
         */
        function applyLayout() {
            imagesLoaded(container, function () {
                if (wookmark === undefined) {
                    wookmark = new Wookmark(container, options);
                } else {
                    wookmark.initItems();
                    wookmark.layout(true);
                }
                $loaderCircle.hide();
            });

        }

        /**
         * Loads data from the API.
         */
        function loadData() {
            if (isCompleteLoading) return;
            var params = {
                pageNum: pageNum,
                perPage: ITEM_PER_PAGE
            };
            if (keyword !== 'All') {
                params.keyword = keyword;
            }
            if (clipId !== null) {
                params.clipId = clipId;
            }
            isLoading = true;
            $loaderCircle.show();

            HttpUtil.getData('/feed/user', params, function(err, data) {
                onLoadData(data);
                bindEvent();
            });
        }

        /**
         * Receives data from the API, creates HTML for images and updates the layout
         */
        function onLoadData(feedData) {
            isLoading = false;
            // Increment pageNum index for future calls.
            pageNum++;
            var length = feedData && feedData.length;
            var html = '';
            var i;

            if (!length) {
                isCompleteLoading = true;
                $loaderCircle.hide();
                return;
            }

            // Create HTML for the images.
            for(i=0; i<length; i++) {
                feedData[i].image = getFeedBoxImageSrc(feedData[i].description);
                html += getFeedBoxHtml(feedData[i]);
            }

            // Add image HTML to the pageNum.
            $(container).append(html);
            // Apply layout.
            applyLayout();
        }

        // Capture scroll event.
        $(document).unbind('scroll').bind('scroll', onScroll);
        // Load first data from the API.
        loadData();
    }

    function bindEvent() {
        $('#feed_list_panel > li > .clip-icon-circle').unbind('click').click(function() {
            var $feedItem = $(this).parent();
            var clipId = $('.myclip_title').data('id');
            var feed = { feed: $feedItem.data('id') };

            if ($(this).hasClass('on')) {
                $(this).removeClass('on');
                HttpUtil.putData('/clip/update/id/'+clipId+'/remove/feed', feed, function(err, result) {
                    if (err) return alert(err);
                    console.log("success");
                });
            } else {
                $(this).addClass('on');
                HttpUtil.putData('/clip/update/id/'+clipId+'/add/feed', feed, function(err, result) {
                    if (err) return alert(err);
                    console.log("success");
                });
            }
            return false;
        });
    }

    function getFeedBoxImageSrc(description) {
        var defaultImageSrc = '/images/card_no_image.png';
        if (!description) return defaultImageSrc;
        return $(description).find('img').first().attr('src') || defaultImageSrc;
    }

    function getFeedBoxHtml(feed) {
        var html =
            '
'+
            ''+
            ''+
            ''+
            '
'+
            ''+
            '
'+
            '
'+
            '
'+feed.title+'
'+
            '
'+
            '
'+
            '
'+
            ''+
            ''+feed.keywordString+
            ''+
            '
'+
            '
';
        if (feed.isCliped) {
            html += '';
        }
        html += '
'+
            '
'+
            '
';
        return html;
    }

    function resetWookmark() {
        pageNum = 0;
        isCompleteLoading = false;
        isLoading = false;
        $(container).empty();
        initWookmark();
    }

    function clearBoardList() {
        $('.boards > .board').remove();
    }

    $(document).ready(function() {
        init();
    });
}());

<|endoftext|>