<commit_before>var OauthController = Ember.Controller.extend({
  showModal: false,
  beginFlow: function(oauthOptions) {
    this.deferred = new Ember.RSVP.defer();
    this.set('oauthOptions', oauthOptions);
    this.set('showModal', true);
    return this.deferred.promise;
  },
  approve: function(){
    // spawn the popup
    var oauthOptions = this.get('oauthOptions'),
        width = oauthOptions.width || 960,
        height = oauthOptions.height || 410;
    window.open(oauthOptions.authorizeUrl, "authwindow", "menubar=0,resizable=1,width=" + width + ",height=" + height);
    var self = this;
    function onmessage(e) {
      self.handleOauthCode(e);
      window.removeEventListener("message", onmessage);
    }
    window.addEventListener("message", onmessage);
  },
  handleOauthCode: function(event){
    if (event.origin !== document.location.origin) {
      Ember.Logger.debug('Invalid origin: ' + event.origin + ' vs ' + document.location.origin);
      return;
    }
    this.deferred.resolve(event.data);
  },
  decline: function(){
    this.set('showModal', false);
    this.deferred.reject("declined");
  },
});
export = OauthController;
<commit_msg>decode access token<commit_after>var OauthController = Ember.Controller.extend({
  showModal: false,
  beginFlow: function(oauthOptions) {
    this.deferred = new Ember.RSVP.defer();
    this.set('oauthOptions', oauthOptions);
    this.set('showModal', true);
    return this.deferred.promise;
  },
  approve: function(){
    // spawn the popup
    var oauthOptions = this.get('oauthOptions'),
        width = oauthOptions.width || 960,
        height = oauthOptions.height || 410;
    window.open(oauthOptions.authorizeUrl, "authwindow", "menubar=0,resizable=1,width=" + width + ",height=" + height);
    var self = this;
    function onmessage(e) {
      self.handleOauthCode(e);
      window.removeEventListener("message", onmessage);
    }
    window.addEventListener("message", onmessage);
  },
  handleOauthCode: function(event){
    if (event.origin !== document.location.origin) {
      Ember.Logger.debug('Invalid origin: ' + event.origin + ' vs ' + document.location.origin);
      return;
    }
    var results = {};
    var params = event.data.split('&');
    for (var i = 0; i < params.length; i++) {
      var param = params[i],
          pair = param.split('=');
      results[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
    }
    this.deferred.resolve(results.access_token);
  },
  decline: function(){
    this.set('showModal', false);
    this.deferred.reject("declined");
  },
});
export = OauthController;
<|endoftext|>


<commit_before>/* List screen to view, add, or delete plots */

//get transectID from calling window
var args = arguments[0];
var transectID = args.transectID;
$.tbl.transectID = transectID;
var siteID = args.siteID;

populateTable();
toggleAddBtn();

/* Nav Bar Label */

// Build title label
var parkName = "";
var transectName ="";

try {
	var db = Ti.Database.open('ltemaDB');

	resultRow = db.execute (	'SELECT p.park_name, t.transect_name \
								FROM park p, transect t, site_survey s \
								WHERE s.site_id = t.site_id \
								AND p.park_id = s.park_id \
								AND t.transect_id = ?' , transectID);
	parkName = resultRow.fieldByName('park_name');
	transectName = resultRow.fieldByName('transect_name');
} catch (e) {
	var errorMessage = e.message;
	Ti.App.fireEvent("app:dataBaseError", {error: errorMessage});
} finally {
	resultRow.close();
	db.close();
}

var labelText = parkName + ' - ' + transectName;

var titleLabel = Titanium.UI.createLabel({
	top:10,
	text: labelText,
	textAlign:'center',
	font:{fontSize:20,fontWeight:'bold'},
});

// Associate label to title
$.plotsWin.setTitleControl(titleLabel);

/* Event Listeners */

Ti.App.addEventListener("app:refreshPlots", function(e) {
	populateTable();
	toggleAddBtn();
});

// Table row click event
$.tbl.addEventListener('click', function(e){
	//ignore row clicks in edit mode
	if ($.tbl.editing == true) {
		return;
	}

	//check if media exists -if no photo has been taken (re-visited plot)
	if(e.rowData.mediaID == null){
		//alert("No Photo Found!");
		var modal = Alloy.createController("plotsModal", {plotID:e.rowData.plotID, title:e.rowData.title, siteID:siteID}).getView();
		modal.open({
			modal : true,
			modalTransitionStyle : Ti.UI.iPhone.MODAL_TRANSITION_STYLE_COVER_VERTICAL,
			modalStyle : Ti.UI.iPhone.MODAL_PRESENTATION_PAGESHEET,
			navBarHidden : false
		});
	}else{

	//info button clicked, display modal
	if(e.source.toString() == '[object TiUIButton]') {
		var modal = Alloy.createController("plotsModal", {plotID:e.rowData.plotID, title:e.rowData.title, siteID:siteID}).getView();
		modal.open({
			modal : true,
			modalTransitionStyle : Ti.UI.iPhone.MODAL_TRANSITION_STYLE_COVER_VERTICAL,
			modalStyle : Ti.UI.iPhone.MODAL_PRESENTATION_PAGESHEET,
			navBarHidden : false
		});
	//row clicked, get transect view
	}else{
		//open plot observations
		var observations = Alloy.createController("plotObservations", {plotID:e.rowData.plotID}).getView();
		var nav = Alloy.Globals.navMenu;
		nav.openWindow(observations);
	}
  }
});

//Delete - event listener
$.tbl.addEventListener('delete', function(e) {
	//get the plot_id of the current row to be deleted
	var currentPlotID = e.rowData.plotID;
	try{
		//open database
		var db = Ti.Database.open('ltemaDB');

		//GET FOLDER NAME - Retrieve site survery, year, park
		var rows = db.execute('SELECT year, protocol_name, park_name \
							FROM site_survey s, protocol p, park prk \
							WHERE s.protocol_id = p.protocol_id \
							AND s.park_id = prk.park_id \
							AND site_id = ?', siteID);

		//Name the directory
		var year = rows.fieldByName('year');
		var protocolName = rows.fieldByName('protocol_name');
		var parkName = rows.fieldByName('park_name');

		var folder = year + ' - ' + protocolName + ' - ' + parkName;

		//delete associated media files
		var plotFiles = db.execute('SELECT media_name \
												FROM media m, plot p \
												WHERE m.media_id = p.media_id \
												AND p.plot_id = ? ', currentPlotID);

		var fileName = plotFiles.fieldByName('media_name');
		deleteImage(fileName, folder);

		var plotObservationFiles = db.execute('SELECT media_name \
												FROM media m, plot_observation po \
												WHERE m.media_id = po.media_id \
												AND po.plot_id = ? ', currentPlotID);

		while (plotObservationFiles.isValidRow()) {
			var fileName = plotObservationFiles.fieldByName('media_name');
			deleteImage(fileName, folder);
			plotObservationFiles.next();
		}

		//delete current row from the database
		db.execute('DELETE FROM plot WHERE plot_id = ?', currentPlotID);

		// Make the last row editable
		var lastRow = $.tbl.data[0].rowCount - 1;
		$.tbl.data[0].rows[lastRow].editable = true;

		// Cycle toggle on the table to show the next row can be deleted
		$.tbl.editing = false;
		$.tbl.editing = true;

	} catch(e) {
		var errorMessage = e.message;
		Ti.App.fireEvent("app:dataBaseError", {error: errorMessage});
	} finally {
		//rows.close();
		//plotFiles.close();
		//plotObservationFiles.close();
		db.close();
		toggleEditBtn();
	}
});

/* Functions */

function populateTable() {

	$.addPlot.enabled = true;

	//Clear the table if there is anything in it
	var rd = [];
	$.tbl.data = rd;
	try {
		//open database
		var db = Ti.Database.open('ltemaDB');

		//Query - Retrieve existing plots from database
		var rows = db.execute('SELECT plot_id, plot_name, media_id \
							FROM plot \
							WHERE transect_id = ?', $.tbl.transectID);

		//Get requested data from each row in table
		while (rows.isValidRow()) {
			var plotID = rows.fieldByName('plot_id');
			var plotName = rows.fieldByName('plot_name');
			var mediaID = rows.fieldByName('media_id');

			var groundCoverRows = db.execute('SELECT sum(ground_cover) \
											FROM plot_observation \
											WHERE plot_id = ?', plotID);

			var totalGroundCover = groundCoverRows.fieldByName('sum(ground_cover)');

			if (totalGroundCover == null) {
				totalGroundCover = 0;
			}

			//create a new row
				var newRow = Ti.UI.createTableViewRow({
					title : plotName,
					plotID : plotID,
					mediaID : mediaID,
					height: 60,
					font: {fontSize: 20},
					totalGroundCover: totalGroundCover,
					editable: false
				});

			//add the total ground cover label
				var groundCoverLabel = Ti.UI.createLabel({
					text: totalGroundCover + '%',
					right: 55,
					font: {fontSize: 20}
				});
				newRow.add(groundCoverLabel);

				//create and add info icon for the row
				var infoButton = Ti.UI.createButton({
					style : Titanium.UI.iPhone.SystemButton.DISCLOSURE,
					right : 15,
					height: 60,
					width: 60
				});
				newRow.add(infoButton);

				//change label colour if total ground cover is less than 100%
				if (totalGroundCover < 100) {
					 newRow.color = "red";
				}

				//Add row to the table view
				$.tbl.appendRow(newRow);

			rows.next();
		}

		// Make the last row editable
		var lastRow = $.tbl.data[0].rowCount - 1;
		$.tbl.data[0].rows[lastRow].editable = true;

	} catch(e){
		var errorMessage = e.message;
		Ti.App.fireEvent("app:dataBaseError", {error: errorMessage});
	} finally {
		rows.close();
		db.close();
		toggleEditBtn();
	}
}

//EDIT BUTTON - toggle edit mode
function editBtn(e){

	//enable or disable edit mode
	if (e.source.title == "Edit") {
		$.tbl.editing = true;
		e.source.title = "Done";
		//disable the add button during edit mode
		$.addPlot.enabled = false;

	} else {
		$.tbl.editing = false;
		e.source.title = "Edit";
		toggleAddBtn();
	}
}

//ADD BUTTON - add a new plot
function addBtn(){
	//disable add button until screen is returned to focus.  Issue #28
	$.addPlot.enabled = false;

	//Navigation to addPlot
	var addPlot = Alloy.createController("addPlot", {transectID: $.tbl.transectID}).getView();
	var nav = Alloy.Globals.navMenu;
	nav.openWindow(addPlot);
}

//ADD BUTTON TOGGLE
function toggleAddBtn(){
	var incompletePlotCount = 0;
	//check if any rows exists
	if(showTotalRowNumber() > 0){
		//loop via plot list and check total ground cover
		for(var i=0; i < $.tbl.data[0].rows.length; i++) {
	        if($.tbl.data[0].rows[i].totalGroundCover < 100){
	        	//disable add plot button
	        	incompletePlotCount += 1;
				//$.tbl.data[0].rows[i].color = "red";
	        }
	    }
	 }
	 //Check the number of incomplete Plot Count
	    if(incompletePlotCount > 0){
	    	//disable add plot button
	    	$.addPlot.enabled = false;
			$.addPlotError.visible = true;
	    }else{
	    	//enable add plot button
	        $.addPlot.enabled = true;
			$.addPlotError.visible = false;
	    }

}

//Enable or Disable the Edit button
function toggleEditBtn(){
	//get the number of total rows
	var numRows = showTotalRowNumber();
	//if no rows exist
	if(numRows <= 0){
		//disable Edit Button
		$.editPlot.enabled = false;
		$.editPlot.title = "Edit";
		$.addPlot.enabled = true;
		$.tbl.editing = false;
		$.addPlotError.visible = false;
	}else{
		//enable Edit Button
		$.editPlot.enabled = true;
	}
}

//Function to get total number of rows (plots)
function showTotalRowNumber(){
	// Variable to get all section
	var allSection = $.tbl.data;

	var sectionNumber = 0;
	var totalRows = 0;

	for(sectionNumber = 0; sectionNumber < allSection.length; sectionNumber++){
		// Get rows for each section
		totalRows += allSection[sectionNumber].rowCount;
	}
	return totalRows;
}

// Delete a file from the application data directory
function deleteImage(fileName, folderName) {
	var imageDir = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, folderName);

	if (imageDir.exists()) {
		// .resolve() provides the resolved native path for the directory.
		var imageFile = Ti.Filesystem.getFile(imageDir.resolve(), fileName);
		if (imageFile.exists()) {
			imageFile.deleteFile();
		}
	}
}<commit_msg>Improving plot screen load<commit_after>/* List screen to view, add, or delete plots */

