<commit_before>
orders_cycle = {

  cycle: {

    edit: function (destroy_url) {
      options = {isoTime: true};
      jQuery('#cycle_start_date, #cycle_start_time, #cycle_finish_date, #cycle_finish_time').calendricalDateTimeRange(options);
      jQuery('#cycle_delivery_start_date, #cycle_delivery_start_time, #cycle_delivery_finish_date, #cycle_delivery_finish_time').calendricalDateTimeRange(options);

      orders_cycle.cycle.saveClick = false;
      if (destroy_url) {
        jQuery(window).bind('beforeunload', function () {
          if (!orders_cycle.cycle.saveClick)
            jQuery.ajax({type: 'POST', async: false, url: destroy_url});
        });
      }
    },
  },

  /* ----- cycle ----- */

  in_cycle_order_toggle: function (context) {
    container = jQuery(context).hasClass('cycle-orders') ? jQuery(context) : jQuery(context).parents('.cycle-orders');
    container.toggleClass('show');
    container.find('.order-content').toggle();
    sortable_table.edit_arrow_toggle(container);
  },

  /* ----- order ----- */

  order: {

    product: {
      include_message: '',
      order_id: 0,
      redirect_after_include: '',
      add_url: '',
      remove_url: '',
      balloon_url: '',

      load: function (id, state) {
        var product = jQuery('#cycle-product-'+id);
        product.toggleClass('in-order', state);
        return product;
      },

      checkbox_click: function (check_box, id) {
        this.click(id, check_box.checked);
        return true;
      },
      click: function (event, id) {
        // was this a child click?
        if (event.target != this && event.target.onclick)
          return;

        var product = jQuery('#cycle-product-'+id);
        var state = !product.hasClass('in-order');
        if (state == true)
          this.add(id);
        else
          this.remove(id);
        product.find('input').get(0).checked = state;
      },

      add: function (id) {
        var product = this.load(id, true);

        if (this.include_message)
          alert(this.include_message);

        loading_overlay.show(product);
        jQuery.post(this.add_url, {order_id: this.order_id, redirect: this.redirect_after_include, offered_product_id: id}, function () {
          loading_overlay.hide(product);
        });
      },
      remove: function (id) {
        var product = this.load(id, false);

        loading_overlay.show(product);
        jQuery.post(this.remove_url, {id: id, order_id: this.order_id}, function () {
          loading_overlay.hide(product);
        });
      },

      supplier: {
        balloon_url: '',

        balloon: function (id) {
          var product = jQuery('#cycle-product-'+id);
          var target = product.find('.supplier');
          var supplier_id = product.attr('supplier-id');
          balloon.showFromGet(target, this.balloon_url+'/'+supplier_id, {position: 'above'});
        },
      },

      balloon: function (id) {
        var product = jQuery('#cycle-product-'+id);
        var target = product.find('.product');
        balloon.showFromGet(target, this.balloon_url+'/'+id, {position: 'above'});
      },
    },
  },

  /* ----- cycle editions ----- */

  offered_product: {

    pmsync: function (context, to_price) {
      p = jQuery(context).parents('.cycle-product .box-edit');
      margin = p.find('#product_margin_percentage');
      price = p.find('#product_price');
      buy_price = p.find('#product_buy_price');
      original_price = p.find('#product_original_price');
      base_price = unlocalize_currency(buy_price.val()) ? buy_price : original_price;

      if (to_price)
        suppliers.price.calculate(price, margin, base_price);
      else
        suppliers.margin.calculate(margin, price, base_price);
    },

    edit: function () {
      toggle_edit.editing().find('.box-edit').toggle(toggle_edit.isEditing());
    },
  },

  /* ----- toggle edit ----- */

  cycle_mail_message_toggle: function () {
    if ($('cycle-new-mail-send').checked) {
      jQuery('#cycle-new-mail').removeClass('disabled');
      jQuery('#cycle-new-mail textarea').removeAttr('disabled');
    } else {
      jQuery('#cycle-new-mail').addClass('disabled');
      jQuery('#cycle-new-mail textarea').attr('disabled', true);
    }
  },

  colorbox: function (options) {
    options.innerWidth = 500;
    jQuery.colorbox(options);
  },

  ajaxifyPagination: function(elementId) {
    jQuery(".pagination a").click(function() {
      loading_overlay.show('#'+elementId);
      jQuery.ajax({
        type: "GET",
        url: jQuery(this).attr("href"),
        dataType: "script"
      });
      return false;
    });
  },

  toggleCancelledOrders: function () {
    jQuery('.consumers-coop #show-cancelled-orders a').toggle();
    jQuery('.consumers-coop #hide-cancelled-orders a').toggle();
    jQuery('.consumers-coop .consumer-order:not(.edit) .status-cancelled').toggle();
  },

};
<commit_msg>orders_cycle: remove old code for removing cycle<commit_after>
orders_cycle = {

  cycle: {

    edit: function () {
      options = {isoTime: true};
      jQuery('#cycle_start_date, #cycle_start_time, #cycle_finish_date, #cycle_finish_time').calendricalDateTimeRange(options);
      jQuery('#cycle_delivery_start_date, #cycle_delivery_start_time, #cycle_delivery_finish_date, #cycle_delivery_finish_time').calendricalDateTimeRange(options);
    },
  },

  /* ----- cycle ----- */

  in_cycle_order_toggle: function (context) {
    container = jQuery(context).hasClass('cycle-orders') ? jQuery(context) : jQuery(context).parents('.cycle-orders');
    container.toggleClass('show');
    container.find('.order-content').toggle();
    sortable_table.edit_arrow_toggle(container);
  },

  /* ----- order ----- */

  order: {

    product: {
      include_message: '',
      order_id: 0,
      redirect_after_include: '',
      add_url: '',
      remove_url: '',
      balloon_url: '',

      load: function (id, state) {
        var product = jQuery('#cycle-product-'+id);
        product.toggleClass('in-order', state);
        return product;
      },

      checkbox_click: function (check_box, id) {
        this.click(id, check_box.checked);
        return true;
      },
      click: function (event, id) {
        // was this a child click?
        if (event.target != this && event.target.onclick)
          return;

        var product = jQuery('#cycle-product-'+id);
        var state = !product.hasClass('in-order');
        if (state == true)
          this.add(id);
        else
          this.remove(id);
        product.find('input').get(0).checked = state;
      },

      add: function (id) {
        var product = this.load(id, true);

        if (this.include_message)
          alert(this.include_message);

        loading_overlay.show(product);
        jQuery.post(this.add_url, {order_id: this.order_id, redirect: this.redirect_after_include, offered_product_id: id}, function () {
          loading_overlay.hide(product);
        });
      },
      remove: function (id) {
        var product = this.load(id, false);

        loading_overlay.show(product);
        jQuery.post(this.remove_url, {id: id, order_id: this.order_id}, function () {
          loading_overlay.hide(product);
        });
      },

      supplier: {
        balloon_url: '',

        balloon: function (id) {
          var product = jQuery('#cycle-product-'+id);
          var target = product.find('.supplier');
          var supplier_id = product.attr('supplier-id');
          balloon.showFromGet(target, this.balloon_url+'/'+supplier_id, {position: 'above'});
        },
      },

      balloon: function (id) {
        var product = jQuery('#cycle-product-'+id);
        var target = product.find('.product');
        balloon.showFromGet(target, this.balloon_url+'/'+id, {position: 'above'});
      },
    },
  },

  /* ----- cycle editions ----- */

  offered_product: {

    pmsync: function (context, to_price) {
      p = jQuery(context).parents('.cycle-product .box-edit');
      margin = p.find('#product_margin_percentage');
      price = p.find('#product_price');
      buy_price = p.find('#product_buy_price');
      original_price = p.find('#product_original_price');
      base_price = unlocalize_currency(buy_price.val()) ? buy_price : original_price;

      if (to_price)
        suppliers.price.calculate(price, margin, base_price);
      else
        suppliers.margin.calculate(margin, price, base_price);
    },

    edit: function () {
      toggle_edit.editing().find('.box-edit').toggle(toggle_edit.isEditing());
    },
  },

  /* ----- toggle edit ----- */

  cycle_mail_message_toggle: function () {
    if ($('cycle-new-mail-send').checked) {
      jQuery('#cycle-new-mail').removeClass('disabled');
      jQuery('#cycle-new-mail textarea').removeAttr('disabled');
    } else {
      jQuery('#cycle-new-mail').addClass('disabled');
      jQuery('#cycle-new-mail textarea').attr('disabled', true);
    }
  },

  colorbox: function (options) {
    options.innerWidth = 500;
    jQuery.colorbox(options);
  },

  ajaxifyPagination: function(elementId) {
    jQuery(".pagination a").click(function() {
      loading_overlay.show('#'+elementId);
      jQuery.ajax({
        type: "GET",
        url: jQuery(this).attr("href"),
        dataType: "script"
      });
      return false;
    });
  },

  toggleCancelledOrders: function () {
    jQuery('.consumers-coop #show-cancelled-orders a').toggle();
    jQuery('.consumers-coop #hide-cancelled-orders a').toggle();
    jQuery('.consumers-coop .consumer-order:not(.edit) .status-cancelled').toggle();
  },

};
<|endoftext|>


<commit_before>const processedString = require('./helpers/stringHelpers').processedString;
const generalChatId = require('./siteConfig').generalChatId;
const pool = require('./pool');

