<commit_before>/* jshint esnext: true */
(function() {
  "use strict";

  let electron = require("electron");
  let app = electron.app;
  const ipcMain = require("electron").ipcMain;
  let crashReporter = require("crash-reporter");
  let BrowserWindow = require("browser-window");
  let noble = require("noble");
  let bunyan = require("bunyan");
  const util = require("util");

  const storage = require("node-persist");

  crashReporter.start({
    productName: "bulb",
    companyName: "FooBar",
    submitURL: "http://localhost:3000/",
    autoSubmit: true
  });

  let log = bunyan.createLogger({
    name: "bulb"
  });

  var mainWindow = null;

  var storedDevices = {};

  var types = {
    COLOR: {
        colorUuid: "0018",
        effectsUuid: "0016",
        modes: {
            FLASH: 0,
            PULSE: 1,
            RAINBOWJUMP: 2,
            RAINBOWFADE: 3
        },
        nameUuid: "001c"
    },
    CANDLE: {
        colorUuid: "fffc",
        effectsUuid: "fffb",
        modes: {
            FADE: 0,
            JUMPRGB: 1,
            FADERGB: 2,
            FLICKER: 3
        },
        nameUuid: "2a00"
    }
};

  log.info("__dirname", __dirname + "/../data/");
  // initialise storage
  storage.initSync({
    dir: __dirname + "/../data/device-storage",
    stringify: JSON.stringify,
    parse: JSON.parse,
    encoding: "utf8",
    logging: false,
    continuous: true,
    interval: false,
    ttl: false
  });

  // load all currently stored devices
  function loadDevicesFromStorage() {
    let storedDeviceKeys = storage.keys();
    storedDeviceKeys.forEach((uuid, index) => {

      let storedDevice = storage.getItem(uuid, (error, device) => {
        if (error) {
          console.error(error);
        }
      });

      log.info("loadDevicesFromStorage: StoredDevice UUID", storedDevice.uuid);

      storedDevice.stored = true;
      storedDevice.power = false;
      storedDevices[uuid] = storedDevice;
    });
    return storedDevices;
  }

  ipcMain.on("crash", (event, arg) => {
    log.info("Crash", arg);
    process.crash(arg);
  });

  ipcMain.on("devTools", (event, arg) => {
    log.info("DevTools", arg);
    mainWindow.openDevTools();
  });

  app.on("window-all-closed", () => {
    // force app termination on OSX when mainWindow has been closed
    if (process.platform == "darwin") {
      app.quit();
    }
  });

  app.on("ready", () => {
    log.info("App Ready");
    mainWindow = new BrowserWindow({
      width: 2000,
      // width: 1000,
      height: 1200,
      // x: 2560,
      x: 4000,
      // x: 300,
      y: 100
    });

    var webContents = mainWindow.webContents;

    webContents.openDevTools();

    webContents.on("did-finish-load", (ev) => {

      log.info("Did Finish Load");
      // noble.on("stateChange", (state) => {
        if (noble.state === "poweredOn") {
          setTimeout(() => {
            noble.startScanning();
            log.info("Noble State = poweredOn - Sending scanning");
            webContents.send("scanning");
          }, 1500);

        }
      // });
    });

    ipcMain.on("get-stored-devices", event => {
      let storedDeviceKeys = storage.keys();
      log.info("Stored Devices Requested by renderer");
      let devicesFromStorage = loadDevicesFromStorage();

      for (var uuid in devicesFromStorage) {
        if (devicesFromStorage.hasOwnProperty(uuid)) {
          event.sender.send("get-stored-devices-reply", devicesFromStorage[uuid], uuid);
        }
      }
    });

    ipcMain.on("scan.start", () => {
      // Start scanning only if already powered up.
      if (noble.state === "poweredOn") {
        log.info("Starting scan... ");
        noble.startScanning();
      }
    });

    ipcMain.on("scan.stop", () => {
      // Stop scanning for devices.
      log.info("Stopping scan...");
      noble.stopScanning();
    });

    ipcMain.on("device.connect", (event, deviceUUID) => {
      connect(deviceUUID);
    });

    ipcMain.on("device.characteristics.get", (event, deviceUUID) => {

      let device = storedDevices[deviceUUID];
      log.info("device.characteristics.get", deviceUUID, device);
      device.discoverAllServicesAndCharacteristics((error, services, characteristics) => {
        if (error) {
          console.error(error);
        }
        log.info(">>>>>>>>>>>>>>>>> services", services, ">>>>>>>>>>>>>> characteristics", characteristics);

      });
    });

    ipcMain.on("device.characteristic.get", (event, deviceUUID, characteristic) => {
      log.info("device.characteristic.get", deviceUUID, characteristic);
    });

    ipcMain.on("device.set-name", (event, uuid, name) => {
      log.info("device.set-name", uuid, name, nameChar);
      var data = new Buffer(name);
      nameChar.write(data, true, error => {
        if (error) {
          console.error("Write Error");
        }

        connect(uuid);
        storedDevices[uuid].name = name;
        storedDevices[uuid].advertisement.advertisement = name;
        log.info("))))))))))))))))))))", storedDevices[uuid], ")))))))))))))))))))))", serializeDevice(storedDevices[uuid]), "((((((((((((((((()))))))))))))))))");
        storage.setItem(uuid, serializeDevice(storedDevices[uuid]), error => {
          if (error) {
            log.info("Storage error: on name change", error);
          }
        });
      });
      // nameChar.once("write", true, arg => {
        // update storage and local devices
        // log.info(/*storedDevices[uuid], */storedDevices[uuid].advertisement);

      // });
    });

    ipcMain.on("device.get", (event, uuid) => {
      log.info(event, uuid, storedDevices[uuid]);
    });

    noble.on("discover", device => {

      if (typeof device.advertisement.manufacturerData !== "undefined") {
        log.info("discovered manufacturerData", device.uuid);
        if (device.advertisement.manufacturerData.toString("hex") === "4d49504f57") {

          // on discovery check if device is in stored devices, if not update stored
          let match = storage.valuesWithKeyMatch(device.uuid);
          // log.info(">>>>>>>>>>>>>> Match", match);
          if (match.length === 0) {
            log.info("Adding device to storage");
            let serializedDevice = serializeDevice(device);
            log.info("serializedDevice", serializedDevice);
            storage.setItem(device.uuid, serializedDevice, error => {
              if (error) {
                log.info("Storage error: ", error);
              }
            });
          }
          device.stored = true;
          device.power = true;
          // check if device is in the local variable and update storted devices local variable with some extra data (powered on etc)
          if (!(device.uuid in storedDevices)) {
            log.info("Device " + device.uuid + " not in local variable");
          }
          storedDevices[device.uuid] = device;

          // log.info(webContents);
          // send notification to renderer that a device has been dicovered
          let serializedDevice = serializeDevice(device);
          log.info("Sending discovered device to renderer", device.uuid);
          webContents.send("discovered", serializedDevice);

          // add listeners for service and characteristic discovery
          device.on("servicesDiscover", mapDiscoveredService);

        }
        log.info("===========================================");
      }
    });

    function getDeviceFromUUID(uuid) {
      return storedDevices[uuid];
    }

    function connect(uuid) {
      noble.stopScanning();
      log.info("Connect: deviceUUID", uuid);
      let device = getDeviceFromUUID(uuid);
      if (typeof device.connect === "function") {
        device.connect(error => {
          if (error) {
            log.error("Connect error", error);
          } else {
            log.info("Connected to device: ", uuid);
            // send message to notify of connection
            webContents.send("connected", serializeDevice(device));
            device.discoverAllServicesAndCharacteristics(error => {
              if (error) {
                console.error(error);
              }
            });
          }
        });
      } else {
        log.info("Device not found");
      }

    }

    function disconnect(uuid) {
      let device = getDeviceFromUUID(uuid);

      device.disconnect(error => {
        if (error) {
          console.error();
        }
      });
    }

    function mapDiscoveredService(services) {
      log.info("#######################################");
      log.info("#######################################");
      services.map(service => {
        log.info("mapDiscoveredService: service", service.uuid, service.name);
        service.on("characteristicsDiscover", mapDiscoveredCharacteristics);
      });
    }
    var colorChar = null,
        effectsChar = null,
        nameChar = null;

    function mapDiscoveredCharacteristics(characteristics) {
      characteristics.map(characteristic => {
        // log.info("#######################################");
        // log.info("mapDiscoveredCharacteristics: characteristics", characteristics);
        characteristics.map(characteristic => {
          // log.info("         ");
          // log.info("************* ", characteristic.uuid, characteristic.name);
          // log.info("         ");
          if (characteristic.uuid === types.CANDLE.colorUuid) {
            colorChar = characteristic;
          } else if (characteristic.uuid === types.CANDLE.effectsUuid) {
            effectsChar = characteristic;
          } else if (characteristic.uuid === types.CANDLE.nameUuid) {
           nameChar = characteristic;
         }
        });

        log.info("+++++ color characteristic", util.inspect(colorChar, { showHidden: true, depth: 5 }));
        log.info("+++++ effects characteristic", util.inspect(effectsChar, { showHidden: true, depth: 5 }));
        log.info("+++++ name characteristic", util.inspect(nameChar, { showHidden: true, depth: 5 }));
        // storedDevices[deviceUUID].services = services;
        // let serializedServices = serializeServices(deviceUUID);

        // event.sender.send("services", {deviceUUID: device.uuid, services: serializeServices(services)});
        // event.sender.send("characteristics", {deviceUUID: device.uuid, characteristics: characteristics});
      });
    }

    mainWindow.loadURL("file://" + __dirname + "/../browser/index.html");
    mainWindow.webContents.on("did-finish-load", () => {
      log.info("Window Did Load");
      mainWindow.setTitle(app.getName());
    });
    mainWindow.on("closed", () => {
      log.info("Window Closed");
      mainWindow = null;
    });

    function serializeDevice(device) {
      // Prepare a Noble device for serialization to send to a renderer process.
      // Copies out all the attributes the renderer might need.  Seems to be
      // necessary as Noble"s objects don"t serialize well and lose attributes when
      // pass around with the ipc class.
      // log.info("Serializing device", device);
      return {
        id: device.id,
        name: device.advertisement.localName,
        address: device.address,
        state: device.state,
        advertisement: device.advertisement,
        rssi: device.rssi,
        uuid: device.uuid,
        addressType: device.addressType,
        connectable: device.connectable,
        power: device.power || false,
        stored: device.stored || false,
        lastSeen: Date.now()
      };
    }

    function serializeServices(uuid) {
      // Prepare all the services & characteristics for a device to be serialized
      // and sent to the rendering process.  This will be an array of service objects
      // where each one looks like:
      //  { uuid: <service uuid, either short or long>,
      //    name: <friendly service name, if known>,
      //    type: <service type, if known>
      //    characteristics: [<list of characteristics (see below)>] }
      //
      // For each service its characteristics attribute will be a list of
      // characteristic objects that look like:
      //  { uuid: <char uuid>,
      //    name: <char name, if known>
      //    type: <char type, if known>
      //    properties: [<list of properties for the char>],
      //    value: <last known characteristic value, or undefined if not known>
      //  }
      let device = storedDevices[uuid];
      log.info("serializeServices", device);
      let services = device.services.map(s => {
        return {
          uuid: s.uuid,
          name: s.name,
          type: s.type,
          characteristics: s.characteristics.map(c => {
            return {
              uuid: c.uuid,
              name: c.name,
              type: c.type,
              properties: c.properties
            };
          })
        };
      });
      return services;
    }
  });

  // function disconnectAll() {
  //
  // }

  app.on("quit", function() {
    // Make sure device is disconnected before exiting.
    // disconnectAll();
  });
})();
<commit_msg>investigating reading and writing characteristics<commit_after>/* jshint esnext: true */
(function() {
  "use strict";

  let electron = require("electron");
  let app = electron.app;
  const ipcMain = require("electron").ipcMain;
  let crashReporter = require("crash-reporter");
  let BrowserWindow = require("browser-window");
  let noble = require("noble");
  let bunyan = require("bunyan");
  const util = require("util");

  const storage = require("node-persist");

  crashReporter.start({
    productName: "bulb",
    companyName: "FooBar",
    submitURL: "http://localhost:3000/",
    autoSubmit: true
  });

  let log = bunyan.createLogger({
    name: "bulb"
  });

  var mainWindow = null;

  var storedDevices = {};

  var types = {
    COLOR: {
        colorUuid: "0018",
        effectsUuid: "0016",
        modes: {
            FLASH: 0,
            PULSE: 1,
            RAINBOWJUMP: 2,
            RAINBOWFADE: 3
        },
        nameUuid: "001c"
    },
    CANDLE: {
        colorUuid: "fffc",
        effectsUuid: "fffb",
        modes: {
            FADE: 0,
            JUMPRGB: 1,
            FADERGB: 2,
            FLICKER: 3
        },
        nameUuid: "2a00"
    }
};

  log.info("__dirname", __dirname + "/../data/");
  // initialise storage
  storage.initSync({
    dir: __dirname + "/../data/device-storage",
    stringify: JSON.stringify,
    parse: JSON.parse,
    encoding: "utf8",
    logging: false,
    continuous: true,
    interval: false,
    ttl: false
  });

  // load all currently stored devices
  function loadDevicesFromStorage() {
    let storedDeviceKeys = storage.keys();
    storedDeviceKeys.forEach((uuid, index) => {

      let storedDevice = storage.getItem(uuid, (error, device) => {
        if (error) {
          console.error(error);
        }
      });

      log.info("loadDevicesFromStorage: StoredDevice UUID", storedDevice.uuid);

      storedDevice.stored = true;
      storedDevice.power = false;
      storedDevices[uuid] = storedDevice;
    });
    return storedDevices;
  }

  ipcMain.on("crash", (event, arg) => {
    log.info("Crash", arg);
    process.crash(arg);
  });

  ipcMain.on("devTools", (event, arg) => {
    log.info("DevTools", arg);
    mainWindow.openDevTools();
  });

  app.on("window-all-closed", () => {
    // force app termination on OSX when mainWindow has been closed
    if (process.platform == "darwin") {
      app.quit();
    }
  });

  app.on("ready", () => {
    log.info("App Ready");
    mainWindow = new BrowserWindow({
      width: 2000,
      // width: 1000,
      height: 1200,
      // x: 2560,
      // x: 4000,
      x: 560,
      y: 100
    });

    var webContents = mainWindow.webContents;

    webContents.openDevTools();

    webContents.on("did-finish-load", (ev) => {

      log.info("Did Finish Load");
      // noble.on("stateChange", (state) => {
        if (noble.state === "poweredOn") {
          setTimeout(() => {
            noble.startScanning();
            log.info("Noble State = poweredOn - Sending scanning");
            webContents.send("scanning");
          }, 1500);

        }
      // });
    });

    ipcMain.on("get-stored-devices", event => {
      let storedDeviceKeys = storage.keys();
      log.info("Stored Devices Requested by renderer");
      let devicesFromStorage = loadDevicesFromStorage();

      for (var uuid in devicesFromStorage) {
        if (devicesFromStorage.hasOwnProperty(uuid)) {
          event.sender.send("get-stored-devices-reply", devicesFromStorage[uuid], uuid);
        }
      }
    });

    ipcMain.on("scan.start", () => {
      // Start scanning only if already powered up.
      if (noble.state === "poweredOn") {
        log.info("Starting scan... ");
        noble.startScanning();
      }
    });

    ipcMain.on("scan.stop", () => {
      // Stop scanning for devices.
      log.info("Stopping scan...");
      noble.stopScanning();
    });

    ipcMain.on("device.connect", (event, deviceUUID) => {
      connect(deviceUUID);
    });

    ipcMain.on("device.characteristics.get", (event, deviceUUID) => {

      let device = storedDevices[deviceUUID];
      log.info("device.characteristics.get", deviceUUID, device);
      device.discoverAllServicesAndCharacteristics((error, services, characteristics) => {
        if (error) {
          console.error(error);
        }
        log.info(">>>>>>>>>>>>>>>>> services", services, ">>>>>>>>>>>>>> characteristics", characteristics);

      });
    });

    ipcMain.on("device.characteristic.get", (event, deviceUUID, characteristic) => {
      log.info("device.characteristic.get", deviceUUID, characteristic);
    });

    ipcMain.on("device.set-name", (event, uuid, name) => {
      log.info("device.set-name", uuid, name, nameChar);
      var data = new Buffer(name);
      nameChar.write(data, true, error => {
        if (error) {
          console.error("Write Error");
        }

        connect(uuid);
        storedDevices[uuid].name = name;
        storedDevices[uuid].advertisement.advertisement = name;
        log.info("))))))))))))))))))))", storedDevices[uuid], ")))))))))))))))))))))", serializeDevice(storedDevices[uuid]), "((((((((((((((((()))))))))))))))))");
        storage.setItem(uuid, serializeDevice(storedDevices[uuid]), error => {
          if (error) {
            log.info("Storage error: on name change", error);
          }
        });
      });
      // nameChar.once("write", true, arg => {
        // update storage and local devices
        // log.info(/*storedDevices[uuid], */storedDevices[uuid].advertisement);

      // });
    });

    ipcMain.on("device.get", (event, uuid) => {
      log.info(event, uuid, storedDevices[uuid]);
    });

    noble.on("discover", device => {

      if (typeof device.advertisement.manufacturerData !== "undefined") {
        log.info("Discovered device with UUID", device.uuid);
        if (device.advertisement.manufacturerData.toString("hex") === "4d49504f57") {
          log.info("Device matches mipow device");
          // on discovery check if device is in stored devices, if not update stored
          let match = storage.valuesWithKeyMatch(device.uuid);
          if (match.length === 0) {
            log.info("Adding device to storage");
            let serializedDevice = serializeDevice(device);
            log.info("serializedDevice", serializedDevice);
            storage.setItem(device.uuid, serializedDevice, error => {
              if (error) {
                log.info("Storage error: ", error);
              }
            });
          }
          device.stored = true;
          device.power = true;
          // check if device is in the local variable and update storted devices local variable with some extra data (powered on etc)
          if (!(device.uuid in storedDevices)) {
            log.info("Device " + device.uuid + " not in local variable");
          }
          storedDevices[device.uuid] = device;

          // log.info(webContents);
          // send notification to renderer that a device has been dicovered
          let serializedDevice = serializeDevice(device);
          log.info("Sending discovered device to renderer", device.uuid);
          webContents.send("discovered", serializedDevice);

          // add listeners for service and characteristic discovery
          device.once("servicesDiscover", mapDiscoveredService.bind(this, device.uuid));

        }
        log.info("===========================================");
      }
    });

    function getDeviceFromUUID(uuid) {
      return storedDevices[uuid];
    }

    function connect(uuid) {
      noble.stopScanning();
      log.info("Connect: deviceUUID", uuid);
      let device = getDeviceFromUUID(uuid);
      if (typeof device.connect === "function") {
        device.connect(error => {
          if (error) {
            log.error("Connect error", error);
          } else {
            log.info("Connected to device: ", uuid);
            // send message to notify of connection
            webContents.send("connected", serializeDevice(device));

            // @TODO fix up to use generic arrays for candle and color
            let serviceUUIDs = ["1800", "ff02"];
            let characteristicUUIDs = ["2a00", "fffb", "fffc"];
            device.discoverSomeServicesAndCharacteristics(serviceUUIDs, characteristicUUIDs, error => {

              log.info("Discovering services and characteristics on connect");
              if (error) {
                console.error("discoverAllServicesAndCharacteristics", error);
              }
            });
          }
        });
      } else {
        log.info("Device not found");
      }

    }

    function disconnect(uuid) {
      let device = getDeviceFromUUID(uuid);

      device.disconnect(error => {
        if (error) {
          console.error();
        }
      });
    }

    function mapDiscoveredService(deviceUUID, services) {
      log.info("UUIDUUIDUUID", deviceUUID, services);
      log.info("SERVICES START #######################################");
      services.map(service => {
        log.info("mapDiscoveredService: service", service.deviceUUID, service.name);
        service.once("characteristicsDiscover", mapDiscoveredCharacteristics.bind(this, deviceUUID));
      });
      log.info("SERVICES END #######################################");
    }

    var colorChar = null,
        effectsChar = null,
        nameChar = null;

    function mapDiscoveredCharacteristics(deviceUUID, characteristics) {

      log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", deviceUUID);
      characteristics.map(characteristic => {
          if (characteristic.uuid === types.CANDLE.colorUuid) {
            colorChar = characteristic;
            log.info("+++++ color characteristic", util.inspect(colorChar, { showHidden: true, depth: 2 }));
            colorChar.read((error, data) => {
              if (error) {
                log.error("Could not read characteristic", error);
              }
              log.info("color Char data", data.toJSON());
              // let r = Math.floor(Math.random() * 256);
              // let g = Math.floor(Math.random() * 256);
              // let b = Math.floor(Math.random() * 256);
              // log.info("Color", r, g, b);
              // let colorBytes = new Buffer([0, r, g, b]);
              // colorChar.write(colorBytes, true, (error) => {
              //   if (error) {
              //     log.error("Could not color name characteristic");
              //   }
              //   // @TODO update stored device
              //   log.info("Wrote color characteristic");
              // });
            });
          } else if (characteristic.uuid === types.CANDLE.effectsUuid) {
            effectsChar = characteristic;
            log.info("+++++ effects characteristic", util.inspect(effectsChar, { showHidden: true, depth: 2 }));
            effectsChar.read((error, data) => {
              if (error) {
                log.error("Could not read characteristic", error);
              }
              log.info("effects Char data", data.toJSON());
            });
          } else if (characteristic.uuid === types.CANDLE.nameUuid) {
            nameChar = characteristic;
            log.info("+++++ name characteristic", util.inspect(nameChar, { showHidden: true, depth: 2 }));
            nameChar.read((error, data) => {
            if (error) {
              log.error("Could not read characteristic", error);
            }
            log.info("name Char data", data.toString());
            // nameChar.write(new Buffer("hello"), false, (error) => {
            //   if (error) {
            //     log.error("Could not write name characteristic");
            //   }
            //   // @TODO update stored device
            //   log.info("Wrote name characteristic");
            // });
           });
          }

        // storedDevices[deviceUUID].services = services;
        // let serializedServices = serializeServices(deviceUUID);

        // event.sender.send("services", {deviceUUID: device.uuid, services: serializeServices(services)});
        // event.sender.send("characteristics", {deviceUUID: device.uuid, characteristics: characteristics});
      });
      log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
    }

    mainWindow.loadURL("file://" + __dirname + "/../browser/index.html");
    mainWindow.webContents.on("did-finish-load", () => {
      log.info("Window Did Load");
      mainWindow.setTitle(app.getName());
    });
    mainWindow.on("closed", () => {
      log.info("Window Closed");
      mainWindow = null;
    });

    function serializeDevice(device) {
      // Prepare a Noble device for serialization to send to a renderer process.
      // Copies out all the attributes the renderer might need.  Seems to be
      // necessary as Noble"s objects don"t serialize well and lose attributes when
      // pass around with the ipc class.
      // log.info("Serializing device", device);
      return {
        id: device.id,
        name: device.advertisement.localName,
        address: device.address,
        state: device.state,
        advertisement: device.advertisement,
        rssi: device.rssi,
        uuid: device.uuid,
        addressType: device.addressType,
        connectable: device.connectable,
        power: device.power || false,
        stored: device.stored || false,
        lastSeen: Date.now()
      };
    }

    function serializeServices(uuid) {
      // Prepare all the services & characteristics for a device to be serialized
      // and sent to the rendering process.  This will be an array of service objects
      // where each one looks like:
      //  { uuid: <service uuid, either short or long>,
      //    name: <friendly service name, if known>,
      //    type: <service type, if known>
      //    characteristics: [<list of characteristics (see below)>] }
      //
      // For each service its characteristics attribute will be a list of
      // characteristic objects that look like:
      //  { uuid: <char uuid>,
      //    name: <char name, if known>
      //    type: <char type, if known>
      //    properties: [<list of properties for the char>],
      //    value: <last known characteristic value, or undefined if not known>
      //  }
      let device = storedDevices[uuid];
      log.info("serializeServices", device);
      let services = device.services.map(s => {
        return {
          uuid: s.uuid,
          name: s.name,
          type: s.type,
          characteristics: s.characteristics.map(c => {
            return {
              uuid: c.uuid,
              name: c.name,
              type: c.type,
              properties: c.properties
            };
          })
        };
      });
      return services;
    }
  });

  // function disconnectAll() {
  //
  // }

  app.on("quit", function() {
    // Make sure device is disconnected before exiting.
    // disconnectAll();
  });
})();
<|endoftext|>