//get transectID from calling window
var args = arguments[0];
var transectID = args.transectID;
$.tbl.transectID = transectID;
var siteID = args.siteID;

populateTable();
toggleAddBtn();

/* Nav Bar Label */

// Build title label
var parkName = "";
var transectName ="";

try {
	var db = Ti.Database.open('ltemaDB');

	resultRow = db.execute (	'SELECT p.park_name, t.transect_name \
								FROM park p, transect t, site_survey s \
								WHERE s.site_id = t.site_id \
								AND p.park_id = s.park_id \
								AND t.transect_id = ?' , transectID);
	parkName = resultRow.fieldByName('park_name');
	transectName = resultRow.fieldByName('transect_name');
} catch (e) {
	var errorMessage = e.message;
	Ti.App.fireEvent("app:dataBaseError", {error: errorMessage});
} finally {
	resultRow.close();
	db.close();
}

var labelText = parkName + ' - ' + transectName;

var titleLabel = Titanium.UI.createLabel({
	top:10,
	text: labelText,
	textAlign:'center',
	font:{fontSize:20,fontWeight:'bold'},
});

// Associate label to title
$.plotsWin.setTitleControl(titleLabel);

/* Event Listeners */

Ti.App.addEventListener("app:refreshPlots", function(e) {
	populateTable();
	toggleAddBtn();
});

// Table row click event
$.tbl.addEventListener('click', function(e){
	//ignore row clicks in edit mode
	if ($.tbl.editing == true) {
		return;
	}

	//check if media exists -if no photo has been taken (re-visited plot)
	if(e.rowData.mediaID == null){
		//alert("No Photo Found!");
		var modal = Alloy.createController("plotsModal", {plotID:e.rowData.plotID, title:e.rowData.title, siteID:siteID}).getView();
		modal.open({
			modal : true,
			modalTransitionStyle : Ti.UI.iPhone.MODAL_TRANSITION_STYLE_COVER_VERTICAL,
			modalStyle : Ti.UI.iPhone.MODAL_PRESENTATION_PAGESHEET,
			navBarHidden : false
		});
	}else{

	//info button clicked, display modal
	if(e.source.toString() == '[object TiUIButton]') {
		var modal = Alloy.createController("plotsModal", {plotID:e.rowData.plotID, title:e.rowData.title, siteID:siteID}).getView();
		modal.open({
			modal : true,
			modalTransitionStyle : Ti.UI.iPhone.MODAL_TRANSITION_STYLE_COVER_VERTICAL,
			modalStyle : Ti.UI.iPhone.MODAL_PRESENTATION_PAGESHEET,
			navBarHidden : false
		});
	//row clicked, get transect view
	}else{
		//open plot observations
		var observations = Alloy.createController("plotObservations", {plotID:e.rowData.plotID}).getView();
		var nav = Alloy.Globals.navMenu;
		nav.openWindow(observations);
	}
  }
});

//Delete - event listener
$.tbl.addEventListener('delete', function(e) {
	//get the plot_id of the current row to be deleted
	var currentPlotID = e.rowData.plotID;
	try{
		//open database
		var db = Ti.Database.open('ltemaDB');

		//GET FOLDER NAME - Retrieve site survery, year, park
		var rows = db.execute('SELECT year, protocol_name, park_name \
							FROM site_survey s, protocol p, park prk \
							WHERE s.protocol_id = p.protocol_id \
							AND s.park_id = prk.park_id \
							AND site_id = ?', siteID);

		//Name the directory
		var year = rows.fieldByName('year');
		var protocolName = rows.fieldByName('protocol_name');
		var parkName = rows.fieldByName('park_name');

		var folder = year + ' - ' + protocolName + ' - ' + parkName;

		//delete associated media files
		var plotFiles = db.execute('SELECT media_name \
												FROM media m, plot p \
												WHERE m.media_id = p.media_id \
												AND p.plot_id = ? ', currentPlotID);

		var fileName = plotFiles.fieldByName('media_name');
		deleteImage(fileName, folder);

		var plotObservationFiles = db.execute('SELECT media_name \
												FROM media m, plot_observation po \
												WHERE m.media_id = po.media_id \
												AND po.plot_id = ? ', currentPlotID);

		while (plotObservationFiles.isValidRow()) {
			var fileName = plotObservationFiles.fieldByName('media_name');
			deleteImage(fileName, folder);
			plotObservationFiles.next();
		}

		//delete current row from the database
		db.execute('DELETE FROM plot WHERE plot_id = ?', currentPlotID);

		// Make the last row editable
		var lastRow = $.tbl.data[0].rowCount - 1;
		$.tbl.data[0].rows[lastRow].editable = true;

		// Cycle toggle on the table to show the next row can be deleted
		$.tbl.editing = false;
		$.tbl.editing = true;

	} catch(e) {
		var errorMessage = e.message;
		Ti.App.fireEvent("app:dataBaseError", {error: errorMessage});
	} finally {
		//rows.close();
		//plotFiles.close();
		//plotObservationFiles.close();
		db.close();
		toggleEditBtn();
	}
});

/* Functions */

function populateTable() {

	//$.addPlot.enabled = true;

	//Clear the table if there is anything in it
	var rd = [];
	$.tbl.data = rd;
	try {
		//open database
		var db = Ti.Database.open('ltemaDB');

		//Query - Retrieve existing plots from database
		var rows = db.execute('SELECT plot_id, plot_name, media_id \
							FROM plot \
							WHERE transect_id = ?', $.tbl.transectID);

		//Get requested data from each row in table
		while (rows.isValidRow()) {
			var plotID = rows.fieldByName('plot_id');
			var plotName = rows.fieldByName('plot_name');
			var mediaID = rows.fieldByName('media_id');

			var groundCoverRows = db.execute('SELECT sum(ground_cover) \
											FROM plot_observation \
											WHERE plot_id = ?', plotID);

			var totalGroundCover = groundCoverRows.fieldByName('sum(ground_cover)');

			if (totalGroundCover == null) {
				totalGroundCover = 0;
			}

			//create a new row
				var newRow = Ti.UI.createTableViewRow({
					title : plotName,
					plotID : plotID,
					mediaID : mediaID,
					height: 60,
					font: {fontSize: 20},
					totalGroundCover: totalGroundCover,
					editable: false
				});

			//add the total ground cover label
				var groundCoverLabel = Ti.UI.createLabel({
					text: totalGroundCover + '%',
					right: 55,
					font: {fontSize: 20}
				});
				newRow.add(groundCoverLabel);

				//create and add info icon for the row
				var infoButton = Ti.UI.createButton({
					style : Titanium.UI.iPhone.SystemButton.DISCLOSURE,
					right : 15,
					height: 60,
					width: 60
				});
				newRow.add(infoButton);

				//change label colour if total ground cover is less than 100%
				if (totalGroundCover < 100) {
					 newRow.color = "red";
				}

				//Add row to the table view
				$.tbl.appendRow(newRow);

			rows.next();
		}

		// Make the last row editable
		var lastRow = $.tbl.data[0].rowCount - 1;
		$.tbl.data[0].rows[lastRow].editable = true;

	} catch(e){
		var errorMessage = e.message;
		Ti.App.fireEvent("app:dataBaseError", {error: errorMessage});
	} finally {
		rows.close();
		db.close();
		toggleEditBtn();
	}
}

//EDIT BUTTON - toggle edit mode
function editBtn(e){

	//enable or disable edit mode
	if (e.source.title == "Edit") {
		$.tbl.editing = true;
		e.source.title = "Done";
		//disable the add button during edit mode
		$.addPlot.enabled = false;

	} else {
		$.tbl.editing = false;
		e.source.title = "Edit";
		toggleAddBtn();
	}
}

//ADD BUTTON - add a new plot
function addBtn(){
	//disable add button until screen is returned to focus.  Issue #28
	$.addPlot.enabled = false;

	//Navigation to addPlot
	var addPlot = Alloy.createController("addPlot", {transectID: $.tbl.transectID}).getView();
	var nav = Alloy.Globals.navMenu;
	nav.openWindow(addPlot);
}