module.exports = function(io) {
  let connections = [];
  io.on('connection', socket => {
    connections.push({
      socketId: socket.id,
      username: '',
      userId: null,
      channels: []
    });

    socket.on('enter_my_notification_channel', userId => {
      socket.join('notificationChannel' + userId)
    })

    socket.on('leave_my_notification_channel', userId => {
      socket.leave('notificationChannel' + userId);
    })

    socket.on('check_online_members', (channelId, callback) => {
      io.of('/').in('chatChannel' + channelId).clients((error, clients) => {
        let membersOnline = clients.map(client => {
          let member = {};
          for (let i = 0; i < connections.length; i++) {
            if (connections[i].socketId === client) {
              member = {
                userId: connections[i].userId,
                username: connections[i].username
              }
            }
          }
          return member;
        })
        membersOnline = membersOnline.reduce(
          (resultingArray, member) => {
            if (resultingArray.length === 0) {
              return resultingArray.concat(member)
            }
            else if (resultingArray[Math.max(resultingArray.length - 1, 0)].userId !== member.userId) {
              return resultingArray.concat(member)
            }
            else {
              return resultingArray;
            }
          }, []
        )
        let data = {channelId, membersOnline}
        callback(error, data);
      })
    })

    socket.on('join_chat_channel', (channelId, callback) => {
      socket.join('chatChannel' + channelId);
      for (let i = 0; i < connections.length; i++) {
        if (connections[i].socketId === socket.id) {
          if (connections[i].channels.indexOf(Number(channelId)) === -1) {
            connections[i].channels.push(Number(channelId));
          }
          break;
        }
      }
      notifyChannelMembersChanged(channelId);
    })

    socket.on('leave_chat_channel', ({channelId, userId, username}) => {
      socket.leave('chatChannel' + channelId);
      for (let i = 0; i < connections.length; i++) {
        if (connections[i].socketId === socket.id) {
          let index = connections[i].channels.indexOf(channelId);
          connections[i].channels.splice(index, 1);
          break;
        }
      }
      notifyChannelMembersChanged(channelId, {userId, username});
    })

    socket.on('bind_uid_to_socket', (userId, username) => {
      const query = [
        'SELECT a.id AS channel FROM msg_chatrooms a WHERE a.id IN ',
        '(SELECT b.roomid FROM msg_chatroom_members b WHERE b.roomid = ? ',
        'OR b.userid = ?)'
      ].join('')
      pool.query(query, [generalChatId, userId], (err, rows) => {
        let channels = rows.map(row => Number(row.channel));
        for (let i = 0; i < connections.length; i++) {
          if (connections[i].socketId === socket.id) {
            connections[i].userId = userId;
            connections[i].username = username;
            connections[i].channels = channels;
            break;
          }
        }
        for (let i = 0; i < channels.length; i++) {
          let channelId = channels[i];
          socket.join('chatChannel' + channelId);
          notifyChannelMembersChanged(channelId);
        }
      })
    })

    socket.on('new_chat_message', (data) => {
      const channelId = data.channelId;
      data.content = processedString(data.content);
      io.to('chatChannel' + channelId).emit('receive_message', data);
    })

    socket.on('send_bi_chat_invitation', (userId, data) => {
      io.to('notificationChannel'+userId).emit('chat_invitation', data);
    })

    socket.on('send_group_chat_invitation', (users, data) => {
      for (let i = 0; i < users.length; i++) {
        io.to('notificationChannel'+users[i]).emit('chat_invitation', data.message);
      }
    })

    socket.on('disconnect', () => {
      for (let i = 0; i < connections.length; i++) {
        if (connections[i].socketId === socket.id) {
          let connection = connections[i];
          for (let i = 0; i < connection.channels.length; i++) {
            let channelId = connection.channels[i];
            socket.leave('chatChannel' + channelId);
            notifyChannelMembersChanged(channelId);
          }
          connections.splice(i, 1)
          break;
        }
      }
    })
  })

  function notifyChannelMembersChanged(channelId, leftChannel) {
    io.of('/').in('chatChannel' + channelId).clients((error, clients) => {
      if (error) return console.error(error);
      let membersOnline = clients.map(client => {
        let member = {};
        for (let i = 0; i < connections.length; i++) {
          if (connections[i].socketId === client) {
            member = {
              userId: connections[i].userId,
              username: connections[i].username
            }
          }
        }
        return member;
      })
      membersOnline = membersOnline.reduce(
        (resultingArray, member) => {
          if (resultingArray.length === 0) {
            return resultingArray.concat([member])
          }
          else if (resultingArray[Math.max(resultingArray.length - 1, 0)].userId !== member.userId) {
            return resultingArray.concat([member])
          }
          else {
            return resultingArray;
          }
        }, []
      )
      let data = {channelId, membersOnline, leftChannel}
      io.to('chatChannel' + channelId).emit('change_in_members_online', data);
    })
  }
}
<commit_msg>number online bug fix<commit_after>const processedString = require('./helpers/stringHelpers').processedString;
const generalChatId = require('./siteConfig').generalChatId;
const pool = require('./pool');

module.exports = function(io) {
  let connections = [];
  io.on('connection', socket => {
    connections.push({
      socketId: socket.id,
      username: '',
      userId: null,
      channels: []
    });

    socket.on('enter_my_notification_channel', userId => {
      socket.join('notificationChannel' + userId)
    })

    socket.on('leave_my_notification_channel', userId => {
      socket.leave('notificationChannel' + userId);
    })

    socket.on('check_online_members', (channelId, callback) => {
      io.of('/').in('chatChannel' + channelId).clients((error, clients) => {
        let membersOnline = clients.map(client => {
          let member = {};
          for (let i = 0; i < connections.length; i++) {
            if (connections[i].socketId === client) {
              member = {
                userId: connections[i].userId,
                username: connections[i].username
              }
            }
          }
          return member;
        })
        membersOnline = membersOnline.reduce(
          (resultingArray, member) => {
            if (resultingArray.length === 0) {
              return resultingArray.concat(member)
            }
            else if (Number(resultingArray[Math.max(resultingArray.length - 1, 0)].userId) !== Number(member.userId)) {
              return resultingArray.concat(member)
            }
            else {
              return resultingArray;
            }
          }, []
        )
        let data = {channelId, membersOnline}
        callback(error, data);
      })
    })

    socket.on('join_chat_channel', (channelId, callback) => {
      socket.join('chatChannel' + channelId);
      for (let i = 0; i < connections.length; i++) {
        if (connections[i].socketId === socket.id) {
          if (connections[i].channels.indexOf(Number(channelId)) === -1) {
            connections[i].channels.push(Number(channelId));
          }
          break;
        }
      }
      notifyChannelMembersChanged(channelId);
    })

    socket.on('leave_chat_channel', ({channelId, userId, username}) => {
      socket.leave('chatChannel' + channelId);
      for (let i = 0; i < connections.length; i++) {
        if (connections[i].socketId === socket.id) {
          let index = connections[i].channels.indexOf(channelId);
          connections[i].channels.splice(index, 1);
          break;
        }
      }
      notifyChannelMembersChanged(channelId, {userId, username});
    })

    socket.on('bind_uid_to_socket', (userId, username) => {
      const query = [
        'SELECT a.id AS channel FROM msg_chatrooms a WHERE a.id IN ',
        '(SELECT b.roomid FROM msg_chatroom_members b WHERE b.roomid = ? ',
        'OR b.userid = ?)'
      ].join('')
      pool.query(query, [generalChatId, userId], (err, rows) => {
        let channels = rows.map(row => Number(row.channel));
        for (let i = 0; i < connections.length; i++) {
          if (connections[i].socketId === socket.id) {
            connections[i].userId = userId;
            connections[i].username = username;
            connections[i].channels = channels;
            break;
          }
        }
        for (let i = 0; i < channels.length; i++) {
          let channelId = channels[i];
          socket.join('chatChannel' + channelId);
          notifyChannelMembersChanged(channelId);
        }
      })
    })

    socket.on('new_chat_message', (data) => {
      const channelId = data.channelId;
      data.content = processedString(data.content);
      io.to('chatChannel' + channelId).emit('receive_message', data);
    })

    socket.on('send_bi_chat_invitation', (userId, data) => {
      io.to('notificationChannel'+userId).emit('chat_invitation', data);
    })

    socket.on('send_group_chat_invitation', (users, data) => {
      for (let i = 0; i < users.length; i++) {
        io.to('notificationChannel'+users[i]).emit('chat_invitation', data.message);
      }
    })

    socket.on('disconnect', () => {
      for (let i = 0; i < connections.length; i++) {
        if (connections[i].socketId === socket.id) {
          let connection = connections[i];
          for (let i = 0; i < connection.channels.length; i++) {
            let channelId = connection.channels[i];
            socket.leave('chatChannel' + channelId);
            notifyChannelMembersChanged(channelId);
          }
          connections.splice(i, 1)
          break;
        }
      }
    })
  })

  function notifyChannelMembersChanged(channelId, leftChannel) {
    io.of('/').in('chatChannel' + channelId).clients((error, clients) => {
      if (error) return console.error(error);
      let membersOnline = clients.map(client => {
        let member = {};
        for (let i = 0; i < connections.length; i++) {
          if (connections[i].socketId === client) {
            member = {
              userId: connections[i].userId,
              username: connections[i].username
            }
          }
        }
        return member;
      })
      membersOnline = membersOnline.reduce(
        (resultingArray, member) => {
          if (resultingArray.length === 0) {
            return resultingArray.concat([member])
          }
          else if (resultingArray[Math.max(resultingArray.length - 1, 0)].userId !== member.userId) {
            return resultingArray.concat([member])
          }
          else {
            return resultingArray;
          }
        }, []
      )
      let data = {channelId, membersOnline, leftChannel}
      io.to('chatChannel' + channelId).emit('change_in_members_online', data);
    })
  }
}
<|endoftext|>


<commit_before>var express = require('express')
var router = express.Router()
var common = require('./lib/common')
var fs = require('fs-extra');
var dirTree = require('./lib/directory-tree')

//
// Check for the positive existence of a directory
//
function checkExistence (file) {
  return new Promise((resolve, reject) => {
    fs.stat(file, (err, data) => {
      if (err) {
        reject({ 'message': "Error: Directory doesn't exist.", 'err': err })
      } else {
        resolve()
      }
    })
  })
}

//
// Check for the negative existence of a directory
//
function checkNegativeExistence (file) {
  return new Promise((resolve, reject) => {
    fs.stat(file, (err, data) => {
      if (err) {
        resolve()
      } else {
        reject({ 'message': "Error: Directory exists.", 'err': err })
      }
    })
  })
}

//
// Build a new directory
//
function createDirectory(dir) {
  return new Promise( function(resolve, reject) {
    fs.ensureDir(dir, config.cmode, function (err) {
      if (err) {
        reject({ 'message': "Error creating directory", 'err': err});
      } else {
        resolve()
      }
    });
  })
}

//
// Delete a directory
//
function deleteDirectory(dir) {
  return new Promise( function(resolve, reject) {
      // Remove file or directory
    fs.remove(dir, function (err) {
        if (err) {
          reject({ 'message': "Error removing entry.", 'err': err });
        } else {
          resolve()
        }
    });
  });
}