<commit_before>import Vue from 'vue'
import Router from 'vue-router'
import HomeLayout from '@/layouts/HomeLayout'
import CreateWalletLayout from '@/layouts/CreateWalletLayout'
import TeamLayout from '@/layouts/TeamLayout'
import PrivacyPolicyLayout from '@/layouts/PrivacyPolicyLayout'
import TermsOfConditionsLayout from '@/layouts/TermsOfConditionsLayout'
import AccessWalletLayout from '@/layouts/AccessWalletLayout'
import InterfaceLayout from '@/layouts/InterfaceLayout'
import HelpCenterLayout from '@/layouts/HelpCenterLayout'
import NotFoundLayout from '@/layouts/NotFoundLayout'
import CreateWalletWarningLayout from '@/layouts/CreateWalletWarningLayout'
import {router as routerConfig} from '@/configs/build'

Vue.use(Router)

export default new Router({
  mode: routerConfig.mode,
  routes: [
    {
      path: '/',
      name: 'Home',
      component: HomeLayout
    },
    {
      path: '/create-wallet',
      name: 'CreateWalletLayout',
      component: CreateWalletLayout
    },
    {
      path: '/team',
      name: 'TeamLayout',
      component: TeamLayout
    },
    {
      path: '/privacy-policy',
      name: 'PrivacyPolicyLayout',
      component: PrivacyPolicyLayout
    },
    {
      path: '/terms-of-conditions',
      name: 'TermsOfConditionsLayout',
      component: TermsOfConditionsLayout
    },
    {
      path: '/access-my-wallet',
      name: 'AccessWalletLayout',
      component: AccessWalletLayout
    },
    {
      path: '/interface',
      name: 'InterfaceLayout',
      component: InterfaceLayout
    },
    {
      path: '/help-center',
      name: 'HelpCenterLayout',
      component: HelpCenterLayout
    },
    {
      path: '/mew-intro',
      name: 'CreateWalletWarningLayout',
      component: CreateWalletWarningLayout
    },
    {
      path: '*',
      name: '404',
      component: NotFoundLayout
    }
  ],
  scrollBehavior (to, from, savedPosition) {
    if (to.hash) {
      return {
        selector: to.hash
      }
    } else {
      window.scrollTo(0, 0)
    }
  }
})
<commit_msg>Router link update /getting-started<commit_after>import Vue from 'vue'
import Router from 'vue-router'
import HomeLayout from '@/layouts/HomeLayout'
import CreateWalletLayout from '@/layouts/CreateWalletLayout'
import TeamLayout from '@/layouts/TeamLayout'
import PrivacyPolicyLayout from '@/layouts/PrivacyPolicyLayout'
import TermsOfConditionsLayout from '@/layouts/TermsOfConditionsLayout'
import AccessWalletLayout from '@/layouts/AccessWalletLayout'
import InterfaceLayout from '@/layouts/InterfaceLayout'
import HelpCenterLayout from '@/layouts/HelpCenterLayout'
import NotFoundLayout from '@/layouts/NotFoundLayout'
import CreateWalletWarningLayout from '@/layouts/CreateWalletWarningLayout'
import {router as routerConfig} from '@/configs/build'