//ADD BUTTON TOGGLE
function toggleAddBtn(){
	var incompletePlotCount = 0;
	//check if any rows exists
	if(showTotalRowNumber() > 0){
		//loop via plot list and check total ground cover
		for(var i=0; i < $.tbl.data[0].rows.length; i++) {
	        if($.tbl.data[0].rows[i].totalGroundCover < 100){
	        	//disable add plot button
	        	incompletePlotCount += 1;
				//$.tbl.data[0].rows[i].color = "red";
	        }
	    }
	 }
	 //Check the number of incomplete Plot Count
	    if(incompletePlotCount > 0){
	    	//disable add plot button
	    	$.addPlot.enabled = false;
			$.addPlotError.visible = true;
	    }else{
	    	//enable add plot button
	        $.addPlot.enabled = true;
			$.addPlotError.visible = false;
	    }

}

//Enable or Disable the Edit button
function toggleEditBtn(){
	//get the number of total rows
	var numRows = showTotalRowNumber();
	//if no rows exist
	if(numRows <= 0){
		//disable Edit Button
		$.editPlot.enabled = false;
		$.editPlot.title = "Edit";
		$.addPlot.enabled = true;
		$.tbl.editing = false;
		$.addPlotError.visible = false;
	}else{
		//enable Edit Button
		$.editPlot.enabled = true;
	}
}

//Function to get total number of rows (plots)
function showTotalRowNumber(){
	// Variable to get all section
	var allSection = $.tbl.data;

	var sectionNumber = 0;
	var totalRows = 0;

	for(sectionNumber = 0; sectionNumber < allSection.length; sectionNumber++){
		// Get rows for each section
		totalRows += allSection[sectionNumber].rowCount;
	}
	return totalRows;
}

// Delete a file from the application data directory
function deleteImage(fileName, folderName) {
	var imageDir = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, folderName);

	if (imageDir.exists()) {
		// .resolve() provides the resolved native path for the directory.
		var imageFile = Ti.Filesystem.getFile(imageDir.resolve(), fileName);
		if (imageFile.exists()) {
			imageFile.deleteFile();
		}
	}
}<|endoftext|>


<commit_before>'use strict';

const path = require('path');
const fs = require('fs');

const findPackage = require('./src/find_package.js');

const webpack = require('webpack');
const resolve = require('resolve');
const mkdirp = require('mkdirp');

// We must place our files in a special folder for integration /w the android
// build system.
const destination = process.env.SILK_BUILDJS_DEST;
const babelCache = path.join(destination, '../.babelcache');
const modulePath = findPackage(process.env.SILK_BUILDJS_SOURCE);
const pkg = require(path.join(modulePath, 'package.json'));
const localWebpack = path.join(modulePath, 'webpack.config.js');

mkdirp.sync(babelCache);

const name = pkg.name;
let main = pkg.main || './index.js';
if (!path.extname(main)) {
  main += '.js';
}

if (main.indexOf('./') !== 0) {
  main = `./${main}`;
}

// XXX: Would be nicer to abort this in the bash script rather than after we
// have booted up node here...
if (
  main.indexOf('build/Release') === 0 ||
  main.indexOf('./build/Release') === 0 ||
  /\.node$/.test(main)
) {
  console.log(`Module contains no JS main skipping webpack ...`);
  process.exit(0);
}

if (!main) {
  throw new Error(`package.json must have main in ${process.cwd()}`);
}

const externals = [
  // TODO: auto generate these ...
  'base_version',
  'bleno',
  'mic',
  'noble',
  'node-hid',
  'node-webrtc',
  'opencv',
  'segfault-handler',
  'silk-alog',
  'silk-battery',
  'silk-camera',
  'silk-core-version',
  'silk-cv',
  'silk-gc1',
  'silk-input',
  'silk-lights',
  'silk-modwatcher',
  'silk-movie',
  'silk-netstatus',
  'silk-ntp',
  'silk-properties',
  'silk-sensors',
  'silk-sysutils',
  'silk-vibrator',
  'silk-volume',
  'silk-wifi',
  'v8-profiler',
  'kissfft',
  'silk-caffe',
  /\.node$/,
  (context, request, callback) => {
    if (resolve.isCore(request)) {
      callback(null, true);
      return;
    }

    // For extra fun node will allow resolving .main without a ./ this behavior
    // makes .main look nicer but is completely different than how requiring
    // without a specific path is handled elsewhere... To ensure we don't
    // accidentally resolve a node module to a local file we handle this case
    // very specifically.
    if (context === modulePath && pkg.main === request) {
      const resolvedPath = path.resolve(context, request);
      if (!fs.existsSync(resolvedPath)) {
        callback(new Error(`${modulePath} has a .main which is missing ...`));
        return;
      }
    }

    resolve(request,  {
      basedir: context,
      package: pkg,
      extensions: ['.js', '.json'],
    }, (err, resolvedPath) => {
      if (err) {
        console.log(`Missing module imported from ${context} (${request})`);
        callback(null, true);
        return;
      }
      callback(null, false);
    });
  }
];

const entry = {};
entry[main] = main;

const config = {
  context: modulePath,
  externals,
  target: 'node',
  node: {
    __dirname: false,
    __filename: false,
  },
  devtool: 'source-map',
  entry,
  output: {
    path: path.join(destination),
    libraryTarget: 'commonjs2',
    filename: `[name]`,
  },
  resolve: {
    extensions: ['', '.js', '.json'],
    // Common "gothcha" modules ...
    alias: {
      'any-promise': require.resolve('./shims/any-promise.js'),
      'json3': require.resolve('./shims/json3.js'),
    },
  },
  babel: {
    cacheDirectory: babelCache,
    presets: [
      require('babel-preset-silk-node4'),
    ],
  },
  module : {
    loaders: [
      { test: /\.json$/, loader: require.resolve('json-loader') },
      {
        test: /\.js$/,
        loader: require.resolve('babel-loader'),
        query: {
          babelrc: false,
        }
      }
    ]
  }
}

if (fs.existsSync(localWebpack)) {
  console.log(`${localWebpack} found agumenting buildjs ...`);
  const rules = Object.assign({}, require(localWebpack));
  if (rules.externals && Array.isArray(rules.externals)) {
    // Order is important here the rules should be ordered such that the
    // webpack.config comes from the module first and our global rules second.
    config.externals = rules.externals.concat(config.externals);
    delete rules.externals;
  }
  Object.assign(config, rules);
}

module.exports = config;
<commit_msg>Update webpack.config<commit_after>'use strict';

const path = require('path');
const fs = require('fs');

const findPackage = require('./src/find_package.js');

const webpack = require('webpack');
const resolve = require('resolve');
const mkdirp = require('mkdirp');

// We must place our files in a special folder for integration /w the android
// build system.
const destination = process.env.SILK_BUILDJS_DEST;
const babelCache = path.join(destination, '../.babelcache');
const modulePath = findPackage(process.env.SILK_BUILDJS_SOURCE);
const pkg = require(path.join(modulePath, 'package.json'));
const localWebpack = path.join(modulePath, 'webpack.config.js');

mkdirp.sync(babelCache);

const name = pkg.name;
let main = pkg.main || './index.js';
if (!path.extname(main)) {
  main += '.js';
}

if (main.indexOf('./') !== 0) {
  main = `./${main}`;
}

// XXX: Would be nicer to abort this in the bash script rather than after we
// have booted up node here...
if (
  main.indexOf('build/Release') === 0 ||
  main.indexOf('./build/Release') === 0 ||
  /\.node$/.test(main)
) {
  console.log(`Module contains no JS main skipping webpack ...`);
  process.exit(0);
}

if (!main) {
  throw new Error(`package.json must have main in ${process.cwd()}`);
}

const externals = [
  // TODO: auto generate these ...
  'base_version',
  'bleno',
  'mic',
  'noble',
  'node-hid',
  'node-webrtc',
  'opencv',
  'segfault-handler',
  'silk-alog',
  'silk-battery',
  'silk-camera',
  'silk-core-version',
  'silk-cv',
  'silk-gc1',
  'silk-input',
  'silk-lights',
  'silk-modwatcher',
  'silk-movie',
  'silk-netstatus',
  'silk-ntp',
  'silk-properties',
  'silk-sensors',
  'silk-sysutils',
  'silk-vad',
  'silk-vibrator',
  'silk-volume',
  'silk-wifi',
  'v8-profiler',
  'kissfft',
  'silk-caffe',
  /\.node$/,
  (context, request, callback) => {
    if (resolve.isCore(request)) {
      callback(null, true);
      return;
    }

    // For extra fun node will allow resolving .main without a ./ this behavior
    // makes .main look nicer but is completely different than how requiring
    // without a specific path is handled elsewhere... To ensure we don't
    // accidentally resolve a node module to a local file we handle this case
    // very specifically.
    if (context === modulePath && pkg.main === request) {
      const resolvedPath = path.resolve(context, request);
      if (!fs.existsSync(resolvedPath)) {
        callback(new Error(`${modulePath} has a .main which is missing ...`));
        return;
      }
    }

    resolve(request,  {
      basedir: context,
      package: pkg,
      extensions: ['.js', '.json'],
    }, (err, resolvedPath) => {
      if (err) {
        console.log(`Missing module imported from ${context} (${request})`);
        callback(null, true);
        return;
      }
      callback(null, false);
    });
  }
];

const entry = {};
entry[main] = main;

const config = {
  context: modulePath,
  externals,
  target: 'node',
  node: {
    __dirname: false,
    __filename: false,
  },
  devtool: 'source-map',
  entry,
  output: {
    path: path.join(destination),
    libraryTarget: 'commonjs2',
    filename: `[name]`,
  },
  resolve: {
    extensions: ['', '.js', '.json'],
    // Common "gothcha" modules ...
    alias: {
      'any-promise': require.resolve('./shims/any-promise.js'),
      'json3': require.resolve('./shims/json3.js'),
    },
  },
  babel: {
    cacheDirectory: babelCache,
    presets: [
      require('babel-preset-silk-node4'),
    ],
  },
  module : {
    loaders: [
      { test: /\.json$/, loader: require.resolve('json-loader') },
      {
        test: /\.js$/,
        loader: require.resolve('babel-loader'),
        query: {
          babelrc: false,
        }
      }
    ]
  }
}

if (fs.existsSync(localWebpack)) {
  console.log(`${localWebpack} found agumenting buildjs ...`);
  const rules = Object.assign({}, require(localWebpack));
  if (rules.externals && Array.isArray(rules.externals)) {
    // Order is important here the rules should be ordered such that the
    // webpack.config comes from the module first and our global rules second.
    config.externals = rules.externals.concat(config.externals);
    delete rules.externals;
  }
  Object.assign(config, rules);
}