//
// Empty a directory
//
function emptyDirectory(dir) {
  return new Promise( function(resolve, reject) {
      // Remove file or directory
    fs.emptyDir(dir, function (err) {
        if (err) {
          reject({ 'message': "Error emptying entry.", 'err': err });
        } else {
          resolve()
        }
    });
  });
}

// Set the derived parameters for all methods
//
router.all(/^(.*)$/, function(req, res, next) {
  req.absolutePath = config.baseDirectory + req.originalUrl
  next()
});

//
// GET a directory tree
//
router.get(/^(.*)$/, function(req, res, next) {
  var url = (req.secure) ? 'https' : 'http' + '://' + req.headers.host + req.originalBaseUrl
  var tree = dirTree(url, config.baseDirectory, req.originalUrl);
  common.resSuccess(tree, res);
});

//
// DELETE a directory
//
router.delete(/^(.*)$/, function(req, res, next) {
  checkExistence(req.absolutePath)
  .then(function() {
    if (req.originalUrl == '/') {
      return emptyDirectory(req.absolutePath)
    } else {
      return deleteDirectory(req.absolutePath)
    }
  })
  .then(function() {
    common.resSuccess({ 'message': 'Deleted.' }, res);
  })
  .catch(function (reason) {
    common.resError(reason.message, reason.err, res);
  })
});

//
// PUT or POST a new directory
//
router.all(/^(.*)$/, function(req, res) {
  if (req.method === 'PUT' || req.method === 'POST') {
    checkNegativeExistence(req.absolutePath)
    .then(function() {
      return createDirectory(req.absolutePath)
    })
    .then(function() {
      var response = {}
      response.url = (req.secure) ? 'https' : 'http' + '://' + req.headers.host + req.originalBaseUrl + req.url
      common.resSuccess(response, res);
    })
    .catch(function (reason) {
      common.resError(reason.message, reason.err, res);
    })
  }
});

module.exports = router;
<commit_msg>Fix for https<commit_after>var express = require('express')
var router = express.Router()
var common = require('./lib/common')
var fs = require('fs-extra');
var dirTree = require('./lib/directory-tree')

//
// Check for the positive existence of a directory
//
function checkExistence (file) {
  return new Promise((resolve, reject) => {
    fs.stat(file, (err, data) => {
      if (err) {
        reject({ 'message': "Error: Directory doesn't exist.", 'err': err })
      } else {
        resolve()
      }
    })
  })
}

//
// Check for the negative existence of a directory
//
function checkNegativeExistence (file) {
  return new Promise((resolve, reject) => {
    fs.stat(file, (err, data) => {
      if (err) {
        resolve()
      } else {
        reject({ 'message': "Error: Directory exists.", 'err': err })
      }
    })
  })
}

//
// Build a new directory
//
function createDirectory(dir) {
  return new Promise( function(resolve, reject) {
    fs.ensureDir(dir, config.cmode, function (err) {
      if (err) {
        reject({ 'message': "Error creating directory", 'err': err});
      } else {
        resolve()
      }
    });
  })
}

//
// Delete a directory
//
function deleteDirectory(dir) {
  return new Promise( function(resolve, reject) {
      // Remove file or directory
    fs.remove(dir, function (err) {
        if (err) {
          reject({ 'message': "Error removing entry.", 'err': err });
        } else {
          resolve()
        }
    });
  });
}

//
// Empty a directory
//
function emptyDirectory(dir) {
  return new Promise( function(resolve, reject) {
      // Remove file or directory
    fs.emptyDir(dir, function (err) {
        if (err) {
          reject({ 'message': "Error emptying entry.", 'err': err });
        } else {
          resolve()
        }
    });
  });
}

// Set the derived parameters for all methods
//
router.all(/^(.*)$/, function(req, res, next) {
  req.absolutePath = config.baseDirectory + req.originalUrl
  next()
});

//
// GET a directory tree
//
router.get(/^(.*)$/, function(req, res, next) {
  var url = ((req.secure) ? 'https' : 'http' + '://' ) + req.headers.host + req.originalBaseUrl
  var tree = dirTree(url, config.baseDirectory, req.originalUrl);
  common.resSuccess(tree, res);
});

//
// DELETE a directory
//
router.delete(/^(.*)$/, function(req, res, next) {
  checkExistence(req.absolutePath)
  .then(function() {
    if (req.originalUrl == '/') {
      return emptyDirectory(req.absolutePath)
    } else {
      return deleteDirectory(req.absolutePath)
    }
  })
  .then(function() {
    common.resSuccess({ 'message': 'Deleted.' }, res);
  })
  .catch(function (reason) {
    common.resError(reason.message, reason.err, res);
  })
});

//
// PUT or POST a new directory
//
router.all(/^(.*)$/, function(req, res) {
  if (req.method === 'PUT' || req.method === 'POST') {
    checkNegativeExistence(req.absolutePath)
    .then(function() {
      return createDirectory(req.absolutePath)
    })
    .then(function() {
      var response = {}
      response.url = (req.secure) ? 'https' : 'http' + '://' + req.headers.host + req.originalBaseUrl + req.url
      common.resSuccess(response, res);
    })
    .catch(function (reason) {
      common.resError(reason.message, reason.err, res);
    })
  }
});

module.exports = router;
<|endoftext|>


<commit_before>var SearchBar = React.createClass({

  getInitialState: function () {
    return {text: ''};
  },

  handleSubmit: function (e) {
    e.preventDefault();
    searchYouTube(this.state.text);
    this.setState({text: ''});
  },

  onChange: function (e) {
    e.preventDefault();
    this.setState({text: e.target.value});
  },
  render: function () {

    var style = {
      borderColor: '#EEEEEE',
      position: 'absolute',
      top: 0,
      width: '100%'

    };

    var searchBarInputStyle = {
      backgroundColor: '#AAAAAA',
      borderColor: '#EEEEEE'
    };

    var searchResultsStyle = {
      marginTop: '50px'
    };

    return (

        <form style={style} onSubmit={this.handleSubmit}>
          <input style={searchBarInputStyle} onChange={this.onChange} value={this.state.text} className="form-control" placeholder="Search YouTube"/>
        </form>

    );
  }
});