Vue.use(Router)

export default new Router({
  mode: routerConfig.mode,
  routes: [
    {
      path: '/',
      name: 'Home',
      component: HomeLayout
    },
    {
      path: '/create-wallet',
      name: 'CreateWalletLayout',
      component: CreateWalletLayout
    },
    {
      path: '/team',
      name: 'TeamLayout',
      component: TeamLayout
    },
    {
      path: '/privacy-policy',
      name: 'PrivacyPolicyLayout',
      component: PrivacyPolicyLayout
    },
    {
      path: '/terms-of-conditions',
      name: 'TermsOfConditionsLayout',
      component: TermsOfConditionsLayout
    },
    {
      path: '/access-my-wallet',
      name: 'AccessWalletLayout',
      component: AccessWalletLayout
    },
    {
      path: '/interface',
      name: 'InterfaceLayout',
      component: InterfaceLayout
    },
    {
      path: '/help-center',
      name: 'HelpCenterLayout',
      component: HelpCenterLayout
    },
    {
      path: '/getting-started',
      name: 'CreateWalletWarningLayout',
      component: CreateWalletWarningLayout
    },
    {
      path: '*',
      name: '404',
      component: NotFoundLayout
    }
  ],
  scrollBehavior (to, from, savedPosition) {
    if (to.hash) {
      return {
        selector: to.hash
      }
    } else {
      window.scrollTo(0, 0)
    }
  }
})
<|endoftext|>


<commit_before>/*
 |--------------------------------------------------------------------------
 |   Airflix
 |--------------------------------------------------------------------------
 */

import Vue from 'vue'
import VueInfiniteScroll from 'vue-infinite-scroll'
import VueRouter from 'vue-router'
import VueResource from 'vue-resource'
import VueMoment from 'vue-moment'
import store from './vuex/store'
import { filterByGenre, filterByHasMovies, filterByHasShows, zeroPad } from './filters'
import { configRouter } from './routes'
import { sync } from 'vuex-router-sync'
import App from './components/App.vue'

// Debug mode
Vue.config.debug = false

// Devtools enabled
Vue.config.devtools = false

// Silence logs and warnings
Vue.config.silent = true

// install resource
Vue.use(VueResource)

Vue.http.headers.common['Accept'] =
  'application/vnd.api+json; version=1; charset=utf-8'

// install infinite scoll
Vue.use(VueInfiniteScroll)

// install router
Vue.use(VueRouter)

// install vue-moment filter
Vue.use(VueMoment)

// register filters globally
Vue.filter('filterByGenre', filterByGenre)
Vue.filter('filterByHasMovies', filterByHasMovies)
Vue.filter('filterByHasShows', filterByHasShows)
Vue.filter('zeroPad', zeroPad)

// create router
var router = new VueRouter({
  history: true,
  saveScrollPosition: true
})

// synchronize vue-router routes with vuex
sync(store, router)

// configure router
configRouter(router)

// boostrap the app
router.start(App, '#app')
<commit_msg>Update app.js file to use new dependency versions.<commit_after>/*
 |--------------------------------------------------------------------------
 |   Airflix
 |--------------------------------------------------------------------------
 */

import Vue from 'vue'
import _ from 'lodash'
import Promise from 'es6-promise'
import VueRouter from 'vue-router'
import VueMoment from 'vue-moment'
import axios from 'axios'
import store from './vuex/store'
import { zeroPad } from './filters'
import { routes } from './routes'
import { sync } from 'vuex-router-sync'
import App from './components/App.vue'

// Devtools enabled
Vue.config.devtools = false

// Silence logs and warnings
Vue.config.silent = true

// install lodash
window._ = _

// install axios
window.axios = axios

axios.defaults.headers.common['Accept'] =
  'application/vnd.api+json; version=1; charset=utf-8'

// install router
Vue.use(VueRouter)

// install vue-moment filter
Vue.use(VueMoment)

// register filters globally
Vue.filter('zeroPad', zeroPad)

// create router
const router = new VueRouter({
  mode: 'history',
  routes
})

// synchronize vue-router routes with vuex
sync(store, router)

window.vueRouter = router

const app = new Vue({
	router,
	store,
	...App
}).$mount('#app')
<|endoftext|>


<commit_before>require('newrelic');
var express = require('express');
var jsdom = require("jsdom");
var request = require('request');
var db = require('./config/db');
var Posts = require('./models/posts');
var Comments = require('./models/comments');