module.exports = config;
<|endoftext|>


<commit_before>import { get } from "ember";
import {
	ARG_TRAY,
	ARG_MIN,
	ARG_MAX,
	ARG_RESET_WINDOW,
	ARG_LAUNCH,
	ARG_GOTO
} from "nwjs/argv";
import {
	setMaximized,
	setMinimized,
	setVisibility
} from "nwjs/Window";
import resetWindow from "nwjs/Window/reset";
import {
	setShowInTray,
	hideOnClick
} from "nwjs/Tray";
import onChangeIntegrations from "./integrations";

export default async function( argv, settings, application ) {
	// reset window
	if ( argv[ ARG_RESET_WINDOW ] ) {
		await resetWindow( true );
	}

	// maximize window
	if ( argv[ ARG_MAX ] ) {
		setMaximized( true );
	}

	// minimize window
	if ( argv[ ARG_MIN ] ) {
		setMinimized( true );
	}

	if ( argv[ ARG_TRAY ] ) {
		const isVisibleInTaskbar = get( settings, "gui.isVisibleInTaskbar" );
		const isVisibleInTray = get( settings, "gui.isVisibleInTray" );
		// show tray icon (and taskbar item)
		setShowInTray( true, isVisibleInTaskbar );
		// remove the tray icon after clicking it if it's disabled in the settings
		if ( !isVisibleInTray ) {
			hideOnClick();
		}
	} else {
		// show tray and taskbar item depending on settings
		onChangeIntegrations( settings );

		// show application window
		setVisibility( true );
	}

	// go to a new route (or refresh current one)
	if ( argv[ ARG_GOTO ] ) {
		const routingService = application.lookup( "service:-routing" );
		await routingService.transitionTo( argv[ ARG_GOTO ] );
	}

	// launch a stream by user name
	if ( argv[ ARG_LAUNCH ] ) {
		const store = application.lookup( "service:store" );
		const streamingService = application.lookup( "service:streaming" );
		const user = await store.findRecord( "twitchUser", argv[ ARG_LAUNCH ] );
		const twitchStream = await get( user, "stream" );
		streamingService.startStream( twitchStream );
	}
}
<commit_msg>Fix --min launch parameter<commit_after>import { get } from "ember";
import {
	ARG_TRAY,
	ARG_MIN,
	ARG_MAX,
	ARG_RESET_WINDOW,
	ARG_LAUNCH,
	ARG_GOTO
} from "nwjs/argv";
import {
	setMaximized,
	setMinimized,
	setVisibility
} from "nwjs/Window";
import resetWindow from "nwjs/Window/reset";
import {
	setShowInTray,
	hideOnClick
} from "nwjs/Tray";
import onChangeIntegrations from "./integrations";

export default async function( argv, settings, application ) {
	// reset window
	if ( argv[ ARG_RESET_WINDOW ] ) {
		await resetWindow( true );
	}

	// maximize window
	if ( argv[ ARG_MAX ] ) {
		setMaximized( true );
	}

	if ( argv[ ARG_TRAY ] ) {
		const isVisibleInTaskbar = get( settings, "gui.isVisibleInTaskbar" );
		const isVisibleInTray = get( settings, "gui.isVisibleInTray" );
		// show tray icon (and taskbar item)
		setShowInTray( true, isVisibleInTaskbar );
		// remove the tray icon after clicking it if it's disabled in the settings
		if ( !isVisibleInTray ) {
			hideOnClick();
		}
	} else {
		// show tray and taskbar item depending on settings
		onChangeIntegrations( settings );

		// show application window
		setVisibility( true );
	}

	// minimize window (after the visibility has changed)
	if ( argv[ ARG_MIN ] ) {
		setMinimized( true );
	}

	// go to a new route (or refresh current one)
	if ( argv[ ARG_GOTO ] ) {
		const routingService = application.lookup( "service:-routing" );
		await routingService.transitionTo( argv[ ARG_GOTO ] );
	}

	// launch a stream by user name
	if ( argv[ ARG_LAUNCH ] ) {
		const store = application.lookup( "service:store" );
		const streamingService = application.lookup( "service:streaming" );
		const user = await store.findRecord( "twitchUser", argv[ ARG_LAUNCH ] );
		const twitchStream = await get( user, "stream" );
		streamingService.startStream( twitchStream );
	}
}
<|endoftext|>


<commit_before>'use strict';

const path = require('path');
const fs = require('fs');

const findPackage = require('./src/find_package.js');

const webpack = require('webpack');
const resolve = require('resolve');
const mkdirp = require('mkdirp');

// We must place our files in a special folder for integration /w the android
// build system.
const destination = process.env.SILK_BUILDJS_DEST;
const modulePath = findPackage(process.env.SILK_BUILDJS_SOURCE);
const pkg = require(path.join(modulePath, 'package.json'));
const localWebpack = path.join(modulePath, 'webpack.config.js');

let babelCache;
if (!process.env.BABEL_CACHE || process.env.BABEL_CACHE === '1') {
  babelCache = path.join(destination, '../.babelcache');
  mkdirp.sync(babelCache);
} else {
  console.log('~ babel cache has been disabled ~');
  babelCache = false;
}

const name = pkg.name;
let main = pkg.main || './index.js';
if (!path.extname(main)) {
  main += '.js';
}

if (main.indexOf('./') !== 0) {
  main = `./${main}`;
}

const absMain = path.resolve(modulePath, main);
let mainDir;

try {
  mainDir = fs.realpathSync(path.dirname(absMain));
} catch (err) {
  mainDir = path.dirname(absMain);
}

// XXX: Would be nicer to abort this in the bash script rather than after we
// have booted up node here...
if (
  main.indexOf('build/Release') === 0 ||
  main.indexOf('./build/Release') === 0 ||
  /\.node$/.test(main)
) {
  console.log(`Module contains no JS main skipping webpack ...`);
  process.exit(0);
}

if (!main) {
  throw new Error(`package.json must have main in ${process.cwd()}`);
}

const externals = [
  // TODO: auto generate these ...
  'bleno',
  'kissfft',
  'lame',
  'mic',
  'nn.js',
  'noble',
  'node-hid',
  'node-nnpack',
  'node-opencl',
  'node-qsml',
  'node-shm',
  'node-wav',
  'node-webrtc',
  'opencv',
  'segfault-handler',
  'silk-alog',
  'silk-audioplayer',
  'silk-battery',
  'silk-bledroid',
  'silk-bsp-version',
  'silk-camera',
  'silk-core-version',
  'silk-crashreporter',
  'silk-cv',
  'silk-device-api',
  'silk-device-ui',
  'silk-dialog-engine',
  'silk-dialog-script',
  'silk-dialog-storage',
  'silk-factory-reset',
  'silk-gc1',
  'silk-input',
  'silk-audio-dnn',
  'silk-lifx',
  'silk-lights',
  'silk-modwatcher',
  'silk-movie',
  'silk-netstatus',
  'silk-ntp',
  'silk-outbox',
  'silk-process',
  'silk-properties',
  'silk-say',
  'silk-sensors',
  'silk-sonos',
  'silk-speaker',
  'silk-streams',
  'silk-stt',
  'silk-sysutils',
  'silk-tts',
  'silk-update',
  'silk-vad',
  'silk-vibrator',
  'silk-volume',
  'silk-watchdog',
  'silk-wifi',
  'sodium',
  'v8-profiler',
  (context, request, callback) => {
    if (resolve.isCore(request)) {
      callback(null, true);
      return;
    }

    // For extra fun node will allow resolving .main without a ./ this behavior
    // makes .main look nicer but is completely different than how requiring
    // without a specific path is handled elsewhere... To ensure we don't
    // accidentally resolve a node module to a local file we handle this case
    // very specifically.
    if (context === modulePath && pkg.main === request) {
      const resolvedPath = path.resolve(context, request);
      if (!fs.existsSync(resolvedPath)) {
        callback(new Error(`${modulePath} has a .main which is missing ...`));
        return;
      }
    }

    // Handle path rewriting for native modules
    if (
      /\.node$/.test(request) ||
      request.indexOf('build/Release') !== -1
    ) {
      if (path.isAbsolute(request)) {
        callback(null, true);
        return;
      }

      const absExternalPath = path.resolve(context, request);
      let relativeExternalPath = path.relative(mainDir, absExternalPath);
      if (relativeExternalPath.indexOf('.') !== 0) {
        relativeExternalPath = `./${relativeExternalPath}`;
      }
      callback(null, relativeExternalPath);
      return;
    }

    resolve(request,  {
      basedir: context,
      package: pkg,
      extensions: ['.js', '.json'],
    }, (err, resolvedPath) => {
      if (err) {
        console.log(`Missing module imported from ${context} (${request})`);
        callback(null, true);
        return;
      }
      callback(null, false);
    });
  }
];

const entry = {};
entry[main] = main;

const config = {
  context: modulePath,
  externals,
  target: 'node',
  node: {
    __dirname: false,
    __filename: false,
  },
  devtool: 'source-map',
  entry,
  output: {
    path: path.join(destination),
    libraryTarget: 'commonjs2',
    filename: `[name]`,
  },
  resolve: {
    extensions: ['', '.js', '.json'],
    // Common "gothcha" modules ...
    alias: {
      'any-promise': require.resolve('./shims/any-promise.js'),
      'json3': require.resolve('./shims/json3.js'),
    },
  },
  babel: {
    cacheDirectory: babelCache,
    presets: [
      require('babel-preset-silk-node6'),
    ],
  },
  module : {
    loaders: [
      { test: /\.json$/, loader: require.resolve('json-loader') },
      {
        test: /\.js$/,
        loader: require.resolve('babel-loader'),
        query: {
          babelrc: false,
        }
      }
    ]
  }
}

if (fs.existsSync(localWebpack)) {
  console.log(`${localWebpack} found agumenting buildjs ...`);
  const rules = Object.assign({}, require(localWebpack));
  if (rules.externals && Array.isArray(rules.externals)) {
    // Order is important here the rules should be ordered such that the
    // webpack.config comes from the module first and our global rules second.
    config.externals = rules.externals.concat(config.externals);
    delete rules.externals;
  }
  Object.assign(config, rules);
}