var MediaAdd = React.createClass({
  render: function() {
    var style ={
      background: '#222222',
      border: '2px solid #444444',
      position: 'absolute',
      width: '100%',
      height: '50%',
      overflow: 'auto',
      top: '0'
    };
    return (

        <SearchBar />

    );
  }
});<commit_msg>(client) Copied code for mediaAdd over from project due to git error<commit_after>var SearchBar = React.createClass({

  getInitialState: function () {
    return {text: ''};
  },

  handleSubmit: function (e) {
    e.preventDefault();
    this.searchYouTube(this.state.text);
    this.setState({text: ''});
  },
  escapeDQ: function (string) {
    return string.replace(/\"/g, "'");
  },

  // Convert YouTube ISO 8061 Format to Int equal to total number of seconds in video
  convertYTDuration: function (duration) {
    var a = duration.match(/\d+/g);

    if (duration.indexOf('M') >= 0 && duration.indexOf('H') === -1 && duration.indexOf('S') === -1) {
      a = [0, a[0], 0];
    }
    if (duration.indexOf('H') >= 0 && duration.indexOf('M') === -1) {
      a = [a[0], 0, a[1]];
    }
    if (duration.indexOf('H') >= 0 && duration.indexOf('M') === -1 && duration.indexOf('S') === -1) {
      a = [a[0], 0, 0];
    }

    duration = 0;
    if (a.length === 3) {
      duration = duration + parseInt(a[0]) * 3600;
      duration = duration + parseInt(a[1]) * 60;
      duration = duration + parseInt(a[2]);
    }
    if (a.length === 2) {
      duration = duration + parseInt(a[0]) * 60;
      duration = duration + parseInt(a[1]);
    }
    if (a.length === 1) {
      duration = duration + parseInt(a[0]);
    }
    return duration;
  },

  // Convert ISO 8061 format to MM:SS
  // TODO: Either filter out videos longer than 59:59 or extend to HH:MM:SS format
  convertYTDurationDisplay: function (duration) {
    duration = this.convertYTDuration(duration);
    var minutes = Math.floor(duration / 60) + "";
    if (minutes.length === 1) {
      minutes = "0" + minutes;
    }
    var seconds = duration % 60 + "";
    if (seconds.length === 1) {
      seconds = "0" + seconds;
    }
    return minutes + ":" + seconds;
  },

  searchYouTube: function (query) {
    var encodedQuery = encodeURIComponent(query);
    var searchUrl = 'https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=20&order=viewCount&q=' + encodedQuery + '&key=' + YOUTUBE_API_KEY;
    var context = this;
    $.ajax({
      type: "GET",
      url: searchUrl,
      success: function (response) {
        var results = [];
        var resultsIds = [];
        response.items.forEach(function (e) {
          if (e.id.videoId) {
            results.push({
              img: e.snippet.thumbnails.default.url,
              title: e.snippet.title,
              id: e.id.videoId
            });
            resultsIds.push(e.id.videoId);
          }
        });
        var videoIds = "";
        for (var i = 0; i < results.length; i++) {
          videoIds += results[i].id + ',';
        }
        var videoMap = {};
        var durationSearchUrl = 'https://www.googleapis.com/youtube/v3/videos?id=' + videoIds + '&part=contentDetails&key=' + YOUTUBE_API_KEY;
        $.ajax({
          type: "GET",
          url: durationSearchUrl,
          success: function (response) {
            response.items.forEach(function (e) {
              videoMap[e.id] = e.contentDetails.duration;
            });
            for (var j = 0; j < results.length; j++) {
              results[j].duration = context.convertYTDuration(videoMap[results[j].id]);
              results[j].durationDisplay = context.convertYTDurationDisplay(videoMap[results[j].id]);
            }
            $(".searchResultItem").remove();
            results.forEach(function (e) {
              // TODO Consult with group on refactoring this line - horrible as is
              $('#searchResults').append('

 ' + (e.title).slice(0, 35) + '...' + '

 | ' + e.durationDisplay + '

');
            });
            $(".searchResultItem").on('click', function (e) {
              if ($(e.target).attr('className') === 'searchResultTitle') {
                loadVideo($(e.target).attr('data-id'), 0);
                addSongToPlaylist({title: $(e.target).attr('data-title'), id: $(e.target).attr('data-id'), duration: $(e.target).attr('data-duration'), durationDisplay: $(e.target).attr('data-durationDisplay')});
              }
            });
          }
        });
      }
    });
  },

  onChange: function (e) {
    e.preventDefault();
    this.setState({text: e.target.value});
  },

  render: function () {

    var style = {
      borderColor: '#EEEEEE',
      position: 'absolute',
      top: 0,
      width: '100%'

    };

    var searchBarInputStyle = {
      backgroundColor: '#AAAAAA',
      borderColor: '#EEEEEE'
    };

    var searchResultsStyle = {
      marginTop: '50px'
    };

    return (

        <form style={style} onSubmit={this.handleSubmit}>
          <input style={searchBarInputStyle} onChange={this.onChange} value={this.state.text} className="form-control" placeholder="Search YouTube"/>
        </form>

    );
  }
});

var MediaAdd = React.createClass({
  render: function() {
    var style ={
      background: '#222222',
      border: '2px solid #444444',
      position: 'absolute',
      width: '100%',
      height: '50%',
      overflow: 'auto',
      top: '0'
    };
    return (

        <SearchBar />

    );
  }
});<|endoftext|>


<commit_before>(function (util, makeList, makeObservable, makeObservableList, window) {
    'use strict';
    /*global 'util', 'makeList', 'makeObservable', 'makeObservableList', 'window'*/

    var makeProperty,
        stack = makeList(),
        // Flag to indicate that properties can only add themselves as
        // dependencies iff the property at the top of the stack has
        // the same owner. By default this is set to false, meaning that
        // if a property were to call another property of a different
        // owner then the property called would be marked as a dependency.
        // This value is never changed at runtime.
        strictDependencies = false;

    stack.pushProperty = function (property) {
        if (this.length) {
            if (!strictDependencies || this.peek().owner === property.owner) {
                this.push(property);
            }
        } else {
            this.push(property);
        }
    };
    stack.addDependency = function (property) {
        if (this.length) {
            if (!strictDependencies || this.peek().owner === property.owner) {
                this.peek().dependencies().add(property);
            }
        }
    };

    makeProperty = function (options) {
        var writing = false,
            dependencies = makeList(),
            subscriptions = [],
            setter,
            getter,
            memo,
            property,
            fn,
            observer = function () {
                memo = undefined;
                property.notify();
            };

        dependencies.add = function (prop) {
            if (!this.contains(prop)) {
                this.push(prop);
                subscriptions.push(prop.subscribe(observer));
            }
        };

        property = {
            equals: function (b) {
                var a = this.get();
                b = makeProperty.get(b);

                a = a ? a.valueOf() : a;
                b = b ? b.valueOf() : b;

                return a === b;
            },
            changed: function (b) {
                var a = this.get();
                b = makeProperty.get(b);

                a = a ? a.valueOf() : a;
                b = b ? b.valueOf() : b;

                return a !== b;
            },
            get: function () {
                if (!writing) {
                    stack.addDependency(this);
                    stack.pushProperty(this);
                }

                var result = memo === undefined ? getter.call(this.owner) : memo;
                memo = result;

                if (stack[stack.length - 1] === this) {
                    stack.pop();
                }

                return result;
            },
            set: function (value) {
                // Check if the property is writable.
                if (typeof setter === 'function') {
                    writing = true;

                    if (!this.equals(value) || this.changed(value)) {
                        memo = undefined;
                        setter.call(this.owner, value);
                        this.notify();
                    }

                    writing = false;
                }
            },
            dependencies: function () {
                return dependencies;
            },
            isDependent: function () {
                return dependencies.length !== 0;
            },
            toString: function () {
                return util.object.toString(this.get());
            },
            valueOf : function () {
                var value = this.get();
                return util.object.isNil(value) ? value : value.valueOf();
            }
        };

        util.object.mixin(property, makeObservable());

        // Initialization.
        (function () {
            var value,
                self = property,
                lazy = false,
                isObject = util.object.isObject,
                isArray = util.object.isArray,
                adheresTo = util.object.adheresTo;

            self.owner = undefined;

            // Just a getter function.
            if (typeof options === 'function') {
                getter = options;
            // {get[, set, lazy, changed, equals, owner]}
            } else if (isObject(options) && (typeof options.get === 'function' || typeof options.set === 'function')) {
                lazy = options.lazy;
                getter = options.get;
                setter = typeof options.set === 'function' ? options.set : null;
                self.equals = typeof options.equals === 'function' ? options.equals : self.equals;
                self.changed = typeof options.changed === 'function' ? options.changed : self.changed;
                self.owner = options.owner;
            } else {
                // {value[, changed, equqls, owner]}
                if (isObject(options)) {
                    self.equals = typeof options.equals === 'function' ? options.equals : self.equals;
                    self.changed = typeof options.changed === 'function' ? options.changed : self.changed;
                    value = options.value;
                    self.owner = options.owner;
                // Just the value.
                } else {
                    value = options;
                }

                // Make all Arrays into ObservableLists.
                if (isArray(value) && !adheresTo(value, makeObservable.interfce)) {
                    value = makeObservableList(value);

                    // For array values the equals and changed operators
                    // specified in the options are opertors for testing items in the list
                    // not for operating on individual lists themselves.

                    // Override the item operators for the newly created ObservableList
                    // so that the item operators are taken from the options.
                    value.getItemOperators = (function (equals, changed) {
                        return function () {
                            return {equals: equals, changed: changed};
                        };
                    }(self.equals, self.changed));

                    self.equals = function (b) {
                        b = makeProperty.get(b);
                        return value.equals(b);
                    };
                    self.changed = function (b) {
                        b = makeProperty.get(b);
                        return value.changed(b);
                    };
                }

                // If the value is observable then we observe it for notifications.
                if (value && typeof value.subscribe === 'function' && typeof value.dispose === 'function') {
                    subscriptions.push(value.subscribe(observer));
                }

                getter = function () {
                    return value;
                };
                setter = function (v) {
                    if (adheresTo(value, makeList.interfce)) {
                        value.clear();

                        if (isArray(v)) {
                            value.push.apply(value, v);
                        } else {
                            value.push(v);
                        }
                    } else if (isArray(value)) {
                        while (value.length) {
                            value.pop();
                        }

                        if (isArray(v)) {
                            value.push.apply(value, v);
                        } else {
                            value.push(v);
                        }
                    } else if (value !== v) {
                        value = v;
                    }
                };
            }

            self.dispose = (function (base) {
                return function () {
                    while (subscriptions.length) {
                        subscriptions.pop().dispose();
                    }
                    while (dependencies.length) {
                        dependencies.pop();
                    }
                    base.call(this);
                };
            }(self.dispose));

            // Watch dependent properties automatically
            // if they are not 'lazy'. If we are lazy then
            // dependent properties will not be tracked until
            // we have been read at least once.
            if (!lazy) {
                self.get();
            }

            // Create the functional property 'fn'.
            fn = function (value) {
                var ret,
                    origOwner = fn.owner;

                // Temporarily set the owner to the 'this' object.
                if (this !== window) {
                    fn.owner = this;
                }

                if (arguments.length) {
                    fn.set(value);
                    ret = this;
                } else {
                    ret = fn.get();
                }

                fn.owner = origOwner;

                return ret;
            };

            util.object.mixin(fn, property);
        }());

        // We can return either the property (object) or fn (functional property).
        return fn;
    };

    // Convenience method to retrieve the value of the specified property.
    // If the specified property is not a property then returns property.
    makeProperty.get = function (property) {
        if (property && typeof property.get === 'function') {
            return property.get();
        }
        return property;
    };

    makeProperty.interfce = util.object.mixin({
        owner: '*',
        get: 'function',
        set: 'function',
        equals: 'function',
        changed: 'function'
    }, makeObservable.interfce);

    return makeProperty;
}(util, makeList, makeObservable, makeObservableList, window));<commit_msg>Added clearMemo() to properties so that properties can be forced to be computed<commit_after>(function (util, makeList, makeObservable, makeObservableList, window) {
    'use strict';
    /*global 'util', 'makeList', 'makeObservable', 'makeObservableList', 'window'*/

    var makeProperty,
        stack = makeList(),
        // Flag to indicate that properties can only add themselves as
        // dependencies iff the property at the top of the stack has
        // the same owner. By default this is set to false, meaning that
        // if a property were to call another property of a different
        // owner then the property called would be marked as a dependency.
        // This value is never changed at runtime.
        strictDependencies = false;

    stack.pushProperty = function (property) {
        if (this.length) {
            if (!strictDependencies || this.peek().owner === property.owner) {
                this.push(property);
            }
        } else {
            this.push(property);
        }
    };
    stack.addDependency = function (property) {
        if (this.length) {
            if (!strictDependencies || this.peek().owner === property.owner) {
                this.peek().dependencies().add(property);
            }
        }
    };

    makeProperty = function (options) {
        var writing = false,
            dependencies = makeList(),
            subscriptions = [],
            setter,
            getter,
            memo,
            property,
            fn,
            observer = function () {
                memo = undefined;
                property.notify();
            };

        dependencies.add = function (prop) {
            if (!this.contains(prop)) {
                this.push(prop);
                subscriptions.push(prop.subscribe(observer));
            }
        };

        property = {
            equals: function (b) {
                var a = this.get();
                b = makeProperty.get(b);

                a = a ? a.valueOf() : a;
                b = b ? b.valueOf() : b;

                return a === b;
            },
            changed: function (b) {
                var a = this.get();
                b = makeProperty.get(b);

                a = a ? a.valueOf() : a;
                b = b ? b.valueOf() : b;

                return a !== b;
            },
            clearMemo: function () {
                memo = undefined;
            },
            get: function () {
                if (!writing) {
                    stack.addDependency(this);
                    stack.pushProperty(this);
                }

                var result = memo === undefined ? getter.call(this.owner) : memo;
                memo = result;

                if (stack[stack.length - 1] === this) {
                    stack.pop();
                }

                return result;
            },
            set: function (value) {
                // Check if the property is writable.
                if (typeof setter === 'function') {
                    writing = true;

                    if (!this.equals(value) || this.changed(value)) {
                        memo = undefined;
                        setter.call(this.owner, value);
                        this.notify();
                    }

                    writing = false;
                }
            },
            dependencies: function () {
                return dependencies;
            },
            isDependent: function () {
                return dependencies.length !== 0;
            },
            toString: function () {
                return util.object.toString(this.get());
            },
            valueOf : function () {
                var value = this.get();
                return util.object.isNil(value) ? value : value.valueOf();
            }
        };

        util.object.mixin(property, makeObservable());

        // Initialization.
        (function () {
            var value,
                self = property,
                lazy = false,
                isObject = util.object.isObject,
                isArray = util.object.isArray,
                adheresTo = util.object.adheresTo;

            self.owner = undefined;

            // Just a getter function.
            if (typeof options === 'function') {
                getter = options;
            // {get[, set, lazy, changed, equals, owner]}
            } else if (isObject(options) && (typeof options.get === 'function' || typeof options.set === 'function')) {
                lazy = options.lazy;
                getter = options.get;
                setter = typeof options.set === 'function' ? options.set : null;
                self.equals = typeof options.equals === 'function' ? options.equals : self.equals;
                self.changed = typeof options.changed === 'function' ? options.changed : self.changed;
                self.owner = options.owner;
            } else {
                // {value[, changed, equqls, owner]}
                if (isObject(options)) {
                    self.equals = typeof options.equals === 'function' ? options.equals : self.equals;
                    self.changed = typeof options.changed === 'function' ? options.changed : self.changed;
                    value = options.value;
                    self.owner = options.owner;
                // Just the value.
                } else {
                    value = options;
                }

                // Make all Arrays into ObservableLists.
                if (isArray(value) && !adheresTo(value, makeObservable.interfce)) {
                    value = makeObservableList(value);

                    // For array values the equals and changed operators
                    // specified in the options are opertors for testing items in the list
                    // not for operating on individual lists themselves.

                    // Override the item operators for the newly created ObservableList
                    // so that the item operators are taken from the options.
                    value.getItemOperators = (function (equals, changed) {
                        return function () {
                            return {equals: equals, changed: changed};
                        };
                    }(self.equals, self.changed));

                    self.equals = function (b) {
                        b = makeProperty.get(b);
                        return value.equals(b);
                    };
                    self.changed = function (b) {
                        b = makeProperty.get(b);
                        return value.changed(b);
                    };
                }

                // If the value is observable then we observe it for notifications.
                if (value && typeof value.subscribe === 'function' && typeof value.dispose === 'function') {
                    subscriptions.push(value.subscribe(observer));
                }

                getter = function () {
                    return value;
                };
                setter = function (v) {
                    if (adheresTo(value, makeList.interfce)) {
                        value.clear();

                        if (isArray(v)) {
                            value.push.apply(value, v);
                        } else {
                            value.push(v);
                        }
                    } else if (isArray(value)) {
                        while (value.length) {
                            value.pop();
                        }

                        if (isArray(v)) {
                            value.push.apply(value, v);
                        } else {
                            value.push(v);
                        }
                    } else if (value !== v) {
                        value = v;
                    }
                };
            }

            self.dispose = (function (base) {
                return function () {
                    while (subscriptions.length) {
                        subscriptions.pop().dispose();
                    }
                    while (dependencies.length) {
                        dependencies.pop();
                    }
                    base.call(this);
                };
            }(self.dispose));

            // Watch dependent properties automatically
            // if they are not 'lazy'. If we are lazy then
            // dependent properties will not be tracked until
            // we have been read at least once.
            if (!lazy) {
                self.get();
            }

            // Create the functional property 'fn'.
            fn = function (value) {
                var ret,
                    origOwner = fn.owner;

                // Temporarily set the owner to the 'this' object.
                if (this !== window) {
                    fn.owner = this;
                }

                if (arguments.length) {
                    fn.set(value);
                    ret = this;
                } else {
                    ret = fn.get();
                }

                fn.owner = origOwner;

                return ret;
            };

            util.object.mixin(fn, property);
        }());

        // We can return either the property (object) or fn (functional property).
        return fn;
    };

    // Convenience method to retrieve the value of the specified property.
    // If the specified property is not a property then returns property.
    makeProperty.get = function (property) {
        if (property && typeof property.get === 'function') {
            return property.get();
        }
        return property;
    };

    makeProperty.interfce = util.object.mixin({
        owner: '*',
        clearMemo: 'function',
        get: 'function',
        set: 'function',
        equals: 'function',
        changed: 'function'
    }, makeObservable.interfce);

    return makeProperty;
}(util, makeList, makeObservable, makeObservableList, window));<|endoftext|>


<commit_before>

export default class FirstPassCache {
    constructor() {
        this._passedFiles = [];
        this._firstPassHandled = false;
    }

    pass(filePath) {
        if (this._firstPassHandled) {
            // Return false to indicate that this is the
            // first pass thru for this file.
            return false;
        } else if (this._passedFiles.indexOf(filePath) !== -1) {
            // Mark that the first pass is over and return true.
            this._firstPassHandled = true;
            this._passedFiles = null;
            return false;
        } else {
            // Mark that this file has passed once already.
            this._passedFiles.push(filePath);
            return true;
        }
    }
};
<commit_msg>Document the FirstPassCache helper class<commit_after>
/**
 * Helper class to keep track of files that
 * have passed through the stream.
 */
export default class FirstPassCache {
    constructor() {
        this._passedFiles = [];
        this._firstPassHandled = false;
    }
    /**
     * Marks that the given file has passed through.
     * @param {string} filePath File that is passing through
     * @return {boolean} True if this is still the first pass,
     *      false if ANY file (this or previous) has already
     *      been passed through twice.
     */
    pass(filePath) {
        if (this._firstPassHandled) {
            // Return false to indicate that this is the
            // first pass thru for this file.
            return false;
        } else if (this._passedFiles.indexOf(filePath) !== -1) {
            // Mark that the first pass is over and return true.
            this._firstPassHandled = true;
            this._passedFiles = null;
            return false;
        } else {
            // Mark that this file has passed once already.
            this._passedFiles.push(filePath);
            return true;
        }
    }
};
<|endoftext|>


<commit_before>#!/usr/bin/env node

var FATB = require('../lib/fromatobree');
var path = require('path');
var whodis = path.basename(process.argv[1]);

if (process.argv.length < 3) {
  console.log("From A to Bree v%s", FATB.version);
  console.log("usage:");
  console.log("%s <start> <finish> - plan route", whodis);
  console.log("%s lookup <place> - lookup place", whodis);
  console.log("%s listregions - lists regions", whodis);
  console.log("%s listplaces <region> - list places for a given region", whodis);
  console.log("%s listreqs <term> - list codes for factions or quests", whodis);
  console.log("\nto impose restrictions, create a config file called .fromatobree.json in your");
  console.log(" home directory. The format is:");
  var exampleConfig = { weighting: true, level: 40, standing: ["Q1", "R1"] };
  console.log("%s", JSON.stringify(exampleConfig, null, 2));
  console.log("key:");
  console.log("weighting - use weighted route, this means some destinations will become");
  console.log("            unavailable because you lack the requirements.");
  console.log("level     - your current level in the game.");
  console.log("standing  - any faction reputation or quests you may have completed. use");
  console.log("            the 'listreqs' command  to see a list of codes");

  return;
}

function getConfig() {
  var tilde = process.env[(process.platform === 'win32') ? "USERPROFILE" : "HOME"];
  var dotFileName = path.join(tilde, '.fromatobree.json');
console.log(dotFileName);
  var opts_from_file = {};
  try {
    var fs = require('fs');
    var dotfile = JSON.parse(fs.readFileSync(dotFileName));
    opts_from_file.weighting = dotfile.weighting;
    opts_from_file.level = dotfile.level;
    opts_from_file.standing = dotfile.standing;
  } catch(e) {
    // no config file, use optimist defaults
    if (e.errno !== 34) {
      console.log(e);
    }
  }

  return opts_from_file;
}
var options = getConfig();
// local testing { weighting: true, level: 50, standing: ["Q1"]};

var fatb = new FATB(options);
var startArg = process.argv[2];
var finishArg = process.argv[3];

//FIXME: use a better args parser!
if (startArg === "listplaces") {
  console.log("Regions in the %j:\n", finishArg, fatb.GetPlacesByRegion(finishArg));
  return;
}

if (startArg === "listregions") {
  console.log("list regions");

  console.log("%j", fatb.GetRegions());
  return;
}

if (startArg === "lookup") {
  console.log("Matches for %s:\n\t%s", finishArg, JSON.stringify(fatb.GetPlace(finishArg)));
  return;
}

var start = fatb.GetPlace(startArg)[0]; // get first
var finish = fatb.GetPlace(finishArg)[0]; // get first

console.log("From A to Bree v%s\n", FATB.version);
console.log("From: %s To: %s\n", start, finish);

if (typeof start === "undefined" || typeof finish === "undefined") {
  console.log("No matches for either start (%s) or finish (%s) locations", startArg, finishArg);
  return;
}

var route  = fatb.FindPath(start, finish);
console.log("Your route:");
route.forEach(function(name) {
  console.log("\t%s", name);
});

var cost = fatb.GetTotalCost(route);
var time = fatb.GetTotalTime(route);

console.log("\nTotal cost for route %d in silver, and the journey will take %s.\n", cost, time > 60 ? Math.round(time/60) + " mins" : time + " seconds");

<commit_msg>wired up client to GetRequirements<commit_after>#!/usr/bin/env node

var FATB = require('../lib/fromatobree');
var path = require('path');
var whodis = path.basename(process.argv[1]);

console.log("From A to Bree v%s\n", FATB.version);

if (process.argv.length < 3) {
  console.log("usage:");
  console.log("%s <start> <finish>    - plan route", whodis);
  console.log("%s lookup <place>      - lookup place", whodis);
  console.log("%s listregions         - lists regions", whodis);
  console.log("%s listplaces <region> - list places for a given region", whodis);
  console.log("%s listreqs <term> - list codes for factions or quests", whodis);
  console.log("\nto impose restrictions, create a config file called .fromatobree.json in your");
  console.log("home directory. The format is:");
  var exampleConfig = { weighting: true, level: 40, standing: ["Q1", "R1"] };
  console.log("%s", JSON.stringify(exampleConfig, null, 2));
  console.log("key:");
  console.log("weighting - use weighted route, this means some destinations will become");
  console.log("            unavailable because you lack the requirements.");
  console.log("level     - your current level in the game.");
  console.log("standing  - any faction reputation or quests you may have completed. use");
  console.log("            the 'listreqs' command  to see a list of codes");

  return;
}

function getConfig() {
  var tilde = process.env[(process.platform === 'win32') ? "USERPROFILE" : "HOME"];
  var dotFileName = path.join(tilde, '.fromatobree.json');
  var opts_from_file = {};
  try {
    var fs = require('fs');
    var dotfile = JSON.parse(fs.readFileSync(dotFileName));
    opts_from_file.weighting = dotfile.weighting;
    opts_from_file.level = dotfile.level;
    opts_from_file.standing = dotfile.standing;
  } catch(e) {
    // no config file, use optimist defaults
    if (e.errno !== 34) {
      console.log(e);
    }
  }

  return opts_from_file;
}
var options = getConfig();
// local testing { weighting: true, level: 50, standing: ["Q1"]};

var fatb = new FATB(options);
var startArg = process.argv[2];
var finishArg = process.argv[3];

if (startArg === "listplaces") {
  console.log("Regions in the %s:", finishArg);
  fatb.GetPlacesByRegion(finishArg).forEach(function(place) {
    console.log("\t%s", place);
  });
  return;
}

if (startArg === "listregions") {
  console.log("List regions");

  fatb.GetRegions().forEach(function(region) {
    console.log("\t%s", region);
  });
  return;
}

if (startArg === "listreqs") {
  console.log("List standing/quest requirement codes");
  if (typeof(finishArg) !== "undefined") {
    console.log("\nMatching term: %s", finishArg);
  }

  var reqs = fatb.GetRequirements(finishArg);
  if (Object.keys(reqs).length === 0) {
    console.log("\nNothing found!");
    return;
  }
  console.log("\nCode\tDescription");
  for(var code in reqs) {
    console.log("%s\t%s", code, reqs[code]);
  }
  return;
}

if (startArg === "lookup") {
  console.log("Matches for %s:\n\t%s", finishArg, JSON.stringify(fatb.GetPlace(finishArg)));
  return;
}

var start = fatb.GetPlace(startArg)[0]; // get first
var finish = fatb.GetPlace(finishArg)[0]; // get first

console.log("From: %s To: %s\n", start, finish);

if (typeof start === "undefined" || typeof finish === "undefined") {
  console.log("No matches for either start (%s) or finish (%s) locations", startArg, finishArg);
  return;
}

var route  = fatb.FindPath(start, finish);
console.log("Your route:");
route.forEach(function(name) {
  console.log("\t%s", name);
});

var cost = fatb.GetTotalCost(route);
var time = fatb.GetTotalTime(route);

console.log("\nTotal cost for route %d in silver, and the journey will take %s.\n", cost, time > 60 ? Math.round(time/60) + " mins" : time + " seconds");

<|endoftext|>


<commit_before>const POD_CONTAINER_STATUS = {
  CREATED: {
    dotClassName: "dot inactive unknown",
    textClassName: "",
    displayName: "Created",
    healthStatus: "NA"
  },
  STAGING: {
    dotClassName: "dot inactive unknown",
    textClassName: "",
    displayName: "Staging",
    healthStatus: "NA"
  },
  STARTING: {
    dotClassName: "dot inactive unknown",
    textClassName: "",
    displayName: "Starting",
    healthStatus: "NA"
  },
  STARTED: {
    dotClassName: "dot inactive unknown",
    textClassName: "",
    displayName: "Started",
    healthStatus: "NA"
  },
  HEALTHY: {
    dotClassName: "dot healthy",
    textClassName: "task-status-running",
    displayName: "Running",
    healthStatus: "HEALTHY"
  },
  UNHEALTHY: {
    dotClassName: "dot unhealthy",
    textClassName: "task-status-running",
    displayName: "Unhealthy",
    healthStatus: "UNHEALTHY"
  },
  RUNNING: {
    dotClassName: "dot running",
    textClassName: "task-status-running",
    displayName: "Running",
    healthStatus: "NA"
  },
  ERROR: {
    dotClassName: "dot danger",
    textClassName: "task-status-error",
    displayName: "Error",
    healthStatus: "UNHEALTHY"
  },
  FAILED: {
    dotClassName: "dot danger",
    textClassName: "task-status-error",
    displayName: "Failed",
    healthStatus: "UNHEALTHY"
  },
  KILLING: {
    dotClassName: "dot danger",
    textClassName: "",
    displayName: "Killing",
    healthStatus: "UNHEALTHY"
  },
  KILLED: {
    dotClassName: "dot inactive danger",
    textClassName: "",
    displayName: "Killed",
    healthStatus: "NA"
  },
  FINISHED: {
    dotClassName: "dot inactive danger",
    textClassName: "",
    displayName: "Completed",
    healthStatus: "NA"
  },
  LOST: {
    dotClassName: "dot inactive danger",
    textClassName: "",
    displayName: "Lost",
    healthStatus: "NA"
  },
  NA: {
    dotClassName: "dot inactive unknown",
    textClassName: "",
    displayName: "N/A",
    healthStatus: "NA"
  }
};

module.exports = POD_CONTAINER_STATUS;
<commit_msg>feat(PodContainerStatus): marked displayName keys for translation<commit_after>import { i18nMark } from "@lingui/react";

const POD_CONTAINER_STATUS = {
  CREATED: {
    dotClassName: "dot inactive unknown",
    textClassName: "",
    displayName: i18nMark("Created"),
    healthStatus: "NA"
  },
  STAGING: {
    dotClassName: "dot inactive unknown",
    textClassName: "",
    displayName: i18nMark("Staging"),
    healthStatus: "NA"
  },
  STARTING: {
    dotClassName: "dot inactive unknown",
    textClassName: "",
    displayName: i18nMark("Starting"),
    healthStatus: "NA"
  },
  STARTED: {
    dotClassName: "dot inactive unknown",
    textClassName: "",
    displayName: i18nMark("Started"),
    healthStatus: "NA"
  },
  HEALTHY: {
    dotClassName: "dot healthy",
    textClassName: "task-status-running",
    displayName: i18nMark("Running"),
    healthStatus: "HEALTHY"
  },
  UNHEALTHY: {
    dotClassName: "dot unhealthy",
    textClassName: "task-status-running",
    displayName: i18nMark("Unhealthy"),
    healthStatus: "UNHEALTHY"
  },
  RUNNING: {
    dotClassName: "dot running",
    textClassName: "task-status-running",
    displayName: i18nMark("Running"),
    healthStatus: "NA"
  },
  ERROR: {
    dotClassName: "dot danger",
    textClassName: "task-status-error",
    displayName: i18nMark("Error"),
    healthStatus: "UNHEALTHY"
  },
  FAILED: {
    dotClassName: "dot danger",
    textClassName: "task-status-error",
    displayName: i18nMark("Failed"),
    healthStatus: "UNHEALTHY"
  },
  KILLING: {
    dotClassName: "dot danger",
    textClassName: "",
    displayName: i18nMark("Killing"),
    healthStatus: "UNHEALTHY"
  },
  KILLED: {
    dotClassName: "dot inactive danger",
    textClassName: "",
    displayName: i18nMark("Killed"),
    healthStatus: "NA"
  },
  FINISHED: {
    dotClassName: "dot inactive danger",
    textClassName: "",
    displayName: i18nMark("Completed"),
    healthStatus: "NA"
  },
  LOST: {
    dotClassName: "dot inactive danger",
    textClassName: "",
    displayName: i18nMark("Lost"),
    healthStatus: "NA"
  },
  NA: {
    dotClassName: "dot inactive unknown",
    textClassName: "",
    displayName: i18nMark("N/A"),
    healthStatus: "NA"
  }
};

module.exports = POD_CONTAINER_STATUS;
<|endoftext|>


<commit_before>import Controller from '@ember/controller';

export default Controller.extend({
  queryParams: {
    leadershipDetails: 'leadershipDetails',
    manageLeadership: 'manageLeadership',
  },
  leadershipDetails: false,
  manageLeadership: false,
});
<commit_msg>modernizes another ci report controller.<commit_after>import Controller from '@ember/controller';
import { tracked } from '@glimmer/tracking';

export default class CurriculumInventoryReportController extends Controller {
  queryParams = ['leadershipDetails', 'manageLeadership'];

  @tracked leadershipDetails = false;
  @tracked manageLeadership = false;
}
<|endoftext|>


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

    angular
        .module('ALEX.controller')
        .controller('SymbolsController', SymbolsController);

    SymbolsController.$inject = ['$scope', 'SessionService', 'Symbol', 'SymbolGroup', '_', 'ToastService'];

    /**
     * The controller that handles CRUD operations on symbols and symbol groups.
     *
     * The template can be found at 'views/pages/symbols.html'.
     *
     * @param $scope - angular scope object
     * @param Session - The SessionService
     * @param Symbol - The Symbol factory
     * @param SymbolGroup - The SymbolGroup factory
     * @param _ - Lodash
     * @param Toast - The ToastService
     * @constructor
     */
    function SymbolsController($scope, Session, Symbol, SymbolGroup, _, Toast) {

        /**
         * The project that is saved in the session
         * @type {Project}
         */
        $scope.project = Session.project.get();

        /**
         * indicates if symbol groups are displayed collapsed
         * @type {boolean}
         */
        $scope.groupsCollapsed = false;

        /**
         * The model for selected symbols
         * @type {Symbol[]}
         */
        $scope.selectedSymbols = [];

        /**
         * The symbol groups that belong to the project
         * @type {SymbolGroup}
         */
        $scope.groups = [];

        // fetch all symbol groups and include all symbols
        (function init() {
            SymbolGroup.Resource.getAll($scope.project.id, {embedSymbols: true})
                .then(function (groups) {
                    $scope.groups = groups;
                })
        }());

        /**
         * Finds the symbol group object from a given symbol. Returns undefined if no symbol group was found.
         *
         * @param symbol - The symbol whose group object should be found
         * @returns {SymbolGroup|undefined} - The found symbol group or undefined
         */
        function findGroupFromSymbol(symbol) {
            return _.find($scope.groups, {id: symbol.group});
        }

        /**
         * Extracts all symbols from all symbol groups and merges them into a single array
         *
         * @returns {Symbol[]}
         */
        $scope.getAllSymbols = function () {
            return _.flatten(_.pluck($scope.groups, 'symbols'));
        };

        /**
         * Adds a single new symbol to the scope by finding its corresponding group and adding it there
         *
         * @param {Symbol} symbol - The symbol that should be added
         */
        $scope.addSymbol = function (symbol) {
            findGroupFromSymbol(symbol).symbols.push(symbol)
        };

        /**
         * Removes a list of symbols from the scope by finding the group of each symbol and removing it from
         * it
         *
         * @param {Symbol[]} symbols - The symbols that should be removed
         */
        $scope.removeSymbols = function (symbols) {
            var group;
            _.forEach(symbols, function (symbol) {
                delete symbol._selected;
                delete symbol._collapsed;
                group = findGroupFromSymbol(symbol);
                _.remove(group.symbols, {id: symbol.id});
            })
        };

        /**
         * Updates an existing symbol
         *
         * @param {Symbol} updatedSymbol - The updated symbol object
         */
        $scope.updateSymbol = function (updatedSymbol) {
            $scope.updateSymbols([updatedSymbol]);
        };

        /**
         * Updates multiple existing symbols
         *
         * @param {Symbol[]} updatedSymbols - The updated symbol objects
         */
        $scope.updateSymbols = function (updatedSymbols) {
            var group;
            var i;
            _.forEach(updatedSymbols, function (symbol) {
                group = findGroupFromSymbol(symbol);
                i = _.findIndex(group.symbols, {id: symbol.id});
                if (i > -1) {
                    group.symbols[i].name = symbol.name;
                    group.symbols[i].abbreviation = symbol.abbreviation;
                    group.symbols[i].group = symbol.group;
                    group.symbols[i].revision = symbol.revision;
                }
            })
        };

        /**
         * Moves a list of existing symbols into another group.
         *
         * @param {Symbol[]} symbols - The symbols that should be moved
         * @param {SymbolGroup} group - The group the symbols should be moved into
         */
        $scope.moveSymbolsToGroup = function (symbols, group) {
            var grp = _.find($scope.groups, {id: group.id});

            _.forEach(symbols, function (symbol) {
                var g = _.find($scope.groups, {id: symbol.group});
                var i = _.findIndex(g.symbols, {id: symbol.id});
                g.symbols.splice(i, 1);
                symbol.group = group.id;
                grp.symbols.push(symbol);
            })
        };

        /**
         * Deletes a single symbol from the server and from the scope if the deletion was successful
         *
         * @param {Symbol} symbol - The symbol to be deleted
         */
        $scope.deleteSymbol = function (symbol) {
            Symbol.Resource.delete($scope.project.id, symbol)
                .then(function () {
                    Toast.success('Symbol ' + symbol.name + ' deleted');
                    $scope.removeSymbols([symbol]);
                })
                .catch(function (response) {
                    Toast.danger('
Deleting symbol failed
' + response.data.message);
                })
        };

        /**
         * Deletes all symbols that the user selected from the server and the scope, if the deletion was successful
         */
        $scope.deleteSelectedSymbols = function () {
            Symbol.Resource.deleteSome($scope.project.id, $scope.selectedSymbols)
                .then(function () {
                    Toast.success('Symbols deleted');
                    $scope.removeSymbols($scope.selectedSymbols);
                })
                .catch(function (response) {
                    Toast.danger('
Deleting symbols failed
' + response.data.message);
                })
        };

        /**
         * Adds a new symbol group to the scope
         *
         * @param {SymbolGroup} group - The group that should be added
         */
        $scope.addGroup = function (group) {
            $scope.groups.push(group);
        };

        /**
         * Updates a symbol group in the scope by changing its name property to the one of the groups that is passed
         * as a parameter
         *
         * @param {SymbolGroup} updatedGroup - The updated symbol group
         */
        $scope.updateGroup = function (updatedGroup) {
            _.find($scope.groups, {id: updatedGroup.id}).name = updatedGroup.name;
        };

        /**
         * Collapses all groups or expands them
         */
        $scope.toggleCollapseAllGroups = function () {
            $scope.groupsCollapsed = !$scope.groupsCollapsed;
            for (var i = 0; i < $scope.groups.length; i++) {
                $scope.groups[i]._collapsed = $scope.groupsCollapsed;
            }
        }
    }
}());<commit_msg>fix: symbol groups do not disappear after removal<commit_after>(function () {
    'use strict';

    angular
        .module('ALEX.controller')
        .controller('SymbolsController', SymbolsController);

    SymbolsController.$inject = ['$scope', 'SessionService', 'Symbol', 'SymbolGroup', '_', 'ToastService'];

    /**
     * The controller that handles CRUD operations on symbols and symbol groups.
     *
     * The template can be found at 'views/pages/symbols.html'.
     *
     * @param $scope - angular scope object
     * @param Session - The SessionService
     * @param Symbol - The Symbol factory
     * @param SymbolGroup - The SymbolGroup factory
     * @param _ - Lodash
     * @param Toast - The ToastService
     * @constructor
     */
    function SymbolsController($scope, Session, Symbol, SymbolGroup, _, Toast) {

        /**
         * The project that is saved in the session
         * @type {Project}
         */
        $scope.project = Session.project.get();

        /**
         * indicates if symbol groups are displayed collapsed
         * @type {boolean}
         */
        $scope.groupsCollapsed = false;

        /**
         * The model for selected symbols
         * @type {Symbol[]}
         */
        $scope.selectedSymbols = [];

        /**
         * The symbol groups that belong to the project
         * @type {SymbolGroup}
         */
        $scope.groups = [];

        // fetch all symbol groups and include all symbols
        (function init() {
            SymbolGroup.Resource.getAll($scope.project.id, {embedSymbols: true})
                .then(function (groups) {
                    $scope.groups = groups;
                })
        }());

        /**
         * Finds the symbol group object from a given symbol. Returns undefined if no symbol group was found.
         *
         * @param symbol - The symbol whose group object should be found
         * @returns {SymbolGroup|undefined} - The found symbol group or undefined
         */
        function findGroupFromSymbol(symbol) {
            return _.find($scope.groups, {id: symbol.group});
        }

        /**
         * Extracts all symbols from all symbol groups and merges them into a single array
         *
         * @returns {Symbol[]}
         */
        $scope.getAllSymbols = function () {
            return _.flatten(_.pluck($scope.groups, 'symbols'));
        };

        /**
         * Adds a single new symbol to the scope by finding its corresponding group and adding it there
         *
         * @param {Symbol} symbol - The symbol that should be added
         */
        $scope.addSymbol = function (symbol) {
            findGroupFromSymbol(symbol).symbols.push(symbol)
        };

        /**
         * Removes a list of symbols from the scope by finding the group of each symbol and removing it from
         * it
         *
         * @param {Symbol[]} symbols - The symbols that should be removed
         */
        $scope.removeSymbols = function (symbols) {
            var group;
            _.forEach(symbols, function (symbol) {
                delete symbol._selected;
                delete symbol._collapsed;
                group = findGroupFromSymbol(symbol);
                _.remove(group.symbols, {id: symbol.id});
            })
        };

        /**
         * Updates an existing symbol
         *
         * @param {Symbol} updatedSymbol - The updated symbol object
         */
        $scope.updateSymbol = function (updatedSymbol) {
            $scope.updateSymbols([updatedSymbol]);
        };

        /**
         * Updates multiple existing symbols
         *
         * @param {Symbol[]} updatedSymbols - The updated symbol objects
         */
        $scope.updateSymbols = function (updatedSymbols) {
            var group;
            var i;
            _.forEach(updatedSymbols, function (symbol) {
                group = findGroupFromSymbol(symbol);
                i = _.findIndex(group.symbols, {id: symbol.id});
                if (i > -1) {
                    group.symbols[i].name = symbol.name;
                    group.symbols[i].abbreviation = symbol.abbreviation;
                    group.symbols[i].group = symbol.group;
                    group.symbols[i].revision = symbol.revision;
                }
            })
        };

        /**
         * Moves a list of existing symbols into another group.
         *
         * @param {Symbol[]} symbols - The symbols that should be moved
         * @param {SymbolGroup} group - The group the symbols should be moved into
         */
        $scope.moveSymbolsToGroup = function (symbols, group) {
            var grp = _.find($scope.groups, {id: group.id});

            _.forEach(symbols, function (symbol) {
                var g = _.find($scope.groups, {id: symbol.group});
                var i = _.findIndex(g.symbols, {id: symbol.id});
                g.symbols.splice(i, 1);
                symbol.group = group.id;
                grp.symbols.push(symbol);
            })
        };

        /**
         * Deletes a single symbol from the server and from the scope if the deletion was successful
         *
         * @param {Symbol} symbol - The symbol to be deleted
         */
        $scope.deleteSymbol = function (symbol) {
            Symbol.Resource.delete($scope.project.id, symbol)
                .then(function () {
                    Toast.success('Symbol ' + symbol.name + ' deleted');
                    $scope.removeSymbols([symbol]);
                })
                .catch(function (response) {
                    Toast.danger('
Deleting symbol failed
' + response.data.message);
                })
        };

        /**
         * Deletes all symbols that the user selected from the server and the scope, if the deletion was successful
         */
        $scope.deleteSelectedSymbols = function () {
            Symbol.Resource.deleteSome($scope.project.id, $scope.selectedSymbols)
                .then(function () {
                    Toast.success('Symbols deleted');
                    $scope.removeSymbols($scope.selectedSymbols);
                })
                .catch(function (response) {
                    Toast.danger('
Deleting symbols failed
' + response.data.message);
                })
        };

        /**
         * Adds a new symbol group to the scope
         *
         * @param {SymbolGroup} group - The group that should be added
         */
        $scope.addGroup = function (group) {
            $scope.groups.push(group);
        };

        /**
         * Updates a symbol group in the scope by changing its name property to the one of the groups that is passed
         * as a parameter
         *
         * @param {SymbolGroup} updatedGroup - The updated symbol group
         */
        $scope.updateGroup = function (updatedGroup) {
            _.find($scope.groups, {id: updatedGroup.id}).name = updatedGroup.name;
        };

        /**
         * Removes a symbol group from the scope and also removes its symbols
         *
         * @param {SymbolGroup} group
         */
        $scope.deleteGroup = function(group){
            $scope.removeSymbols(group.symbols);
            _.remove($scope.groups, {id: group.id});
        };

        /**
         * Collapses all groups or expands them
         */
        $scope.toggleCollapseAllGroups = function () {
            $scope.groupsCollapsed = !$scope.groupsCollapsed;
            for (var i = 0; i < $scope.groups.length; i++) {
                $scope.groups[i]._collapsed = $scope.groupsCollapsed;
            }
        }
    }
}());<|endoftext|>


<commit_before>/* This file is part of Indico.
 * Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN).
 *
 * Indico is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 *
 * Indico is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Indico; if not, see <http://www.gnu.org/licenses/>.
 */

import {indicoAxios, handleAxiosError} from 'indico/utils/axios';

export const SET_KEYWORD = 'SET_KEYWORD';
export const SET_FILTER = 'SET_FILTER';
export const SET_PAGE = 'SET_PAGE';
export const UPDATE_ENTRIES = 'UPDATE_ENTRIES';
export const FETCH_STARTED = 'FETCH_STARTED';
export const FETCH_FAILED = 'FETCH_FAILED';
export const SET_DETAILED_VIEW = 'SET_DETAILED_VIEW';
export const VIEW_PREV_ENTRY = 'VIEW_PREV_ENTRY';
export const VIEW_NEXT_ENTRY = 'VIEW_NEXT_ENTRY';

export function setKeyword(keyword) {
    return {type: SET_KEYWORD, keyword};
}

export function setFilter(filter) {
    return {type: SET_FILTER, filter};
}

export function setPage(currentPage) {
    return {type: SET_PAGE, currentPage};
}

export function setDetailedView(entryIndex) {
    return {type: SET_DETAILED_VIEW, currentViewIndex: entryIndex};
}

export function viewPrevEntry() {
    return async (dispatch, getStore) => {
        const {
            staticData: {pageSize},
            logs: {currentViewIndex, currentPage}
        } = getStore();

        if (currentViewIndex === 0) {
            if (currentPage === 0) {
                // ERROR!
            } else {
                await dispatch(setPage(currentPage - 1));
                await dispatch(fetchPosts());
                await dispatch(setDetailedView(pageSize - 1));
            }
        } else {
            dispatch({type: SET_DETAILED_VIEW, currentViewIndex: currentViewIndex - 1});
        }
    };
}

export function viewNextEntry() {
    return async (dispatch, getStore) => {
        const {
            staticData: {pageSize},
            logs: {currentViewIndex, currentPage, pages}
        } = getStore();

        if (currentViewIndex === (pageSize - 1)) {
            if (currentPage === pages[pages.length - 1]) {
                // ERROR!
            } else {
                await dispatch(setPage(currentPage + 1));
                await dispatch(fetchPosts());
                await dispatch(setDetailedView(0));
            }
        } else {
            dispatch({type: SET_DETAILED_VIEW, currentViewIndex: currentViewIndex + 1});
        }
    };
}

export function updateEntries(entries, pages) {
    return {type: UPDATE_ENTRIES, entries, pages};
}

export function fetchStarted() {
    return {type: FETCH_STARTED};
}

export function fetchFailed() {
    return {type: FETCH_FAILED};
}

export function fetchPosts() {
    return async (dispatch, getStore) => {
        dispatch(fetchStarted());

        const {
            logs: {filters, keyword, currentPage},
            staticData: {fetchLogsUrl},
        } = getStore();

        const params = {
            page: currentPage,
            filters: [],
        };
        if (keyword) {
            params.q = keyword;
        }

        Object.entries(filters).forEach(([item, active]) => {
            if (active) {
                params.filters.push(item);
            }
        });

        let response;
        try {
            response = await indicoAxios.get(fetchLogsUrl, {params});
        } catch (error) {
            handleAxiosError(error);
            dispatch(fetchFailed());
            return;
        }
        const {entries, pages} = response.data;
        dispatch(updateEntries(entries, pages));
    };
}
<commit_msg>Set currentViewIndex before fetching logs<commit_after>/* This file is part of Indico.
 * Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN).
 *
 * Indico is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 *
 * Indico is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Indico; if not, see <http://www.gnu.org/licenses/>.
 */

import {indicoAxios, handleAxiosError} from 'indico/utils/axios';

export const SET_KEYWORD = 'SET_KEYWORD';
export const SET_FILTER = 'SET_FILTER';
export const SET_PAGE = 'SET_PAGE';
export const UPDATE_ENTRIES = 'UPDATE_ENTRIES';
export const FETCH_STARTED = 'FETCH_STARTED';
export const FETCH_FAILED = 'FETCH_FAILED';
export const SET_DETAILED_VIEW = 'SET_DETAILED_VIEW';
export const VIEW_PREV_ENTRY = 'VIEW_PREV_ENTRY';
export const VIEW_NEXT_ENTRY = 'VIEW_NEXT_ENTRY';

export function setKeyword(keyword) {
    return {type: SET_KEYWORD, keyword};
}

export function setFilter(filter) {
    return {type: SET_FILTER, filter};
}

export function setPage(currentPage) {
    return {type: SET_PAGE, currentPage};
}

export function setDetailedView(entryIndex) {
    return {type: SET_DETAILED_VIEW, currentViewIndex: entryIndex};
}

export function viewPrevEntry() {
    return async (dispatch, getStore) => {
        const {
            staticData: {pageSize},
            logs: {currentViewIndex, currentPage}
        } = getStore();

        if (currentViewIndex === 0) {
            if (currentPage === 0) {
                // ERROR!
            } else {
                await dispatch(setPage(currentPage - 1));
                await dispatch(fetchPosts());
                await dispatch(setDetailedView(pageSize - 1));
            }
        } else {
            dispatch({type: SET_DETAILED_VIEW, currentViewIndex: currentViewIndex - 1});
        }
    };
}

export function viewNextEntry() {
    return async (dispatch, getStore) => {
        const {
            staticData: {pageSize},
            logs: {currentViewIndex, currentPage, pages}
        } = getStore();

        if (currentViewIndex === (pageSize - 1)) {
            if (currentPage === pages[pages.length - 1]) {
                // ERROR!
            } else {
                await dispatch(setPage(currentPage + 1));
                await dispatch(setDetailedView(0));
                await dispatch(fetchPosts());
            }
        } else {
            dispatch({type: SET_DETAILED_VIEW, currentViewIndex: currentViewIndex + 1});
        }
    };
}

export function updateEntries(entries, pages) {
    return {type: UPDATE_ENTRIES, entries, pages};
}

export function fetchStarted() {
    return {type: FETCH_STARTED};
}

export function fetchFailed() {
    return {type: FETCH_FAILED};
}

export function fetchPosts() {
    return async (dispatch, getStore) => {
        dispatch(fetchStarted());

        const {
            logs: {filters, keyword, currentPage},
            staticData: {fetchLogsUrl},
        } = getStore();

        const params = {
            page: currentPage,
            filters: [],
        };
        if (keyword) {
            params.q = keyword;
        }

        Object.entries(filters).forEach(([item, active]) => {
            if (active) {
                params.filters.push(item);
            }
        });

        let response;
        try {
            response = await indicoAxios.get(fetchLogsUrl, {params});
        } catch (error) {
            handleAxiosError(error);
            dispatch(fetchFailed());
            return;
        }
        const {entries, pages} = response.data;
        dispatch(updateEntries(entries, pages));
    };
}
<|endoftext|>


<commit_before>var React = require('react');

var meetingRelationPropType = require('types/meetingRelationPropType');
var {attachMediaStream} = require('helpers/WebRTCAdapter');

var Broadcast = React.createClass({

  propTypes: {
    meetingRelation: meetingRelationPropType.isRequired,
    webRTC: React.PropTypes.object.isRequired,
  },

  getInitialState: function() {
    return {
      isConnectionLost: false
    };
  },

  componentDidMount: function() {
    this.attachWebRTCStream();
  },

  componentDidUpdate: function(prevProps, prevState) {
    if (prevProps.webRTC.localStream !== this.props.webRTC.localStream ||
        prevProps.webRTC.remoteStream !== this.props.webRTC.remoteStream) {
      this.attachWebRTCStream();
    }
  },

  attachWebRTCStream: function() {
    var {meetingRelation, webRTC} = this.props;
    var videoNode = this.refs['broadcast'].getDOMNode();
    var stream = meetingRelation.isHost
      ? webRTC.localStream
      : webRTC.remoteStream;

    attachMediaStream(videoNode, stream);
  },

  render: function() {
    var {meetingRelation} = this.props;

    return (
      <video
        ref="broadcast"
        muted={meetingRelation.isHost}
        autoPlay={true}
        {...this.props}
      />
    );
  }

});

module.exports = Broadcast;<commit_msg>Make sure we don't try to load a null path.<commit_after>var React = require('react');

var meetingRelationPropType = require('types/meetingRelationPropType');
var {attachMediaStream} = require('helpers/WebRTCAdapter');

var Broadcast = React.createClass({

  propTypes: {
    meetingRelation: meetingRelationPropType.isRequired,
    webRTC: React.PropTypes.object.isRequired,
  },

  getInitialState: function() {
    return {
      isConnectionLost: false
    };
  },

  componentDidMount: function() {
    this.attachWebRTCStream();
  },

  componentDidUpdate: function(prevProps, prevState) {
    if ((prevProps.webRTC.localStream !== this.props.webRTC.localStream ||
         prevProps.webRTC.remoteStream !== this.props.webRTC.remoteStream) &&
        this.props.webRTC.localStream !== null &&
        this.props.webRTC.remoteStream) {
      this.attachWebRTCStream();
    }
  },

  attachWebRTCStream: function() {
    var {meetingRelation, webRTC} = this.props;
    var videoNode = this.refs['broadcast'].getDOMNode();
    var stream = meetingRelation.isHost
      ? webRTC.localStream
      : webRTC.remoteStream;

    attachMediaStream(videoNode, stream);
  },

  render: function() {
    var {meetingRelation} = this.props;

    return (
      <video
        ref="broadcast"
        muted={meetingRelation.isHost}
        autoPlay={true}
        {...this.props}
      />
    );
  }

});

module.exports = Broadcast;<|endoftext|>