var app = express();

var BASE_URL = 'http://www.producthunt.com';

app.configure(function (){
  app.set('port', process.env.PORT || 8888);
  app.use(express.cookieParser('keyboard cat'));
  app.use(express.session({ secret: 'keyboard cat' }));
  app.use(app.router);
});

app.get('/', function (req, res) {
  res.redirect('https://github.com/karan/Hook');
});

app.get('/today', function (req, res) {

  var today = new Date().toJSON().slice(0,10);

  Posts.findOne({date: today}, function (err, obj) {

    if (obj && obj.expires < Date.now()) {
      // post expired, scrape again, and save
      console.log("posts expired - " + today);
      getPostDetails(null, function (posts) {
        Posts.findOneAndUpdate({date: today}, {posts: posts, expires: new Date(Date.now() + 60*60*1000)}, {new: true}, function (err, newObj) {
          res.send(200, {
            status: 'success',
            hunts: posts
          });
        });
      });
    } else if (obj) {
      console.log("posts not expired - " + today);
      // not expired, just return this
      res.send(200, {
        status: 'success',
        hunts: obj.posts
      });
    } else {
      // not in the db, scrape and send
      console.log("posts not found in db - " + today);

      getPostDetails(null, function (posts) {
        console.log("got details");
        new Posts({
          date: today,
          posts: posts
        }).save(function (err) {
          res.send(200, {
            status: 'success',
            hunts: posts
          });
        });
      });

    }

  });

});

app.get("/posts/:slug", function (req, res) {

  var post_url = '/posts/'+req.params.slug;

  Comments.findOne({'permalink': post_url}, function(err, commentobj) {

    if (commentobj && commentobj.expires < Date.now()) {
      // expired. Scrape again, save and send
      getPostDetails(post_url, function (post) {
        post = post[0];
        getComments(post_url, function (err, comments, related) {
          Comments.findOneAndUpdate({permalink: post_url}, {post: post, comments: comments, expires: new Date(Date.now() + 2*60*60*1000)}, function (err, newObj) {
            res.send(200, {
              status: 'success',
              post: post,
              comments: comments
            });
          });
        });
      });
    } else if (commentobj) {
      // not expired, just send response
      res.send(200, {
        status: 'success',
        post: commentobj.post,
        comments: commentobj.comments
      });
    } else {
      // not in db, scrape, save and send
      getPostDetails(post_url, function (post) {
        post = post[0];
        getComments(post_url, function (err, comments, related) {
          new Comments({
            post: post,
            permalink: post.permalink,
            comments: comments
          }).save(function(err) {
            res.send(200, {
              status: 'success',
              post: post,
              comments: comments
            });
          });
        });
      });

    }

  });

});

function getComments(url, callback) {

  jsdom.env(
    BASE_URL+url,
    ["http://code.jquery.com/jquery.js"],
    function (errors, window) {
      var $ = window.$;

      var comments = [];

      var comments_dom = $(".modal-container").find(".comment");

      if (comments_dom.length === 0) {
        return callback(null, comments);
      }

      comments_dom.each(function (index) {
        var name = $(this).find(".comment-user-name a").text();
        var username = $(this).find(".comment-user-handle").text().match(/\(\@(.*)\)/)[1];
        var timestamp = $(this).find(".comment-timestamp").text();
        var comment = $(this).find(".comment-body").find(".comment-user-name").remove().end().text();
        var comment_html = $(this).find(".comment-body").find(".comment-user-name").remove().end().html();

        comments.push({
          index: index+1,
          user: {
            username: username,
            name: name
          },
          timestamp: timestamp,
          comment: comment,
          comment_html: comment_html
        });

        if (comments.length === comments_dom.length) {
          callback(null, comments);
        }

      });

    }
  );

}