module.exports = config;
<commit_msg>Allow specifying a loader in local webpack config<commit_after>'use strict';

const path = require('path');
const fs = require('fs');

const findPackage = require('./src/find_package.js');

const webpack = require('webpack');
const resolve = require('resolve');
const mkdirp = require('mkdirp');

// We must place our files in a special folder for integration /w the android
// build system.
const destination = process.env.SILK_BUILDJS_DEST;
const modulePath = findPackage(process.env.SILK_BUILDJS_SOURCE);
const pkg = require(path.join(modulePath, 'package.json'));
const localWebpack = path.join(modulePath, 'webpack.config.js');

let babelCache;
if (!process.env.BABEL_CACHE || process.env.BABEL_CACHE === '1') {
  babelCache = path.join(destination, '../.babelcache');
  mkdirp.sync(babelCache);
} else {
  console.log('~ babel cache has been disabled ~');
  babelCache = false;
}

const name = pkg.name;
let main = pkg.main || './index.js';
if (!path.extname(main)) {
  main += '.js';
}

if (main.indexOf('./') !== 0) {
  main = `./${main}`;
}

const absMain = path.resolve(modulePath, main);
let mainDir;

try {
  mainDir = fs.realpathSync(path.dirname(absMain));
} catch (err) {
  mainDir = path.dirname(absMain);
}

// XXX: Would be nicer to abort this in the bash script rather than after we
// have booted up node here...
if (
  main.indexOf('build/Release') === 0 ||
  main.indexOf('./build/Release') === 0 ||
  /\.node$/.test(main)
) {
  console.log(`Module contains no JS main skipping webpack ...`);
  process.exit(0);
}

if (!main) {
  throw new Error(`package.json must have main in ${process.cwd()}`);
}

const externals = [
  // TODO: auto generate these ...
  'bleno',
  'kissfft',
  'lame',
  'mic',
  'nn.js',
  'noble',
  'node-hid',
  'node-nnpack',
  'node-opencl',
  'node-qsml',
  'node-shm',
  'node-wav',
  'node-webrtc',
  'opencv',
  'segfault-handler',
  'silk-alog',
  'silk-audioplayer',
  'silk-battery',
  'silk-bledroid',
  'silk-bsp-version',
  'silk-camera',
  'silk-core-version',
  'silk-crashreporter',
  'silk-cv',
  'silk-device-api',
  'silk-device-ui',
  'silk-dialog-engine',
  'silk-dialog-script',
  'silk-dialog-storage',
  'silk-factory-reset',
  'silk-gc1',
  'silk-input',
  'silk-audio-dnn',
  'silk-lifx',
  'silk-lights',
  'silk-modwatcher',
  'silk-movie',
  'silk-netstatus',
  'silk-ntp',
  'silk-outbox',
  'silk-process',
  'silk-properties',
  'silk-say',
  'silk-sensors',
  'silk-sonos',
  'silk-speaker',
  'silk-streams',
  'silk-stt',
  'silk-sysutils',
  'silk-tts',
  'silk-update',
  'silk-vad',
  'silk-vibrator',
  'silk-volume',
  'silk-watchdog',
  'silk-wifi',
  'sodium',
  'v8-profiler',
  (context, request, callback) => {
    if (resolve.isCore(request)) {
      callback(null, true);
      return;
    }

    // For extra fun node will allow resolving .main without a ./ this behavior
    // makes .main look nicer but is completely different than how requiring
    // without a specific path is handled elsewhere... To ensure we don't
    // accidentally resolve a node module to a local file we handle this case
    // very specifically.
    if (context === modulePath && pkg.main === request) {
      const resolvedPath = path.resolve(context, request);
      if (!fs.existsSync(resolvedPath)) {
        callback(new Error(`${modulePath} has a .main which is missing ...`));
        return;
      }
    }

    // Handle path rewriting for native modules
    if (
      /\.node$/.test(request) ||
      request.indexOf('build/Release') !== -1
    ) {
      if (path.isAbsolute(request)) {
        callback(null, true);
        return;
      }

      const absExternalPath = path.resolve(context, request);
      let relativeExternalPath = path.relative(mainDir, absExternalPath);
      if (relativeExternalPath.indexOf('.') !== 0) {
        relativeExternalPath = `./${relativeExternalPath}`;
      }
      callback(null, relativeExternalPath);
      return;
    }

    resolve(request,  {
      basedir: context,
      package: pkg,
      extensions: ['.js', '.json'],
    }, (err, resolvedPath) => {
      if (err) {
        console.log(`Missing module imported from ${context} (${request})`);
        callback(null, true);
        return;
      }
      callback(null, false);
    });
  }
];

const entry = {};
entry[main] = main;

const config = {
  context: modulePath,
  externals,
  target: 'node',
  node: {
    __dirname: false,
    __filename: false,
  },
  devtool: 'source-map',
  entry,
  output: {
    path: path.join(destination),
    libraryTarget: 'commonjs2',
    filename: `[name]`,
  },
  resolve: {
    extensions: ['', '.js', '.json'],
    // Common "gothcha" modules ...
    alias: {
      'any-promise': require.resolve('./shims/any-promise.js'),
      'json3': require.resolve('./shims/json3.js'),
    },
  },
  babel: {
    cacheDirectory: babelCache,
    presets: [
      require('babel-preset-silk-node6'),
    ],
  },
  module : {
    loaders: [
      { test: /\.json$/, loader: require.resolve('json-loader') },
      {
        test: /\.js$/,
        loader: require.resolve('babel-loader'),
        query: {
          babelrc: false,
        }
      }
    ]
  }
}

if (fs.existsSync(localWebpack)) {
  console.log(`${localWebpack} found agumenting buildjs ...`);
  const rules = Object.assign({}, require(localWebpack));
  if (rules.externals && Array.isArray(rules.externals)) {
    // Order is important here the rules should be ordered such that the
    // webpack.config comes from the module first and our global rules second.
    config.externals = rules.externals.concat(config.externals);
    delete rules.externals;
  }
  if (rules.loaders && Array.isArray(rules.loaders)) {
    config.module.loaders = rules.loaders.concat(config.module.loaders);
    delete rules.loaders;
  }
  Object.assign(config, rules);
}

module.exports = config;
<|endoftext|>


<commit_before>/**
 * @author v.lugovsky
 * created on 16.12.2015
 */
(function () {
  'use strict';

  angular.module('BlurAdmin.pages.profile', [])
      .config(routeConfig);

  /** @ngInject */
  function routeConfig($stateProvider) {
    $stateProvider
        .state('profile', {
          url: '/profile',
          templateUrl: 'app/pages/profile/profile.html',
          controller: 'ProfilePageCtrl',
        });
  }

})();
<commit_msg>fix(profilePage): fix title<commit_after>/**
 * @author v.lugovsky
 * created on 16.12.2015
 */
(function () {
  'use strict';

  angular.module('BlurAdmin.pages.profile', [])
      .config(routeConfig);

  /** @ngInject */
  function routeConfig($stateProvider) {
    $stateProvider
        .state('profile', {
          url: '/profile',
          title: 'Profile',
          templateUrl: 'app/pages/profile/profile.html',
          controller: 'ProfilePageCtrl',
        });
  }

})();
<|endoftext|>


<commit_before>/* global cozy, __ALLOW_HTTP__ */

import { initClient, startReplication as startPouchReplication } from '../lib/cozy-helper'
import { setClient, setFirstReplication } from '../../../src/actions/settings'
import { openFolder } from '../../../src/actions'
import { onRegistered } from '../lib/registration'
import { logException, logInfo } from '../lib/reporter'
import { pingOnceADay } from './timestamp'
import { startBackgroundService, stopBackgroundService } from '../lib/background'
import { revokeClient as reduxRevokeClient } from './authorization'

export const SET_URL = 'SET_URL'
export const BACKUP_IMAGES = 'BACKUP_IMAGES'
export const WIFI_ONLY = 'WIFI_ONLY'
export const ERROR = 'ERROR'
export const SET_ANALYTICS = 'SET_ANALYTICS'

// url

export const setUrl = url => ({ type: SET_URL, url })
export const checkURL = url => dispatch => {
  let scheme = 'https://'
  if (__ALLOW_HTTP__) {
    if (!url.startsWith(scheme)) scheme = 'http://'
    console.warn('development mode: we don\'t check SSL requirement')
  }
  if (/(.*):\/\/(.*)/.test(url) && !url.startsWith(scheme)) {
    dispatch(wrongAddressError())
    if (__ALLOW_HTTP__) {
      throw new OnBoardingError(`The supported protocols are http:// or https:// (development mode)`)
    }
    throw new OnBoardingError(`The only supported protocol is ${scheme}`)
  }
  if (!url.startsWith(scheme)) {
    url = `${scheme}${url}`
  }
  return dispatch(setUrl(url))
}

// settings

export const setAnalytics = (analytics, source = 'settings') => (dispatch, getState) => {
  dispatch({ type: SET_ANALYTICS, analytics })
  const state = getState()
  if (analytics && state.mobile) {
    const value = state.mobile.settings.backupImages
    logInfo(`${source}: backup images is ${value ? 'enabled' : 'disabled'}`)
    dispatch(pingOnceADay(state.mobile.timestamp, analytics))
  }
}

export const setBackupImages = backupImages => (dispatch, getState) => {
  const state = getState()
  if (state.mobile && state.mobile.settings.analytics) {
    backupImages ? logInfo('settings: backup images is enabled') : logInfo('settings: backup images is disabled')
  }
  backupImages ? startBackgroundService() : stopBackgroundService()
  return dispatch({ type: BACKUP_IMAGES, backupImages })
}
export const setWifiOnly = wifiOnly => ({ type: WIFI_ONLY, wifiOnly })

// errors

export const wrongAddressErrorMsg = 'mobile.onboarding.server_selection.wrong_address'
export const wrongAddressError = () => ({ type: ERROR, error: wrongAddressErrorMsg })
export class OnBoardingError extends Error {
  constructor (message) {
    super(message)
    this.name = 'OnBoardingError'
  }
}

// registration

export const registerDevice = () => async (dispatch, getState) => {
  const device = window.cordova ? window.cordova.platformId : null
  const onRegister = (dispatch) => (client, url) => {
    return onRegistered(client, url)
    .then(url => url)
    .catch(err => {
      dispatch(wrongAddressError())
      logException(err)
      throw err
    })
  }
  dispatch(checkURL(getState().mobile.settings.serverUrl))
  initClient(getState().mobile.settings.serverUrl, onRegister(dispatch), device)
  await cozy.client.authorize().then(({ client }) => {
    dispatch(setClient(client))
    startReplication(dispatch, getState)
  }).catch(err => {
    dispatch(wrongAddressError())
    logException(err)
    throw err
  })
}

export const startReplication = (dispatch, getState) => {
  const firstReplication = getState().settings.firstReplication
  const refreshFolder = () => { dispatch(openFolder(getState().folder.id)) }
  const revokeClient = () => { dispatch(reduxRevokeClient()) }
  const firstReplicationFinished = () => { dispatch(setFirstReplication(true)) }

  startPouchReplication(firstReplication, firstReplicationFinished, refreshFolder, revokeClient)
}
<commit_msg>fix: import :bug:<commit_after>/* global cozy, __ALLOW_HTTP__ */

import { initClient } from '../lib/cozy-helper'
import { startReplication as startPouchReplication } from '../lib/replication'
import { setClient, setFirstReplication } from '../../../src/actions/settings'
import { openFolder } from '../../../src/actions'
import { onRegistered } from '../lib/registration'
import { logException, logInfo } from '../lib/reporter'
import { pingOnceADay } from './timestamp'
import { startBackgroundService, stopBackgroundService } from '../lib/background'
import { revokeClient as reduxRevokeClient } from './authorization'

export const SET_URL = 'SET_URL'
export const BACKUP_IMAGES = 'BACKUP_IMAGES'
export const WIFI_ONLY = 'WIFI_ONLY'
export const ERROR = 'ERROR'
export const SET_ANALYTICS = 'SET_ANALYTICS'

// url

export const setUrl = url => ({ type: SET_URL, url })
export const checkURL = url => dispatch => {
  let scheme = 'https://'
  if (__ALLOW_HTTP__) {
    if (!url.startsWith(scheme)) scheme = 'http://'
    console.warn('development mode: we don\'t check SSL requirement')
  }
  if (/(.*):\/\/(.*)/.test(url) && !url.startsWith(scheme)) {
    dispatch(wrongAddressError())
    if (__ALLOW_HTTP__) {
      throw new OnBoardingError(`The supported protocols are http:// or https:// (development mode)`)
    }
    throw new OnBoardingError(`The only supported protocol is ${scheme}`)
  }
  if (!url.startsWith(scheme)) {
    url = `${scheme}${url}`
  }
  return dispatch(setUrl(url))
}

// settings

export const setAnalytics = (analytics, source = 'settings') => (dispatch, getState) => {
  dispatch({ type: SET_ANALYTICS, analytics })
  const state = getState()
  if (analytics && state.mobile) {
    const value = state.mobile.settings.backupImages
    logInfo(`${source}: backup images is ${value ? 'enabled' : 'disabled'}`)
    dispatch(pingOnceADay(state.mobile.timestamp, analytics))
  }
}

export const setBackupImages = backupImages => (dispatch, getState) => {
  const state = getState()
  if (state.mobile && state.mobile.settings.analytics) {
    backupImages ? logInfo('settings: backup images is enabled') : logInfo('settings: backup images is disabled')
  }
  backupImages ? startBackgroundService() : stopBackgroundService()
  return dispatch({ type: BACKUP_IMAGES, backupImages })
}
export const setWifiOnly = wifiOnly => ({ type: WIFI_ONLY, wifiOnly })

// errors

export const wrongAddressErrorMsg = 'mobile.onboarding.server_selection.wrong_address'
export const wrongAddressError = () => ({ type: ERROR, error: wrongAddressErrorMsg })
export class OnBoardingError extends Error {
  constructor (message) {
    super(message)
    this.name = 'OnBoardingError'
  }
}

// registration

export const registerDevice = () => async (dispatch, getState) => {
  const device = window.cordova ? window.cordova.platformId : null
  const onRegister = (dispatch) => (client, url) => {
    return onRegistered(client, url)
    .then(url => url)
    .catch(err => {
      dispatch(wrongAddressError())
      logException(err)
      throw err
    })
  }
  dispatch(checkURL(getState().mobile.settings.serverUrl))
  initClient(getState().mobile.settings.serverUrl, onRegister(dispatch), device)
  await cozy.client.authorize().then(({ client }) => {
    dispatch(setClient(client))
    startReplication(dispatch, getState)
  }).catch(err => {
    dispatch(wrongAddressError())
    logException(err)
    throw err
  })
}

export const startReplication = (dispatch, getState) => {
  const firstReplication = getState().settings.firstReplication
  const refreshFolder = () => { dispatch(openFolder(getState().folder.id)) }
  const revokeClient = () => { dispatch(reduxRevokeClient()) }
  const firstReplicationFinished = () => { dispatch(setFirstReplication(true)) }

  startPouchReplication(firstReplication, firstReplicationFinished, refreshFolder, revokeClient)
}
<|endoftext|>


<commit_before>var CONFIG = A.config,
	DOC = CONFIG.doc,
	WIN = CONFIG.win,
	UA = A.UA,
	IE = UA.ie,

	isShivDisabled = function() {
		return WIN.AUI_HTML5_IE === false;
	};

if (!IE || IE >= 9 || isShivDisabled()) {
	return;
}

var BUFFER_CSS_TEXT = [],

	CSS_PRINTFIX = 'aui-printfix',
	CSS_PRINTFIX_PREFIX = 'aui-printfix-',

	LOCATION = WIN.location,

	DOMAIN = LOCATION.protocol + '//' + LOCATION.host,

	GLOBAL_AUI = YUI.AUI,

	HTML = DOC.documentElement,

	HTML5_ELEMENTS = GLOBAL_AUI.HTML5_ELEMENTS,
	HTML5_ELEMENTS_LENGTH = HTML5_ELEMENTS.length,
	HTML5_ELEMENTS_LIST = HTML5_ELEMENTS.join('|'),

	REGEX_CLONE_NODE_CLEANUP = new RegExp('<(/?):(' + HTML5_ELEMENTS_LIST + ')', 'gi'),
	REGEX_ELEMENTS = new RegExp('(' + HTML5_ELEMENTS_LIST + ')', 'gi'),
	REGEX_ELEMENTS_FAST = new RegExp('\\b(' + HTML5_ELEMENTS_LIST + ')\\b', 'i'),

	REGEX_PRINT_MEDIA = /print|all/,

	REGEX_RULE = new RegExp('(^|[^\\n{}]*?\\s)(' + HTML5_ELEMENTS_LIST + ').*?{([^}]*)}', 'gim'),
	REGEX_TAG = new RegExp('<(\/*)(' + HTML5_ELEMENTS_LIST + ')', 'gi'),

	SELECTOR_REPLACE_RULE = '.' + CSS_PRINTFIX_PREFIX + '$1',

	STR_ALL = 'all',
	STR_BLANK = ' ',
	STR_EMPTY = '',

	STR_BRACKET_OPEN = '{',
	STR_BRACKET_CLOSE = '}',

	STR_CHECKBOX = 'checkbox',
	STR_CHECKED = 'checked',
	STR_HTTPS = 'https',
	STR_INPUT = 'INPUT',
	STR_OPTION = 'OPTION',
	STR_RADIO = 'radio',
	STR_SELECTED = 'selected',
	STR_STAR = '*',
	STR_URL = 'url(',
	STR_URL_DOMAIN = STR_URL + DOMAIN,

	TAG_REPLACE_ORIGINAL = '<$1$2',
	TAG_REPLACE_FONT = '<$1font';

var html5shiv = GLOBAL_AUI.html5shiv,
	// Yes, IE does this wackiness; converting an object
	// to a string should never result in undefined, but
	// IE's styleSheet object sometimes becomes inaccessible
	// after trying to print the second time
	isStylesheetDefined = function(obj) {
		return obj && (obj + STR_EMPTY !== undefined);
	},

	toggleNode = function(node, origNode, prop) {
		var state = origNode[prop];

		if (state) {
			node.setAttribute(prop, state);
		}
		else {
			node.removeAttribute(prop);
		}
	};

	html5shiv(DOC);

var PrintFix = function() {
	var afterPrint = function() {
		if (isShivDisabled()) {
			destroy();
		}
		else {
			PrintFix.onAfterPrint();
		}
	};

	var beforePrint = function() {
		if (isShivDisabled()) {
			destroy();
		}
		else {
			PrintFix.onBeforePrint();
		}
	};

	var destroy = function() {
		WIN.detachEvent('onafterprint', afterPrint);
		WIN.detachEvent('onbeforeprint', beforePrint);
	};

	var init = function() {
		WIN.attachEvent('onafterprint', afterPrint);
		WIN.attachEvent('onbeforeprint', beforePrint);
	};

	init();

	PrintFix.destroy = destroy;
	PrintFix.init = init;
};