function getPostDetails(post_url, callback) {
  var url = post_url ? BASE_URL + post_url : BASE_URL;
  console.log(url);
  var posts = [];

  jsdom.env(
    url,
    ["http://code.jquery.com/jquery.js"],
    function (errors, window) {
      var $ = window.$;

      var container = post_url ? $(".modal-container") : null;
      var $ph_posts = post_url ? $(".modal-container .posts-group tr") : $(".today tr");

      $ph_posts.each(function (rank) {

        var votes = +$(this).find(".upvote").text();
        var name = $(this).find("h3.user-name").clone().children().remove().end().text().trim().replace(/"/g, "");
        var username = $(this).find("span.user-handle").text().trim().replace(/"/g, "").match(/\(\@(.*)\)/)[1];
        var title = $(this).find(".post-url").text();
        var tagline = $(this).find(".post-tagline").text();

        if (container) {
          var comment_count = $(container.find(".subhead")[2]).text().trim().match(/(\d+)/g);;
        } else {
          var comment_count = $(this).find(".view-discussion").text().trim().match(/(\d+)/g);
        }
        comment_count = comment_count ? comment_count[0] : 0;

        var permalink = post_url ? post_url : $(this).find(".view-discussion").attr("data-url");

        request({url: BASE_URL+$(this).find(".post-url").attr("href"), followRedirect: false}, function (error, response, body) {
          url = response.headers.location;

          posts.push({
            'title': title,
            'votes': votes,
            'user': {
              'username': username,
              'name': name
            },
            'rank': rank + 1,
            'tagline': tagline,
            'comment_count': comment_count,
            'permalink': permalink,
            'url': url
          });

          if (posts.length === $ph_posts.length) {
            callback(posts);
          }

        });

      });
    }
  );
}

app.listen(app.get('port'));
<commit_msg>start fixing comments page<commit_after>require('newrelic');
var express = require('express');
var jsdom = require("jsdom");
var request = require('request');
var db = require('./config/db');
var Posts = require('./models/posts');
var Comments = require('./models/comments');

var app = express();

var BASE_URL = 'http://www.producthunt.com';

app.configure(function (){
  app.set('port', process.env.PORT || 8888);
  app.use(express.cookieParser('keyboard cat'));
  app.use(express.session({ secret: 'keyboard cat' }));
  app.use(app.router);
});

app.get('/', function (req, res) {
  res.redirect('https://github.com/karan/Hook');
});

app.get('/today', function (req, res) {

  var today = new Date().toJSON().slice(0,10);

  Posts.findOne({date: today}, function (err, obj) {

    if (obj && obj.expires < Date.now()) {
      // post expired, scrape again, and save
      console.log("posts expired - " + today);
      getHomePosts(null, function (posts) {
        Posts.findOneAndUpdate({date: today}, {posts: posts, expires: new Date(Date.now() + 60*60*1000)}, {new: true}, function (err, newObj) {
          res.send(200, {
            status: 'success',
            hunts: posts
          });
        });
      });
    } else if (obj) {
      console.log("posts not expired - " + today);
      // not expired, just return this
      res.send(200, {
        status: 'success',
        hunts: obj.posts
      });
    } else {
      // not in the db, scrape and send
      console.log("posts not found in db - " + today);

      getHomePosts(null, function (posts) {
        console.log("got details");
        new Posts({
          date: today,
          posts: posts
        }).save(function (err) {
          res.send(200, {
            status: 'success',
            hunts: posts
          });
        });
      });

    }

  });

});

app.get("/posts/:slug", function (req, res) {

  var post_url = '/posts/'+req.params.slug;

  Comments.findOne({'permalink': post_url}, function(err, commentobj) {

    if (commentobj && commentobj.expires < Date.now()) {
      // expired. Scrape again, save and send
      getPostDetails(post_url, function (post) {
        post = post[0];
        getComments(post_url, function (err, comments, related) {
          Comments.findOneAndUpdate({permalink: post_url}, {post: post, comments: comments, expires: new Date(Date.now() + 2*60*60*1000)}, function (err, newObj) {
            res.send(200, {
              status: 'success',
              post: post,
              comments: comments
            });
          });
        });
      });
    } else if (commentobj) {
      // not expired, just send response
      res.send(200, {
        status: 'success',
        post: commentobj.post,
        comments: commentobj.comments
      });
    } else {
      // not in db, scrape, save and send
      getPostDetails(post_url, function (post) {
        post = post[0];
        getComments(post_url, function (err, comments, related) {
          new Comments({
            post: post,
            permalink: post.permalink,
            comments: comments
          }).save(function(err) {
            res.send(200, {
              status: 'success',
              post: post,
              comments: comments
            });
          });
        });
      });

    }

  });

});

function getPostDetails(post_url, callback) {
  var url = post_url ? BASE_URL + post_url : BASE_URL;
  console.log(url);

  jsdom.env(
    url,
    ["http://code.jquery.com/jquery.js"],
    function (errors, window) {
      var $ = window.$;

      var header_dom = $(".modal-container").find(".comments-header");

      var votes = +header_dom.find(".vote-count").text()
      var name = header_dom.find(".posted-by").text().trim().replace(/"/g, "");
      var username = header_dom.find(".user-with-tooltip").attr("href").slice(1).trim().replace(/"/g, "").match("Posted\sby\s(.*)\s\d+\shours\sago");
      console.log(username);
      var title = $(this).find(".post-url").text();
      var tagline = $(this).find(".post-tagline").text();

      if (container) {
        var comment_count = $(container.find(".subhead")[2]).text().trim().match(/(\d+)/g);
      } else {
        var comment_count = $(this).find(".view-discussion").text().trim().match(/(\d+)/g);
      }
      comment_count = comment_count ? comment_count[0] : 0;

      var permalink = post_url ? post_url : $(this).find(".view-discussion").attr("data-url");

      request({url: BASE_URL+$(this).find(".post-url").attr("href"), followRedirect: false}, function (error, response, body) {
        url = response.headers.location;

        posts.push({
          'title': title,
          'votes': votes,
          'user': {
            'username': username,
            'name': name
          },
          'rank': rank + 1,
          'tagline': tagline,
          'comment_count': comment_count,
          'permalink': permalink,
          'url': url
        });

        console.log(posts);

        if (posts.length === $ph_posts.length) {
          callback(posts);
        }

      });

    }
  );
}

function getComments(url, callback) {

  jsdom.env(
    BASE_URL+url,
    ["http://code.jquery.com/jquery.js"],
    function (errors, window) {
      var $ = window.$;

      var comments = [];

      var comments_dom = $(".modal-container");

      if (comments_dom.length === 0) {
        return callback(null, comments);
      }

      comments_dom.each(function (index) {
        var name = $(this).find(".comment-user-name a").text();
        var username = $(this).find(".comment-user-handle").text().match(/\(\@(.*)\)/)[1];
        var timestamp = $(this).find(".comment-timestamp").text();
        var comment = $(this).find(".comment-body").find(".comment-user-name").remove().end().text();
        var comment_html = $(this).find(".comment-body").find(".comment-user-name").remove().end().html();

        comments.push({
          index: index+1,
          user: {
            username: username,
            name: name
          },
          timestamp: timestamp,
          comment: comment,
          comment_html: comment_html
        });

        if (comments.length === comments_dom.length) {
          callback(null, comments);
        }

      });

    }
  );

}

function getHomePosts(post_url, callback) {
  var url = post_url ? BASE_URL + post_url : BASE_URL;
  console.log(url);
  var posts = [];

  jsdom.env(
    url,
    ["http://code.jquery.com/jquery.js"],
    function (errors, window) {
      var $ = window.$;

      var container = post_url ? $(".modal-container") : null;
      var $ph_posts = post_url ? $(".modal-container .posts-group tr") : $(".today tr");

      $ph_posts.each(function (rank) {

        var votes = +$(this).find(".upvote").text();
        var name = $(this).find("h3.user-name").clone().children().remove().end().text().trim().replace(/"/g, "");
        var username = $(this).find("span.user-handle").text().trim().replace(/"/g, "").match(/\(\@(.*)\)/)[1];
        var title = $(this).find(".post-url").text();
        var tagline = $(this).find(".post-tagline").text();

        if (container) {
          var comment_count = $(container.find(".subhead")[2]).text().trim().match(/(\d+)/g);;
        } else {
          var comment_count = $(this).find(".view-discussion").text().trim().match(/(\d+)/g);
        }
        comment_count = comment_count ? comment_count[0] : 0;

        var permalink = post_url ? post_url : $(this).find(".view-discussion").attr("data-url");

        request({url: BASE_URL+$(this).find(".post-url").attr("href"), followRedirect: false}, function (error, response, body) {
          url = response.headers.location;

          posts.push({
            'title': title,
            'votes': votes,
            'user': {
              'username': username,
              'name': name
            },
            'rank': rank + 1,
            'tagline': tagline,
            'comment_count': comment_count,
            'permalink': permalink,
            'url': url
          });

          console.log(posts);

          if (posts.length === $ph_posts.length) {
            callback(posts);
          }

        });

      });
    }
  );
}

app.listen(app.get('port'));
<|endoftext|>


<commit_before>//holds the XMLHttpRequest which will be used to dynamically add the days
var request;

$(function(){
	request = new XMLHttpRequest();
	//request.open("GET", "https://mims002.github.io/websiteLayouts/cardStyleCalendar/json/data.json");
	request.open("GET", "json/data.json");

	request.onload = xmlRequestData;

	request.send();

	console.log("ran");

});

function xmlRequestData(){

	if (request.status >= 200 && request.status < 400) {
      var data = JSON.parse(request.responseText);
      renderHTML(data);
    } else {
      console.log("We connected to the server, but it returned an error.");
    }

}

function renderHTML(data) {
  var htmlString = "";

  var day, date, eventDetail, eventLocation, eventTime, eventName, month;

  for(var i=0; i< data.numDays; i++){

	  day = data.daysEntry[i].day;
	  date = data.daysEntry[i].date;
	  eventDetail = data.daysEntry[i].details;
	  eventLocation = data.daysEntry[i].location;
	  eventTime = data.daysEntry[i].time;
	  eventName = data.daysEntry[i].event;
	  month = data.daysEntry[i].month;

	  console.log(eventName);

	  var description = [eventName, eventTime, eventLocation, eventDetail ];

	  createDaysEntry(day,date,month, createDescription(description));

  }

}

function createDescription(d){
	var inner = "";
	var title =["Event: ", "Location: ", "Time: ", "Details: "];
	for(var i=0; i<d.length-1; i++){

		inner +=''+title[i]+"";
		inner += d[i]+"
";

	}
	inner += ''+title[i] + d[i]+ "";

	return inner;
}

function createDaysEntry(day,date,month,description){
	//creates the divs to the calendar entry
	var $divContainer = $("
", {"class":"calendar_entries"});
	var $divDate = $("
", {"class":"calendar_entries_left"});
	var $divInfo = $("
", {"class":"calendar_entries_right"});

	//puts the date and the day together
	$divDate.html(day+"
"+date);

	//puts the description in the correct format
	$divInfo.html(description);

	//appends date and description to the main entry
	$divContainer.append($divDate);
	$divContainer.append($divInfo);

	//adds a unique class to it
	$divContainer.attr({"class":"calendar_entries"},{"class":month},{"class":date});

	//adds it to the website
	addDayInOrder($divContainer,month,day);
	$("#calendar_inner").append($divContainer);

}

function addDayInOrder($divContainer, month, day){

	var l = $("#calendar_inner").children().length;

	//adds the first month if it doesn't exits
	if(l==0){
		var months = '
'+ month +'
';
		$("#calendar_inner").append(months);
	}

	for(var i = 0; i<l; i++){
		console.log($("#calendar_inner").children().find("."+month));
	}

	console.log(l);

}

function msg(msg){
 alert(msg);
}

<commit_msg>layout change<commit_after>//holds the XMLHttpRequest which will be used to dynamically add the days
var request;

$(function(){
	request = new XMLHttpRequest();
	request.open("GET", "https://mims002.github.io/websiteLayouts/cardStyleCalendar/json/data.json");
	//request.open("GET", "json/data.json");

	request.onload = xmlRequestData;

	request.send();

	console.log("ran");

});

function xmlRequestData(){

	if (request.status >= 200 && request.status < 400) {
      var data = JSON.parse(request.responseText);
      renderHTML(data);
    } else {
      console.log("We connected to the server, but it returned an error.");
    }

}

function renderHTML(data) {
  var htmlString = "";

  var day, date, eventDetail, eventLocation, eventTime, eventName, month;

  for(var i=0; i< data.numDays; i++){

	  day = data.daysEntry[i].day;
	  date = data.daysEntry[i].date;
	  eventDetail = data.daysEntry[i].details;
	  eventLocation = data.daysEntry[i].location;
	  eventTime = data.daysEntry[i].time;
	  eventName = data.daysEntry[i].event;
	  month = data.daysEntry[i].month;

	  console.log(eventName);

	  var description = [eventName, eventTime, eventLocation, eventDetail ];

	  createDaysEntry(day,date,month, createDescription(description));

  }

}

function createDescription(d){
	var inner = "";
	var title =["Event: ", "Location: ", "Time: ", "Details: "];
	for(var i=0; i<d.length-1; i++){

		inner +=''+title[i]+"";
		inner += d[i]+"
";

	}
	inner += ''+title[i] + d[i]+ "";

	return inner;
}

function createDaysEntry(day,date,month,description){
	//creates the divs to the calendar entry
	var $divContainer = $("
", {"class":"calendar_entries"});
	var $divDate = $("
", {"class":"calendar_entries_left"});
	var $divInfo = $("
", {"class":"calendar_entries_right"});

	//puts the date and the day together
	$divDate.html(day+"
"+date);

	//puts the description in the correct format
	$divInfo.html(description);

	//appends date and description to the main entry
	$divContainer.append($divDate);
	$divContainer.append($divInfo);

	//adds a unique class to it
	$divContainer.attr({"class":"calendar_entries"},{"class":month},{"class":date});

	//adds it to the website
	addDayInOrder($divContainer,month,day);
	$("#calendar_inner").append($divContainer);

}

function addDayInOrder($divContainer, month, day){

	var l = $("#calendar_inner").children().length;

	//adds the first month if it doesn't exits
	if(l==0){
		var months = '
'+ month +'
';
		$("#calendar_inner").append(months);
	}

	for(var i = 0; i<l; i++){
		console.log($("#calendar_inner").children().find("."+month)==0);
	}

	console.log(l);

}

function msg(msg){
 alert(msg);
}

<|endoftext|>


<commit_before>
var express = require("express")
var router = express.Router()
var ensureLoggedIn = require('connect-ensure-login').ensureLoggedIn();
var fs = require("fs")
var MarkdownIt = require('markdown-it')
var md = new MarkdownIt();
var User = require("../models/db_user")

// will crawl the lesson folder as a tree, finding each *.md and each *.desc
// will convert these into html and store them
function loadLessons()
{
	var dirTree = require('directory-tree');
	var lessonfiles = dirTree('./lessons/',[".md"]);

	var lessontable = {

	}

	for(var lessonblock in lessonfiles.children)
	{
		// new lesson group
		lessontable[lessonblock] = {
			name: lessonfiles.children[lessonblock].name,
			lessons: {

			}
		}

		// load each lesson file with its description and markdown
		for(var i in lessonfiles.children[lessonblock].children)
		{

			var lesson = lessonfiles.children[lessonblock].children[i]

			// load data and desc
			var lesson_markdown = fs.readFileSync(lesson.path,"utf8")
			var lesson_desc = fs.readFileSync(lesson.path.substring(0,lesson.path.length-3) + ".desc","utf8")

 			lessontable[lessonblock].lessons[i] = {
				title: lesson.name.substring(0,lesson.name.length-3),
				markdown: lesson_markdown,
				desc: lesson_desc,
				link: "/learn/" + (parseInt(lessonblock)+1) + "/" + (parseInt(i)+1)
			}

		}
	}

	return lessontable
}

var lessonsTree = undefined

router.getLessonInfo = function(lesson_string)
{
	var lessonsTree = lessonsTree || loadLessons()
	var lessonids = lesson_string.split("/")
	var lessongroup = parseInt(lessonids[0])
	var lessonid = parseInt(lessonids[1])

	var lessongroup = lessonsTree[lessongroup-1]
	if(lessongroup)
	{
		var lesson = lessongroup.lessons[lessonid-1]
		if(lesson)
		{
			return lesson
		}
	}

}

// render overview with lesson tree
router.get("/overview",ensureLoggedIn,function(req,res,next)
{
	lessonsTree = loadLessons()
	console.log(lessonsTree)

	var isLoggedIn = (req.isAuthenticated && req.isAuthenticated())
	res.render("learnoverview",
	{
		title: "Vimmy :: Lesson Overview",
		loggedIn: isLoggedIn,
		user: (isLoggedIn ? req.user.db : { }),
		lessonsTree: lessonsTree
	})
})

// if the user asks for the enxt lesson, check if there is one in the current group or else redirect them to the overview
router.get("/:lessongroup/:lessonid/next", ensureLoggedIn, function(req,res,next)
{
	lessonsTree = loadLessons()

	var lessongroup = lessonsTree[req.params.lessongroup-1]
	if(lessongroup)
	{
		var lesson = lessongroup.lessons[req.params.lessonid-1]
		if(lesson)
		{
			var possible_next_sub_lesson = lessongroup.lessons[req.params.lessonid]
			if(possible_next_sub_lesson)
			{
				var lessonpathid = req.params.lessongroup + "/" + (parseInt(req.params.lessonid)+1)
				res.redirect("/learn/"+lessonpathid)
			}
			else
			{
				res.redirect("/learn/overview")
			}
		}
	}
})

// render lesson
router.get("/:lessongroup/:lessonid", ensureLoggedIn, function(req,res,next)
{
	lessonsTree = loadLessons()
	//console.log(lessonsTree)
	var lessongroup = lessonsTree[req.params.lessongroup-1]

	if(lessongroup)
	{
		var lesson = lessongroup.lessons[req.params.lessonid-1]
		if(lesson)
		{
			// remove existing lesson if its been there before
			// eg. 1/1

			// add the lesson to the recent lessons list of the user
			User.findOne({user_id: req.user.db.user_id}, function(err,user)
				{
					if(user)
					{
						console.log(user)
						var lessonpathid = req.params.lessongroup + "/" + req.params.lessonid
						var index = user.recent_lessons.indexOf(lessonpathid);

						if (index > -1)
						{
							// remove existing lesson if its been there before
							user.recent_lessons.splice(index, 1);
						}

						user.recent_lessons.push(lessonpathid)

						user.save(function(err)
						{
							if(err)
							{
								console.error(err)
								return -1;
							}
						})
					}
				})

			var markdown = md.render(lesson.markdown)

			var isLoggedIn = (req.isAuthenticated && req.isAuthenticated())
			res.render("lesson",
			{
				title: "Vimmy :: Lesson Overview",
				loggedIn: isLoggedIn,
				user: (isLoggedIn ? req.user.db : { }),
				lessonsTree: lessonsTree,
				markdown: markdown
			})

			return
		}
	}

	res.status(404).send("Not Found")
})

module.exports = router<commit_msg>Linted learn.js<commit_after>
let express = require('express')
let router = express.Router()
let ensureLoggedIn = require('connect-ensure-login').ensureLoggedIn()
let fs = require('fs')
let MarkdownIt = require('markdown-it')
let md = new MarkdownIt()
let User = require('../models/db_user')

/*
  Crawl the lessons folder looking for each lesson in a group
  as *.md and *.desc.

  Builds a tree of markdown and desc
*/
function loadLessons() {
  let dirTree = require('directory-tree')

  // get a directory tree of the lessons folder
  let lessonfiles = dirTree('./lessons/',['.md'])

  // our return tree
  let lessontable = {

  }

  // for each directory inside lessons (i.e each category e.g. 1 - The Language)
  for(let lessonblock in lessonfiles.children) {
    // new lesson group (e.g. 1 - The Language)
    lessontable[lessonblock] = {
      name: lessonfiles.children[lessonblock].name,
      lessons: { }
    }

    // load each lesson file with its description and markdown
    // (e.g. 1.1 - The Virtual Machine)
    for(let i in lessonfiles.children[lessonblock].children) {
      let lesson = lessonfiles.children[lessonblock].children[i]

      // load data and desc
      let lesson_markdown = fs.readFileSync(lesson.path,'utf8')

      // desc is filename with .md stripped and + .desc
      let lesson_desc = fs.readFileSync(lesson.path.substring(0,lesson.path.length-3) + '.desc','utf8')

      lessontable[lessonblock].lessons[i] = {
        title: lesson.name.substring(0,lesson.name.length-3), // strip .md
        markdown: lesson_markdown, // markdown
        desc: lesson_desc, // description

        // link to lesson, i.e /learn/1/1
        // group 1, lesson 1
        link: '/learn/' + (parseInt(lessonblock)+1) + '/' + (parseInt(i)+1)
      }

    }
  }

  return lessontable
}

let lessonsTree = loadLessons()

// Gets the lesson at '/learn/x/y'
// where x is the lesson group, and y is the lesson number
// note: lesson and group numbers start from 1!
router.getLessonInfo = function(lesson_string) {
  let lessonsTree = lessonsTree || loadLessons()
  let lesson_ids = lesson_string.split('/')
  let lesson_group_id = parseInt(lesson_ids[0])
  let lesson_id = parseInt(lesson_ids[1])

  // get lesson group and account for starting from 1
  let lesson_group = lessonsTree[lesson_group_id-1]

  if(lesson_group) {
    let lesson = lesson_group.lessons[lesson_id-1]

    if(lesson) {
      return lesson
    }
  }

  return undefined

}

// GET /overview - Render overview of all lessons and lesson groups
router.get('/overview',ensureLoggedIn,function(req, res, next)
{
  lessonsTree = loadLessons()

  let isLoggedIn = (req.isAuthenticated && req.isAuthenticated())

  res.render('learnoverview', {
    title: 'Vimmy :: Lesson Overview',
    loggedIn: isLoggedIn,
    user: (isLoggedIn ? req.user.db : { }),
    lessonsTree: lessonsTree
  })
})

// GET /<lesson_group>/<lesson_id>/next -> Returns the next lesson in the group or returns to overview
// if the user asks for the next lesson, check if there is one in the current group or else redirect them to the overview
// TODO: fix existence of var checking, lesson sanity checking
router.get('/:lesson_group/:lesson_id/next', ensureLoggedIn, function(req, res, next)
{
  let lessonsTree = lessonsTree || loadLessons()
  let lesson_group = lessonsTree[req.params.lesson_group-1]

  if(lesson_group) { // if in valid lesson group

    // get the lesson they're at
    let lesson = lesson_group.lessons[req.params.lesson_id-1]

    if(lesson) // if it exists
    {
      // get the next possible lesson (note the lack of a -1), check if it exists
      if(lesson_group.lessons[req.params.lesson_id])
      {
        // calculate the path based off the two ids, and redirect
        let lessonpathid = req.params.lesson_group + '/' + (parseInt(req.params.lesson_id)+1)
        res.redirect('/learn/'+lessonpathid)
      }
      else // not a valid lesson (they reached the end of the group, redirect back to overview)
      {
        res.redirect('/learn/overview')
      }
    }
  }
})

// GET /<lesson_group>/<lesson_id> -> Renders lesson in group at id
// TODO: lesson sanity checking
router.get('/:lesson_group/:lesson_id', ensureLoggedIn, function(req, res, next)
{
  let lessonsTree = lessonsTree || loadLessons()

  let lessongroup = lessonsTree[req.params.lesson_group-1]

  if(lessongroup) {

    let lesson = lessongroup.lessons[req.params.lesson_id-1]

    // if lesson exists
    if(lesson) {

      // add the lesson to the recent lessons list of the user
      User.findOne({user_id: req.user.db.user_id}, function(err,user)
      {
        if(err){
          console.log(err)
          return
        }

        if(user) {
          let lessonpath_id = req.params.lesson_group + '/' + req.params.lesson_id
          let index = user.recent_lessons.indexOf(lessonpath_id)

          if (index > -1)
          {
            // remove existing lesson if its been there before
            user.recent_lessons.splice(index, 1)
          }

          user.recent_lessons.push(lessonpath_id)

          // save back to their profile
          user.save(function(err) {
            if(err) {
              console.error(err)
              return -1
            }
          })
        }
      })

      // convert the lesson to html
      let markdown = md.render(lesson.markdown)

      let isLoggedIn = (req.isAuthenticated && req.isAuthenticated())

      res.render('lesson', {
        title: 'Vimmy - ' + lesson.name,
        loggedIn: isLoggedIn,
        user: (isLoggedIn ? req.user.db : { }),
        lessonsTree: lessonsTree,
        markdown: markdown
      })

      return
    }
  }

  res.status(404).send('Not Found')
})

module.exports = router<|endoftext|>


<commit_before>var express = require('express');
var app     = express();
var server  = require('http').createServer(app);
var path    = require('path');
var math    = require('mathjs')();

var problem = require(__dirname + '/public/javascripts/helpers/problem')();
var H       = require(__dirname + '/public/javascripts/helpers/util')();

app.use(express.static(__dirname + '/public'));

require('./socketroutes')(io, H, problem, math);
<commit_msg>sockets added<commit_after>var express = require('express');
var app     = express();
var server  = require('http').createServer(app);
var io      = require('socket.io').listen(server);
var path    = require('path');
var math    = require('mathjs')();

var problem = require(__dirname + '/public/javascripts/helpers/problem')();
var H       = require(__dirname + '/public/javascripts/helpers/util')();

app.use(express.static(__dirname + '/public'));

require('./sockets')(io, H, problem, math);

server.listen(3000);
<|endoftext|>


<commit_before>const express = require('express');
const router = new express.Router();
const util = require('util');
const OAuth = require('oauth').OAuth;

const keys = require('../../keys.json');

const appConsumerKey = keys.tumblr.consumerKey;
const appConsumerSecret = keys.tumblr.consumerSecret;

// Used for testing an API call with aquired token and secret
const protectedResourceUrl = 'https://api.tumblr.com/v2/blog/developers.tumblr.com/info';

// Tumblr endpoints
const authorizeUrl = 'https://www.tumblr.com/oauth/authorize';
const requestTokenUrl = 'https://www.tumblr.com/oauth/request_token';
const accessTokenUrl = 'https://www.tumblr.com/oauth/access_token';

// OAuth(requestTokenUrl, accessTokenUrl, consumerKey, consumerSecret, OAuthVersion, callbackUrl, digest)
const oa = new OAuth(
  requestTokenUrl,
  accessTokenUrl,
  appConsumerKey,
  appConsumerSecret,
  '1.0A',
  'http://localhost:3000/callback',
  'HMAC-SHA1'
);

router.get('/', function (req, res, next) {
  console.log('getOAuthRequestToken');
  oa.getOAuthRequestToken(function (err, token, secret) {
    if (err) {
      console.error('\tFailed with error', err);
      return next(err);
    }
    console.log('\ttoken %s | secret %s', token, secret);

    // Save generated tokens to session
    req.session.requestToken = token;
    req.session.requestTokenSecret = secret;

    let authUrl = authorizeUrl + '?oauth_token=' + token;
    let html = util.format('%s', authUrl, authUrl);

    console.log('Direct client to authUrl');
    console.log('\t' + authUrl);
    console.log('\t... waiting for callback');

    return res.status(200).send(html);
  });
});

router.get('/callback', function (req, res, next) {
  console.log('Received callback');
  console.log('\toauth_token %s | oauth_verifier %s', req.query.oauth_token, req.query.oauth_verifier);
  console.log('\tsession token %s | session secret %s', req.session.requestToken, req.session.requestTokenSecret);

  if (!req.session.requestToken || !req.session.requestTokenSecret) {
    console.error('Error: Missing session information');
    return next('No requestToken found');
  }

  console.log('getOAuthAccessToken');

  oa.getOAuthAccessToken(
    req.query.oauth_token,
    req.session.requestTokenSecret,
    req.query.oauth_verifier,
    function (err, token, secret) {
      if (err) {
        console.error('Validation failed with error', err);
        return next(err);
      }
      console.log('\ttoken %s | secret %s', token, secret);

      console.log('Test accessToken', protectedResourceUrl);

      oa.get(protectedResourceUrl, token, secret, function (err) {
        if (err) {
          console.error('\tFailed with error', err);
          return next(err);
        }

        console.log('\tVerification successful!');

        return res.send(JSON.stringify({
          message: 'You are authorized!',
          token: token,
          secret: secret
        }));
      });
    }
  );
});

module.exports = router;
<commit_msg>Refactor, improved comments<commit_after>const express = require('express');
const router = new express.Router();
const util = require('util');
const OAuth = require('oauth').OAuth;

const keys = require('../../keys.json');

const appConsumerKey = keys.tumblr.consumerKey;
const appConsumerSecret = keys.tumblr.consumerSecret;

// Used for testing an API call with aquired token and secret
const protectedResourceUrl = 'https://api.tumblr.com/v2/blog/developers.tumblr.com/info';

// Tumblr endpoints
const authorizeUrl = 'https://www.tumblr.com/oauth/authorize';
const requestTokenUrl = 'https://www.tumblr.com/oauth/request_token';
const accessTokenUrl = 'https://www.tumblr.com/oauth/access_token';

// OAuth(requestTokenUrl, accessTokenUrl, consumerKey, consumerSecret, OAuthVersion, callbackUrl, digest)
const oa = new OAuth(
  requestTokenUrl,
  accessTokenUrl,
  appConsumerKey,
  appConsumerSecret,
  '1.0A',
  'http://localhost:3000/callback',
  'HMAC-SHA1'
);

router.get('/', function (req, res, next) {
  console.log('getOAuthRequestToken');
  oa.getOAuthRequestToken(function (err, token, secret) {
    if (err) {
      console.error('\tFailed with error', err);
      return next(err);
    }
    console.log('\ttoken %s | secret %s', token, secret);

    // Save generated tokens to session
    req.session.requestToken = token;
    req.session.requestTokenSecret = secret;

    let authUrl = authorizeUrl + '?oauth_token=' + token;
    let html = util.format('%s', authUrl, authUrl);

    console.log('Direct client to authUrl');
    console.log('\t' + authUrl);
    console.log('\t... waiting for callback');

    return res.status(200).send(html);
  });
});

router.get('/callback', function (req, res, next) {
  console.log('Received callback');
  console.log('\toauth_token %s | oauth_verifier %s', req.query.oauth_token, req.query.oauth_verifier);
  console.log('\tsession token %s | session secret %s', req.session.requestToken, req.session.requestTokenSecret);

  if (!req.session.requestToken || !req.session.requestTokenSecret) {
    console.error('\tError: Missing session information');
    return next('No previous session info found');
  }

  console.log('getOAuthAccessToken');

  oa.getOAuthAccessToken(
    req.query.oauth_token,
    req.session.requestTokenSecret,
    req.query.oauth_verifier,
    function (err, token, secret) {
      if (err) {
        console.error('\tValidation failed with error', err);
        return next('getOAuthAccessToken failed');
      }
      console.log('\ttoken %s | secret %s', token, secret);

      testOAuthToken(token, secret);
    }
  );

  function testOAuthToken(token, secret) {
    console.log('Test accessToken', protectedResourceUrl);
    oa.get(protectedResourceUrl, token, secret, function (err) {
      if (err) {
        console.error('\tFailed with error', err);
        return next('Error testing OAuthToken');
      }

      console.log('\tVerification successful!');

      return res.send(JSON.stringify({
        message: 'You are authorized!',
        token: token,
        secret: secret
      }));
    });
  }
});

module.exports = router;
<|endoftext|>


<commit_before>'use strict';

var EventEmitter = require('events');

class ModernEventEmitter extends EventEmitter {

    addListener(type, listener, self) {
        if (typeof listener == "function" && self) listener.ctx = self;
        return _addListener(this, type, listener, false);
    };

    prependListener(type, listener, self) {
        if (typeof listener == "function" && self) listener.ctx = self;
        return _addListener(this, type, listener, true);
    };

    emit(type) {
        var er, handler, len, args, i, events;

        events = this._events;
        if (!events) return false;

        handler = events[type];
        if (!handler) return false;

        var self = this;
        var isFn = typeof handler === 'function';
        if (isFn && handler.ctx) self = handler.ctx;

        len = arguments.length;
        switch (len) {
            // fast cases
            case 1:
                this.emitNone(handler, isFn, self);
                break;
            case 2:
                this.emitOne(handler, isFn, self, arguments[1]);
                break;
            case 3:
                this.emitTwo(handler, isFn, self, arguments[1], arguments[2]);
                break;
            case 4:
                this.emitThree(handler, isFn, self, arguments[1], arguments[2], arguments[3]);
                break;
            // slower
            default:
                args = new Array(len - 1);
                for (i = 1; i < len; i++)
                    args[i - 1] = arguments[i];
                this.emitMany(handler, isFn, self, args);
        }

        return true;
    }

    emitNone (handler, isFn, self) {
        if (isFn) {
            handler.call(self);
        } else {
            var len = handler.length;
            var listeners = arrayClone(handler, len);
            for (var i = 0; i < len; ++i) {
                if (listeners[i].ctx) self = listeners[i].ctx;
                if (!listeners[i].call(self)) break;
            }
        }
    }

    emitOne(handler, isFn, self, arg1) {
        if (isFn) {
            handler.call(self, arg1);
        } else {
            var len = handler.length;
            var listeners = arrayClone(handler, len);
            for (var i = 0; i < len; ++i) {
                if (listeners[i].ctx) self = listeners[i].ctx;
                if (!listeners[i].call(self, arg1)) break;
            }
        }
    }

    emitTwo(handler, isFn, self, arg1, arg2) {
        if (isFn) {
            handler.call(self, arg1, arg2);
        } else {
            var len = handler.length;
            var listeners = arrayClone(handler, len);
            for (var i = 0; i < len; ++i) {
                if (listeners[i].ctx) self = listeners[i].ctx;
                if (!listeners[i].call(self, arg1, arg2)) break;
            }
        }
    }

    emitThree(handler, isFn, self, arg1, arg2, arg3) {
        if (isFn) {
            handler.call(self, arg1, arg2, arg3);
        } else {
            var len = handler.length;
            var listeners = arrayClone(handler, len);
            for (var i = 0; i < len; ++i) {
                if (listeners[i].ctx) self = listeners[i].ctx;
                if (!listeners[i].call(self, arg1, arg2, arg3)) break;
            }
        }
    }

    emitMany(handler, isFn, self, args) {
        if (isFn) {
            handler.apply(self, args);
        } else {
            var len = handler.length;
            var listeners = arrayClone(handler, len);
            for (var i = 0; i < len; ++i) {
                if (listeners[i].ctx) self = listeners[i].ctx;
                if (!listeners[i].apply(self, args)) break;
            }
        }
    }

}

module.exports = ModernEventEmitter;
<commit_msg>Keep trying<commit_after>'use strict';

//Based on node.js EventEmitter as of node 7.x

class ModernEventEmitter {

    var _events = null;
    var _eventsCount = 0;

    _addListener(type, listener, prepend) {
        var existing;

        if (typeof listener !== 'function')
            throw new TypeError('"listener" argument must be a function');

        if (!this._events) {
            this._events = {};
            this._eventsCount = 0;
        }

        existing = this._events[type];

        if (!existing) {
            existing = this._events[type] = listener;
            ++this._eventsCount;
        } else {
            if (typeof existing === 'function') {
                existing = this._events[type] = prepend ? [listener, existing] : [existing, listener];
            } else {
                if (prepend) {
                    existing.unshift(listener);
                } else {
                    existing.push(listener);
                }
            }
        }
    }

    addListener(type, listener, self) {
        if (typeof listener == "function" && self) listener.ctx = self;
        return this._addListener(type, listener, false);
    };

    prependListener(type, listener, self) {
        if (typeof listener == "function" && self) listener.ctx = self;
        return this._addListener(type, listener, true);
    };

    on(type, listener, self) {
        this.addListener(type, listener, self);
    }

    emit(type) {
        var er, handler, len, args, i, events;

        events = this._events;
        if (!events) return false;

        handler = events[type];
        if (!handler) return false;

        var self = this;
        var isFn = typeof handler === 'function';
        if (isFn && handler.ctx) self = handler.ctx;

        len = arguments.length;
        switch (len) {
            case 1:
                this.emitNone(handler, isFn, self);
                break;
            case 2:
                this.emitOne(handler, isFn, self, arguments[1]);
                break;
            case 3:
                this.emitTwo(handler, isFn, self, arguments[1], arguments[2]);
                break;
            case 4:
                this.emitThree(handler, isFn, self, arguments[1], arguments[2], arguments[3]);
                break;
            default:
                args = new Array(len - 1);
                for (i = 1; i < len; i++)
                    args[i - 1] = arguments[i];
                this.emitMany(handler, isFn, self, args);
        }

        return true;
    }

    emitNone (handler, isFn, self) {
        if (isFn) {
            handler.call(self);
        } else {
            var len = handler.length;
            var listeners = arrayClone(handler, len);
            for (var i = 0; i < len; ++i) {
                if (listeners[i].ctx) self = listeners[i].ctx;
                if (!listeners[i].call(self)) break;
            }
        }
    }

    emitOne(handler, isFn, self, arg1) {
        if (isFn) {
            handler.call(self, arg1);
        } else {
            var len = handler.length;
            var listeners = arrayClone(handler, len);
            for (var i = 0; i < len; ++i) {
                if (listeners[i].ctx) self = listeners[i].ctx;
                if (!listeners[i].call(self, arg1)) break;
            }
        }
    }

    emitTwo(handler, isFn, self, arg1, arg2) {
        if (isFn) {
            handler.call(self, arg1, arg2);
        } else {
            var len = handler.length;
            var listeners = arrayClone(handler, len);
            for (var i = 0; i < len; ++i) {
                if (listeners[i].ctx) self = listeners[i].ctx;
                if (!listeners[i].call(self, arg1, arg2)) break;
            }
        }
    }

    emitThree(handler, isFn, self, arg1, arg2, arg3) {
        if (isFn) {
            handler.call(self, arg1, arg2, arg3);
        } else {
            var len = handler.length;
            var listeners = arrayClone(handler, len);
            for (var i = 0; i < len; ++i) {
                if (listeners[i].ctx) self = listeners[i].ctx;
                if (!listeners[i].call(self, arg1, arg2, arg3)) break;
            }
        }
    }

    emitMany(handler, isFn, self, args) {
        if (isFn) {
            handler.apply(self, args);
        } else {
            var len = handler.length;
            var listeners = arrayClone(handler, len);
            for (var i = 0; i < len; ++i) {
                if (listeners[i].ctx) self = listeners[i].ctx;
                if (!listeners[i].apply(self, args)) break;
            }
        }
    }

}

module.exports = ModernEventEmitter;

function arrayClone(arr, i) {
    var copy = new Array(i);
    while (i--) copy[i] = arr[i];
    return copy;
}
<|endoftext|>


<commit_before>var _ = require('lodash'),
	ffmpeg = require('fluent-ffmpeg');
var ShowImporter = require('../importers/ShowImporter.js');
var traktConfig = require('../../config/trakt');
var directoriesConfig = require('../../config/directories');
module.exports = function home(app, models){
	app.get('/shows', function(req, res){
		var Show = models.Show;
		if(req.isAuthenticated()){
			Show.find(function(err, shows){
				res.render('shows/index', {
					shows: shows
				});
			});
		}else{
			res.redirect('/auth/login');
		}
	});
	app.get('/show/:show', function(req, res){
		var Show = models.Show,
			Episode = models.Episode;
		if(req.isAuthenticated()){
			Show.findOne({url: req.params.show}, function(err, show){
				if(!show || show.length == 0){
					return res.render('error.html', {
						message: 'Show not found'
					});
				}
				//console.log(show)
				if(show && show.seasons){
					show.seasons = show.seasons.sort(function(a, b){
							if(a.season > b.season){
								return 1;
							}else if(a.season < b.season){
								return -1;
							}
							return 0;
					});
				}
				Episode.find({'show': show._id}, function(err, episodes){
					if(err){
						console.log(err);
					}
					//console.log('lol', episodes)
					var seasons = {};
					_.each(episodes, function (el){
						var s = el.season,
							e = el.episode;
						if(!seasons[s]){
							seasons[s] = {};
							seasons[s].num = s;
						}
						var season = seasons[s];
						if(!season.episodes){
							season.episodes = [];
						}
						if(show && show.seasons){
							if(show.seasons && show.seasons[s] && show.seasons[s].episodes){
								el = _.merge(el, show.seasons[s].episodes[e - 1])
								//console.log(show.seasons[s].episodes[e])
							}
						}
						season.episodes.push(el)
					});
					seasons = _.each(seasons, function(season){
						if(season){
							season.episodes = season.episodes.sort(function(a, b){
								if(a.episode > b.episode){
									return 1;
								}else if(a.episode < b.episode){
									return -1;
								}
								return 0;
							});
						}
					});
					res.render('shows/single', {
						show: show,
						seasons: seasons
					});
				})
			});
		}else{
			res.redirect('/auth/login');
		}
	});
	app.get('/watch/:episodeId', function(req, res){
		var dir = directoriesConfig.tv,
			Show = models.Show,
			Episode = models.Episode;
		if(req.isAuthenticated()){
			Episode
			.findOne({'_id': req.params.episodeId})
			.exec(function(err, ep){
				console.log(ep);
				if(err){
					return res.redirect('/');
				}
				Show.findOne({'_id': ep.show}, function(err, show){
					if(err){
						return res.redirect('/');
					}
					console.log(show)
					seasons = show.seasons.sort(function(a, b){
							if(a.season > b.season){
								return 1;
							}else if(a.season < b.season){
								return -1;
							}
							return 0;
					});
					seasons = _.each(show.seasons, function(season){
						if(season){
							season.episodes = season.episodes.sort(function(a, b){
								if(a.episode > b.episode){
									return 1;
								}else if(a.episode < b.episode){
									return -1;
								}
								return 0;
							});
						}
					});
					if(ep.season
						&& ep.episode
						&& seasons
						&& seasons[ep.season]
						&& seasons[ep.season].episodes
						&& seasons[ep.season].episodes[ep.episode - 1]){
						ep.overview = seasons[ep.season].episodes[ep.episode - 1].overview;
					}
					res.render('shows/episode', {
						show: show,
						ep: ep
					});
				})
			});
		}else{
			res.redirect('/auth/login');
		}
	});
	app.get('/transcode/:episodeId', function(req, res){
		var dir = directoriesConfig.tv,
			Episode = models.Episode;
		if(/*req.isAuthenticated()*/true){
			Episode
			.findOne({'_id': req.params.episodeId})
			.populate('show')
			.exec(function(err, ep){
				if(ep && ep.file){
					var options = [
						'-threads 0',
						'-coder 0',
						'-flags -loop',
						'-pix_fmt yuv420p',
						'-subq 0',
						'-sc_threshold 0',
						'-keyint_min 150',
						'-deinterlace',
						'-maxrate 10000000',
						'-bufsize 10000000',
						//'-acodec aac',
						'-strict experimental',
						'-frag_duration 1000',
						'-movflags +frag_keyframe+empty_moov',
						'-profile:v baseline'
					];
					// High quality, not lossless
					options.push('-g 52', '-crf 22', '-ar 48000', '-ab 320k');
					res.contentType('video/webm');
					console.log(ep.file)
					var proc = ffmpeg({source: dir + ep.file})
					.format('libvpx')
					.audioCodec('libvorbis')
					.withVideoBitrate(1024)
					.addOptions(options)
					.on('start', function(commandLine) {
						console.log('Spawned Ffmpeg with command: ' + commandLine);
					})
					.on('end', function(){
						console.log('file has been converted succesfully');
					})
					.on('error', function(err){
						console.log('an error happened: ' + err.message);
					})
					.pipe(res, {end:true});

				}
			});
		}else{
			res.redirect('/auth/login');
		}
	});
	app.get('/import', function(req, res){
		var dir = directoriesConfig.tv,
			importer = new ShowImporter(traktConfig.apiKey, models);
		importer.importAll(dir, function(){});
		res.end();
	});
};<commit_msg>Yes sir<commit_after>var _ = require('lodash'),
	ffmpeg = require('fluent-ffmpeg');
var ShowImporter = require('../importers/ShowImporter.js');
var traktConfig = require('../../config/trakt');
var directoriesConfig = require('../../config/directories');
module.exports = function home(app, models){
	app.get('/shows', function(req, res){
		var Show = models.Show;
		if(req.isAuthenticated()){
			Show.find(function(err, shows){
				res.render('shows/index', {
					shows: shows
				});
			});
		}else{
			res.redirect('/auth/login');
		}
	});
	app.get('/show/:show', function(req, res){
		var Show = models.Show,
			Episode = models.Episode;
		if(req.isAuthenticated()){
			Show.findOne({url: req.params.show}, function(err, show){
				if(!show || show.length == 0){
					return res.render('error.html', {
						message: 'Show not found'
					});
				}
				//console.log(show)
				if(show && show.seasons){
					show.seasons = show.seasons.sort(function(a, b){
							if(a.season > b.season){
								return 1;
							}else if(a.season < b.season){
								return -1;
							}
							return 0;
					});
				}
				Episode.find({'show': show._id}, function(err, episodes){
					if(err){
						console.log(err);
					}
					//console.log('lol', episodes)
					var seasons = {};
					_.each(episodes, function (el){
						var s = el.season,
							e = el.episode;
						if(!seasons[s]){
							seasons[s] = {};
							seasons[s].num = s;
						}
						var season = seasons[s];
						if(!season.episodes){
							season.episodes = [];
						}
						if(show && show.seasons){
							if(show.seasons && show.seasons[s] && show.seasons[s].episodes){
								el = _.merge(el, show.seasons[s].episodes[e - 1])
								//console.log(show.seasons[s].episodes[e])
							}
						}
						season.episodes.push(el)
					});
					seasons = _.each(seasons, function(season){
						if(season){
							season.episodes = season.episodes.sort(function(a, b){
								if(a.episode > b.episode){
									return 1;
								}else if(a.episode < b.episode){
									return -1;
								}
								return 0;
							});
						}
					});
					res.render('shows/single', {
						show: show,
						seasons: seasons
					});
				})
			});
		}else{
			res.redirect('/auth/login');
		}
	});
	app.get('/watch/:episodeId', function(req, res){
		var dir = directoriesConfig.tv,
			Show = models.Show,
			Episode = models.Episode;
		if(req.isAuthenticated()){
			Episode
			.findOne({'_id': req.params.episodeId})
			.exec(function(err, ep){
				console.log(ep);
				if(err){
					return res.redirect('/');
				}
				Show.findOne({'_id': ep.show}, function(err, show){
					if(err){
						return res.redirect('/');
					}
					console.log(show)
					seasons = show.seasons.sort(function(a, b){
							if(a.season > b.season){
								return 1;
							}else if(a.season < b.season){
								return -1;
							}
							return 0;
					});
					seasons = _.each(show.seasons, function(season){
						if(season){
							season.episodes = season.episodes.sort(function(a, b){
								if(a.episode > b.episode){
									return 1;
								}else if(a.episode < b.episode){
									return -1;
								}
								return 0;
							});
						}
					});
					if(ep.season
						&& ep.episode
						&& seasons
						&& seasons[ep.season]
						&& seasons[ep.season].episodes
						&& seasons[ep.season].episodes[ep.episode - 1]){
						ep.overview = seasons[ep.season].episodes[ep.episode - 1].overview;
					}
					res.render('shows/episode', {
						show: show,
						ep: ep
					});
				})
			});
		}else{
			res.redirect('/auth/login');
		}
	});
	app.get('/transcode/:episodeId', function(req, res){
		var dir = directoriesConfig.tv,
			Episode = models.Episode;
		if(/*req.isAuthenticated()*/true){
			Episode
			.findOne({'_id': req.params.episodeId})
			.populate('show')
			.exec(function(err, ep){
				if(ep && ep.file){
					var options = [
						'-threads 0',
						'-coder 0',
						'-flags -loop',
						'-pix_fmt yuv420p',
						'-subq 0',
						'-sc_threshold 0',
						'-keyint_min 150',
						'-deinterlace',
						'-maxrate 10000000',
						'-bufsize 10000000',
						//'-acodec aac',
						'-strict experimental',
						'-frag_duration 1000',
						'-movflags +frag_keyframe+empty_moov',
						'-profile:v baseline'
					];
					// High quality, not lossless
					options.push('-g 52', '-crf 22', '-ar 48000', '-ab 320k');
					res.contentType('video/webm');
					console.log(ep.file)
					var proc = ffmpeg({source: dir + ep.file})
					.videoCodec('libvpx')
					.audioCodec('libvorbis')
					.withVideoBitrate(1024)
					.addOptions(options)
					.on('start', function(commandLine) {
						console.log('Spawned Ffmpeg with command: ' + commandLine);
					})
					.on('end', function(){
						console.log('file has been converted succesfully');
					})
					.on('error', function(err){
						console.log('an error happened: ' + err.message);
					})
					.pipe(res, {end:true});

				}
			});
		}else{
			res.redirect('/auth/login');
		}
	});
	app.get('/import', function(req, res){
		var dir = directoriesConfig.tv,
			importer = new ShowImporter(traktConfig.apiKey, models);
		importer.importAll(dir, function(){});
		res.end();
	});
};<|endoftext|>