A.mix(
	PrintFix,
	{
		onAfterPrint: function() {
			var instance = this;

			instance.restoreHTML();

			var styleSheet = instance._getStyleSheet();

			styleSheet.styleSheet.cssText = STR_EMPTY;
		},

		onBeforePrint: function() {
			var instance = this;

			var styleSheet = instance._getStyleSheet();
			var cssRules = instance._getAllCSSText();

			styleSheet.styleSheet.cssText = instance.parseCSS(cssRules);

			instance.writeHTML();
		},

		parseCSS: function(cssText) {
			var instance = this;

			var css = STR_EMPTY;
			var rules = cssText.match(REGEX_RULE);

			if (rules) {
				css = rules.join('\n').replace(REGEX_ELEMENTS, SELECTOR_REPLACE_RULE);
			}

			return css;
		},

		restoreHTML: function() {
			var instance = this;

			var bodyClone = instance._getBodyClone();
			var bodyEl = instance._getBodyEl();

			bodyClone.innerHTML = STR_EMPTY;

			HTML.removeChild(bodyClone);
			HTML.appendChild(bodyEl);
		},

		writeHTML: function() {
			var instance = this;

			var i = -1;
			var j;

			var bodyEl = instance._getBodyEl();

			var html5Element;

			var cssClass;

			var nodeList;
			var nodeListLength;
			var node;
			var buffer = [];

			while (++i < HTML5_ELEMENTS_LENGTH) {
				html5Element = HTML5_ELEMENTS[i];

				nodeList = DOC.getElementsByTagName(html5Element);
				nodeListLength = nodeList.length;

				j = -1;

				while (++j < nodeListLength) {
					node = nodeList[j];

					cssClass = node.className;

					if (cssClass.indexOf(CSS_PRINTFIX_PREFIX) == -1) {
						buffer[0] = CSS_PRINTFIX_PREFIX + html5Element;
						buffer[1] = cssClass;

						node.className = buffer.join(STR_BLANK);
					}
				}
			}

			var docFrag = instance._getDocFrag();
			var bodyClone = instance._getBodyClone();

			docFrag.appendChild(bodyEl);
			HTML.appendChild(bodyClone);

			bodyClone.className = bodyEl.className;
			bodyClone.id = bodyEl.id;

			var originalNodes = bodyEl.getElementsByTagName(STR_STAR);
			var length = originalNodes.length;

			// IE will throw a mixed content warning when using https
			// and calling clone node if the body contains elements with
			// an inline background-image style that is relative to the domain.
			if (UA.secure) {
				var bodyElStyle = bodyEl.style;

				var elStyle;
				var backgroundImage;

				bodyElStyle.display = 'none';

				for (i = 0; i < length; i++) {
					elStyle = originalNodes[i].style;

					backgroundImage = elStyle.backgroundImage;

					if (backgroundImage &&
						backgroundImage.indexOf(STR_URL) > -1 &&
						backgroundImage.indexOf(STR_HTTPS) == -1) {

						elStyle.backgroundImage = backgroundImage.replace(STR_URL, STR_URL_DOMAIN);
					}
				}

				bodyElStyle.display = STR_EMPTY;
			}

			var bodyElClone = bodyEl.cloneNode(true);

			var newNodes = bodyElClone.getElementsByTagName(STR_STAR);

			if (length == newNodes.length) {
				while (length--) {
					var newNode = newNodes[length];
					var newNodeName = newNode.nodeName;

					if (newNodeName == STR_INPUT || newNodeName == STR_OPTION) {
						var originalNode = originalNodes[length];
						var originalNodeName = originalNode.nodeName;

						if (originalNodeName == newNodeName) {
							var prop = null;

							if (newNodeName == STR_OPTION) {
								prop = STR_SELECTED;
							}
							else if (newNodeName == STR_INPUT && (newNode.type == STR_CHECKBOX || newNode.type == STR_RADIO)) {
								prop = STR_CHECKED;
							}

							if (prop !== null) {
								toggleNode(newNode, originalNode, prop);
							}
						}
					}
				}
			}

			var bodyHTML = bodyElClone.innerHTML;

			bodyHTML = bodyHTML.replace(REGEX_CLONE_NODE_CLEANUP, TAG_REPLACE_ORIGINAL).replace(REGEX_TAG, TAG_REPLACE_FONT);

			bodyClone.innerHTML = bodyHTML;
		},

		_getAllCSSText: function() {
			var instance = this;

			var buffer = [];
			var styleSheets = instance._getAllStyleSheets(DOC.styleSheets, STR_ALL);
			var rule;
			var cssText;

			for (var i = 0; styleSheet = styleSheets[i]; i++) {
				var rules = styleSheet.rules;

				if (rules && rules.length) {
					for (var j = 0, ruleLength = rules.length; j < ruleLength; j++) {
						rule = rules[j];

						if (!rule.href) {
							cssText = instance._getCSSTextFromRule(rule);

							buffer.push(cssText);
						}
					}
				}
			}

			return buffer.join(STR_BLANK);
		},

		_getCSSTextFromRule: function(rule) {
			var instance = this;

			var cssText = STR_EMPTY;

			var ruleStyle = rule.style;
			var ruleCSSText;
			var ruleSelectorText;

			if (ruleStyle && (ruleCSSText = ruleStyle.cssText) && (ruleSelectorText = rule.selectorText) && REGEX_ELEMENTS_FAST.test(ruleSelectorText)) {
				BUFFER_CSS_TEXT.length = 0;

				BUFFER_CSS_TEXT.push(ruleSelectorText, STR_BRACKET_OPEN, ruleCSSText, STR_BRACKET_CLOSE);

				cssText = BUFFER_CSS_TEXT.join(STR_BLANK);
			}

			return cssText;
		},

		_getAllStyleSheets: function(styleSheet, mediaType, level, buffer) {
			var instance = this;

			level = level || 1;

			buffer = buffer || [];

			var i;

			if (isStylesheetDefined(styleSheet)) {
				var imports = styleSheet.imports;

				mediaType = styleSheet.mediaType || mediaType;

				if (REGEX_PRINT_MEDIA.test(mediaType)) {
					var length;

					// IE can crash when trying to access imports more than 3 levels deep
					if (level <= 3 && isStylesheetDefined(imports) && imports.length) {
						for (i = 0, length = imports.length; i < length; i++) {
							instance._getAllStyleSheets(imports[i], mediaType, level + 1, buffer);
						}
					}
					else if (styleSheet.length) {
						for (i = 0, length = styleSheet.length; i < length; i++) {
							instance._getAllStyleSheets(styleSheet[i], mediaType, level, buffer);
						}
					}
					else {
						var rules = styleSheet.rules;
						var ruleStyleSheet;

						if (rules && rules.length) {
							for (i = 0, length = rules.length; i < length; i++) {
								ruleStyleSheet = rules[i].styleSheet;

								if (ruleStyleSheet) {
									instance._getAllStyleSheets(ruleStyleSheet, mediaType, level, buffer);
								}
							}
						}
					}

					if (!styleSheet.disabled && styleSheet.rules) {
						buffer.push(styleSheet);
					}
				}
			}

			mediaType = STR_ALL;

			return buffer;
		},

		_getBodyEl: function() {
			var instance = this;

			var bodyEl = instance._bodyEl;

			if (!bodyEl) {
				bodyEl = DOC.body;

				instance._bodyEl = bodyEl;
			}

			return bodyEl;
		},

		_getBodyClone: function() {
			var instance = this;

			var bodyClone = instance._bodyClone;

			if (!bodyClone) {
				bodyClone = DOC.createElement('body');

				instance._bodyClone = bodyClone;
			}

			return bodyClone;
		},

		_getDocFrag: function() {
			var instance = this;

			var docFrag = instance._docFrag;

			if (!docFrag) {
				docFrag = DOC.createDocumentFragment();

				html5shiv(docFrag);

				instance._docFrag = docFrag;
			}

			return docFrag;
		},

		_getStyleSheet: function() {
			var instance = this;

			var styleSheet = instance._styleSheet;

			if (!styleSheet) {
				styleSheet = DOC.createElement('style');

				var head = DOC.documentElement.firstChild;

				head.insertBefore(styleSheet, head.firstChild);

				styleSheet.media = 'print';
				styleSheet.className = CSS_PRINTFIX;

				instance._styleSheet = styleSheet;
			}

			return styleSheet;
		}
	}
);

A.namespace('HTML5').PrintFix = PrintFix;

PrintFix();<commit_msg>AUI-808 Iframe location is not retained during printing in IE<commit_after>var CONFIG = A.config,
	DOC = CONFIG.doc,
	WIN = CONFIG.win,
	UA = A.UA,
	IE = UA.ie,

	isShivDisabled = function() {
		return WIN.AUI_HTML5_IE === false;
	};

if (!IE || IE >= 9 || isShivDisabled()) {
	return;
}

var BUFFER_CSS_TEXT = [],

	CSS_PRINTFIX = 'aui-printfix',
	CSS_PRINTFIX_PREFIX = 'aui-printfix-',

	LOCATION = WIN.location,

	DOMAIN = LOCATION.protocol + '//' + LOCATION.host,

	GLOBAL_AUI = YUI.AUI,

	HTML = DOC.documentElement,

	HTML5_ELEMENTS = GLOBAL_AUI.HTML5_ELEMENTS,
	HTML5_ELEMENTS_LENGTH = HTML5_ELEMENTS.length,
	HTML5_ELEMENTS_LIST = HTML5_ELEMENTS.join('|'),

	REGEX_CLONE_NODE_CLEANUP = new RegExp('<(/?):(' + HTML5_ELEMENTS_LIST + ')', 'gi'),
	REGEX_ELEMENTS = new RegExp('(' + HTML5_ELEMENTS_LIST + ')', 'gi'),
	REGEX_ELEMENTS_FAST = new RegExp('\\b(' + HTML5_ELEMENTS_LIST + ')\\b', 'i'),

	REGEX_PRINT_MEDIA = /print|all/,

	REGEX_RULE = new RegExp('(^|[^\\n{}]*?\\s)(' + HTML5_ELEMENTS_LIST + ').*?{([^}]*)}', 'gim'),
	REGEX_TAG = new RegExp('<(\/*)(' + HTML5_ELEMENTS_LIST + ')', 'gi'),

	SELECTOR_REPLACE_RULE = '.' + CSS_PRINTFIX_PREFIX + '$1',

	STR_ALL = 'all',
	STR_BLANK = ' ',
	STR_EMPTY = '',

	STR_BRACKET_OPEN = '{',
	STR_BRACKET_CLOSE = '}',

	STR_CHECKBOX = 'checkbox',
	STR_CHECKED = 'checked',
	STR_HTTPS = 'https',
	STR_IFRAME = 'IFRAME',
	STR_INPUT = 'INPUT',
	STR_OPTION = 'OPTION',
	STR_RADIO = 'radio',
	STR_SELECTED = 'selected',
	STR_STAR = '*',
	STR_URL = 'url(',
	STR_URL_DOMAIN = STR_URL + DOMAIN,

	TAG_REPLACE_ORIGINAL = '<$1$2',
	TAG_REPLACE_FONT = '<$1font';

var html5shiv = GLOBAL_AUI.html5shiv,
	// Yes, IE does this wackiness; converting an object
	// to a string should never result in undefined, but
	// IE's styleSheet object sometimes becomes inaccessible
	// after trying to print the second time
	isStylesheetDefined = function(obj) {
		return obj && (obj + STR_EMPTY !== undefined);
	},

	toggleNode = function(node, origNode, prop) {
		var state = origNode[prop];

		if (state) {
			node.setAttribute(prop, state);
		}
		else {
			node.removeAttribute(prop);
		}
	};

	html5shiv(DOC);

var PrintFix = function() {
	var afterPrint = function() {
		if (isShivDisabled()) {
			destroy();
		}
		else {
			PrintFix.onAfterPrint();
		}
	};

	var beforePrint = function() {
		if (isShivDisabled()) {
			destroy();
		}
		else {
			PrintFix.onBeforePrint();
		}
	};

	var destroy = function() {
		WIN.detachEvent('onafterprint', afterPrint);
		WIN.detachEvent('onbeforeprint', beforePrint);
	};

	var init = function() {
		WIN.attachEvent('onafterprint', afterPrint);
		WIN.attachEvent('onbeforeprint', beforePrint);
	};

	init();

	PrintFix.destroy = destroy;
	PrintFix.init = init;
};

A.mix(
	PrintFix,
	{
		onAfterPrint: function() {
			var instance = this;

			instance.restoreHTML();

			var styleSheet = instance._getStyleSheet();

			styleSheet.styleSheet.cssText = STR_EMPTY;
		},

		onBeforePrint: function() {
			var instance = this;

			var styleSheet = instance._getStyleSheet();
			var cssRules = instance._getAllCSSText();

			styleSheet.styleSheet.cssText = instance.parseCSS(cssRules);

			instance.writeHTML();
		},

		parseCSS: function(cssText) {
			var instance = this;

			var css = STR_EMPTY;
			var rules = cssText.match(REGEX_RULE);

			if (rules) {
				css = rules.join('\n').replace(REGEX_ELEMENTS, SELECTOR_REPLACE_RULE);
			}

			return css;
		},

		restoreHTML: function() {
			var instance = this;

			var bodyClone = instance._getBodyClone();
			var bodyEl = instance._getBodyEl();

			var newNodes = bodyClone.getElementsByTagName(STR_IFRAME);
			var originalNodes = bodyEl.getElementsByTagName(STR_IFRAME);

			var length = originalNodes.length;

			// Moving IFRAME nodes back to their original position
			if (length == newNodes.length) {
				while (length--) {
					var newNode = newNodes[length];
					var originalNode = originalNodes[length];

					originalNode.swapNode(newNode);
				}
			}

			bodyClone.innerHTML = STR_EMPTY;

			HTML.removeChild(bodyClone);
			HTML.appendChild(bodyEl);
		},

		writeHTML: function() {
			var instance = this;

			var i = -1;
			var j;

			var bodyEl = instance._getBodyEl();

			var html5Element;

			var cssClass;

			var nodeList;
			var nodeListLength;
			var node;
			var buffer = [];

			while (++i < HTML5_ELEMENTS_LENGTH) {
				html5Element = HTML5_ELEMENTS[i];

				nodeList = DOC.getElementsByTagName(html5Element);
				nodeListLength = nodeList.length;

				j = -1;

				while (++j < nodeListLength) {
					node = nodeList[j];

					cssClass = node.className;

					if (cssClass.indexOf(CSS_PRINTFIX_PREFIX) == -1) {
						buffer[0] = CSS_PRINTFIX_PREFIX + html5Element;
						buffer[1] = cssClass;

						node.className = buffer.join(STR_BLANK);
					}
				}
			}

			var docFrag = instance._getDocFrag();
			var bodyClone = instance._getBodyClone();

			docFrag.appendChild(bodyEl);
			HTML.appendChild(bodyClone);

			bodyClone.className = bodyEl.className;
			bodyClone.id = bodyEl.id;

			var originalNodes = bodyEl.getElementsByTagName(STR_STAR);
			var length = originalNodes.length;

			// IE will throw a mixed content warning when using https
			// and calling clone node if the body contains elements with
			// an inline background-image style that is relative to the domain.
			if (UA.secure) {
				var bodyElStyle = bodyEl.style;

				var elStyle;
				var backgroundImage;

				bodyElStyle.display = 'none';

				for (i = 0; i < length; i++) {
					elStyle = originalNodes[i].style;

					backgroundImage = elStyle.backgroundImage;

					if (backgroundImage &&
						backgroundImage.indexOf(STR_URL) > -1 &&
						backgroundImage.indexOf(STR_HTTPS) == -1) {

						elStyle.backgroundImage = backgroundImage.replace(STR_URL, STR_URL_DOMAIN);
					}
				}

				bodyElStyle.display = STR_EMPTY;
			}

			var bodyElClone = bodyEl.cloneNode(true);

			var newNodes = bodyElClone.getElementsByTagName(STR_STAR);

			if (length == newNodes.length) {
				while (length--) {
					var newNode = newNodes[length];
					var newNodeName = newNode.nodeName;

					if (newNodeName == STR_INPUT || newNodeName == STR_OPTION) {
						var originalNode = originalNodes[length];
						var originalNodeName = originalNode.nodeName;

						if (originalNodeName == newNodeName) {
							var prop = null;

							if (newNodeName == STR_OPTION) {
								prop = STR_SELECTED;
							}
							else if (newNodeName == STR_INPUT && (newNode.type == STR_CHECKBOX || newNode.type == STR_RADIO)) {
								prop = STR_CHECKED;
							}

							if (prop !== null) {
								toggleNode(newNode, originalNode, prop);
							}
						}
					}
				}
			}

			var bodyHTML = bodyElClone.innerHTML;

			bodyHTML = bodyHTML.replace(REGEX_CLONE_NODE_CLEANUP, TAG_REPLACE_ORIGINAL).replace(REGEX_TAG, TAG_REPLACE_FONT);

			bodyClone.innerHTML = bodyHTML;

			// Post processing the DOM in order to move IFRAME nodes

			newNodes = bodyClone.getElementsByTagName(STR_IFRAME);
			originalNodes = bodyEl.getElementsByTagName(STR_IFRAME);

			length = originalNodes.length;

			if (length == newNodes.length) {
				while (length--) {
					var newNode = newNodes[length];
					var originalNode = originalNodes[length];

					// According to quirksmode.org, swapNode is supported on all major IE versions
					originalNode.swapNode(newNode);
				}
			}
		},

		_getAllCSSText: function() {
			var instance = this;

			var buffer = [];
			var styleSheets = instance._getAllStyleSheets(DOC.styleSheets, STR_ALL);
			var rule;
			var cssText;

			for (var i = 0; styleSheet = styleSheets[i]; i++) {
				var rules = styleSheet.rules;

				if (rules && rules.length) {
					for (var j = 0, ruleLength = rules.length; j < ruleLength; j++) {
						rule = rules[j];

						if (!rule.href) {
							cssText = instance._getCSSTextFromRule(rule);

							buffer.push(cssText);
						}
					}
				}
			}

			return buffer.join(STR_BLANK);
		},

		_getCSSTextFromRule: function(rule) {
			var instance = this;

			var cssText = STR_EMPTY;

			var ruleStyle = rule.style;
			var ruleCSSText;
			var ruleSelectorText;

			if (ruleStyle && (ruleCSSText = ruleStyle.cssText) && (ruleSelectorText = rule.selectorText) && REGEX_ELEMENTS_FAST.test(ruleSelectorText)) {
				BUFFER_CSS_TEXT.length = 0;

				BUFFER_CSS_TEXT.push(ruleSelectorText, STR_BRACKET_OPEN, ruleCSSText, STR_BRACKET_CLOSE);

				cssText = BUFFER_CSS_TEXT.join(STR_BLANK);
			}

			return cssText;
		},

		_getAllStyleSheets: function(styleSheet, mediaType, level, buffer) {
			var instance = this;

			level = level || 1;

			buffer = buffer || [];

			var i;

			if (isStylesheetDefined(styleSheet)) {
				var imports = styleSheet.imports;

				mediaType = styleSheet.mediaType || mediaType;

				if (REGEX_PRINT_MEDIA.test(mediaType)) {
					var length;

					// IE can crash when trying to access imports more than 3 levels deep
					if (level <= 3 && isStylesheetDefined(imports) && imports.length) {
						for (i = 0, length = imports.length; i < length; i++) {
							instance._getAllStyleSheets(imports[i], mediaType, level + 1, buffer);
						}
					}
					else if (styleSheet.length) {
						for (i = 0, length = styleSheet.length; i < length; i++) {
							instance._getAllStyleSheets(styleSheet[i], mediaType, level, buffer);
						}
					}
					else {
						var rules = styleSheet.rules;
						var ruleStyleSheet;

						if (rules && rules.length) {
							for (i = 0, length = rules.length; i < length; i++) {
								ruleStyleSheet = rules[i].styleSheet;

								if (ruleStyleSheet) {
									instance._getAllStyleSheets(ruleStyleSheet, mediaType, level, buffer);
								}
							}
						}
					}

					if (!styleSheet.disabled && styleSheet.rules) {
						buffer.push(styleSheet);
					}
				}
			}

			mediaType = STR_ALL;

			return buffer;
		},

		_getBodyEl: function() {
			var instance = this;

			var bodyEl = instance._bodyEl;

			if (!bodyEl) {
				bodyEl = DOC.body;

				instance._bodyEl = bodyEl;
			}

			return bodyEl;
		},

		_getBodyClone: function() {
			var instance = this;

			var bodyClone = instance._bodyClone;

			if (!bodyClone) {
				bodyClone = DOC.createElement('body');

				instance._bodyClone = bodyClone;
			}

			return bodyClone;
		},

		_getDocFrag: function() {
			var instance = this;

			var docFrag = instance._docFrag;

			if (!docFrag) {
				docFrag = DOC.createDocumentFragment();

				html5shiv(docFrag);

				instance._docFrag = docFrag;
			}

			return docFrag;
		},

		_getStyleSheet: function() {
			var instance = this;

			var styleSheet = instance._styleSheet;

			if (!styleSheet) {
				styleSheet = DOC.createElement('style');

				var head = DOC.documentElement.firstChild;

				head.insertBefore(styleSheet, head.firstChild);

				styleSheet.media = 'print';
				styleSheet.className = CSS_PRINTFIX;

				instance._styleSheet = styleSheet;
			}

			return styleSheet;
		}
	}
);

A.namespace('HTML5').PrintFix = PrintFix;

PrintFix();<|endoftext|>


<commit_before>import Ember from 'ember';

export function pokeType([types]/*, hash*/) {
	var sortedTypes = types.sort((a, b) => a.slot - b.slot);
	return sortedTypes
		.map(typeData => typeData.type.name)
		.join(' / ');
}

export default Ember.Helper.helper(pokeType);
<commit_msg>Capitalize first letter of type<commit_after>import Ember from 'ember';

export function pokeType([types]/*, hash*/) {
	var sortedTypes = types.sort((a, b) => a.slot - b.slot);
	return sortedTypes
		.map(typeData => typeData.type.name)
		.map(name => name[0].toUpperCase() + name.slice(1).toLowerCase())
		.join(' / ');
}

export default Ember.Helper.helper(pokeType);
<|endoftext|>