<commit_before>/*
Node wrapper for Freshdesk v2 API

Copyright (C) 2016-2017 Maksim Koryukov <maxkoryukov@gmail.com>

This program is free software: you can redistribute it and/or modify
it under the terms of the MIT License, attached to this software package.

This program 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.

You should have received a copy of the MIT License along with this
program. If not, see <https://opensource.org/licenses/MIT>.

http://spdx.org/licenses/MIT
*/

'use strict'

const nock = require('nock')

const Freshdesk = require('..')

describe('api.tickets', function () {

	const freshdesk = new Freshdesk('https://test.freshdesk.com', 'TESTKEY')

	describe('listAllTicketFields', () => {

		describe('without params', () => {

			let res = null

			beforeEach(() => {
				res = [
					{
						"id": 1,
						"description": "Ticket requester",
						"label": "Search a requester",
						"name": "requester",
						"position": 1,
						"portal_cc": false,
						"portal_cc_to": "company",
						"type": "default_requester",
					},
				]

				// SET UP expected request
				nock('https://test.freshdesk.com')
					.get('/api/v2/ticket_fields')
					//.query({})
					.reply(200, res)
			})

			it('should send GET request to /api/v2/ticket_fields', function (done) {
				freshdesk.listAllTicketFields((err, data) => {
					expect(err).is.null
					expect(data).to.deep.equal(res)

					done()
				})
			})

			it('(explicit null) should send GET request to /api/v2/ticket_fields', function (done) {
				freshdesk.listAllTicketFields(null, (err, data, extra) => {
					expect(err).is.null
					expect(data).to.deep.equal(res)
					expect(extra).to.be.an('object')
						.that.have.property('requestId', '')

					done()
				})
			})
		})

		describe('with params', () => {

			let res = null

			beforeEach(() => {
				res = [{
					"id": 1,
					"description": "Ticket requester",
					"label": "Search a requester",
					"name": "requester",
					"position": 1,
					"portal_cc": false,
					"portal_cc_to": "company",
					"type": "default_requester",
				}]

				// SET UP expected request
				nock('https://test.freshdesk.com')
					.get('/api/v2/ticket_fields')
					.query({'type': 'default_requester'})
					.reply(200, res)
			})

			it('should send GET request to /api/v2/ticket_fields?type=xx', function (done) {

				const params = {'type': 'default_requester'}

				freshdesk.listAllTicketFields(params, (err, data) => {
					expect(err).is.null
					expect(data).to.deep.equal(res)

					done()
				})
			})

		})

	})

	describe('listAllTicket', () => {

		describe('without params', () => {

			let res = null
			let params = {}

			beforeEach(() => {
				res = [{
					"cc_emails": ["user@cc.com", "user2@cc.com"],
					"fwd_emails": [],
					"reply_cc_emails": ["user@cc.com", "user2@cc.com"],
					"fr_escalated": false,
					"spam": false,
					"email_config_id": null,
					"group_id": 2,
					"priority": 1,
					"requester_id": 5,
					"responder_id": 1,
					"source": 2,
					"status": 2,
					"subject": "Please help",
					"to_emails": null,
					"product_id": null,
					"id": 18,
					"type": "Lead",
					"created_at": "2015-08-17T12:02:50Z",
					"updated_at": "2015-08-17T12:02:51Z",
					"due_by": "2015-08-20T11:30:00Z",
					"fr_due_by": "2015-08-18T11:30:00Z",
					"is_escalated": false,
					"custom_fields": {
						"category": "Default",
					},
				}]

				// SET UP expected request
				nock('https://test.freshdesk.com')
					.get('/api/v2/tickets')
					.query(params)
					.reply(200, res)
			})

			it('should send GET request to /api/v2/tickets', function (done) {

				freshdesk.listAllTickets(params, (err, data) => {
					expect(err).is.null
					expect(data).to.deep.equal(res)

					done()
				})
			})

		})

		describe('with params', () => {

			let res = null
			let params = {'type': 'default_requester'}

			beforeEach(() => {
				res = [{
					"cc_emails": ["user@cc.com", "user2@cc.com"],
					"fwd_emails": [],
					"reply_cc_emails": ["user@cc.com", "user2@cc.com"],
					"fr_escalated": false,
					"spam": false,
					"email_config_id": null,
					"group_id": 2,
					"priority": 1,
					"requester_id": 5,
					"responder_id": 1,
					"source": 2,
					"status": 2,
					"subject": "Please help",
					"to_emails": null,
					"product_id": null,
					"id": 18,
					"type": "Lead",
					"created_at": "2015-08-17T12:02:50Z",
					"updated_at": "2015-08-17T12:02:51Z",
					"due_by": "2015-08-20T11:30:00Z",
					"fr_due_by": "2015-08-18T11:30:00Z",
					"is_escalated": false,
					"custom_fields": {
						"category": "Default",
					},
				}]

				// SET UP expected request
				nock('https://test.freshdesk.com')
					.get('/api/v2/tickets')
					.query(params)
					.reply(200, res)
			})

			it('should send GET request to /api/v2/tickets', function (done) {

				freshdesk.listAllTickets(params, (err, data) => {
					expect(err).is.null
					expect(data).to.deep.equal(res)

					done()
				})
			})

		})
	})
})
<commit_msg>Add more tests<commit_after>/*
Node wrapper for Freshdesk v2 API

Copyright (C) 2016-2017 Maksim Koryukov <maxkoryukov@gmail.com>

This program is free software: you can redistribute it and/or modify
it under the terms of the MIT License, attached to this software package.

This program 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.

You should have received a copy of the MIT License along with this
program. If not, see <https://opensource.org/licenses/MIT>.

http://spdx.org/licenses/MIT
*/

'use strict'

const nock = require('nock')

const Freshdesk = require('..')

describe('api.tickets', function () {

	const freshdesk = new Freshdesk('https://test.freshdesk.com', 'TESTKEY')

	describe('listAllTicketFields', () => {

		describe('without params', () => {

			let res = null

			beforeEach(() => {
				res = [
					{
						"id": 1,
						"description": "Ticket requester",
						"label": "Search a requester",
						"name": "requester",
						"position": 1,
						"portal_cc": false,
						"portal_cc_to": "company",
						"type": "default_requester",
					},
				]

				// SET UP expected request
				nock('https://test.freshdesk.com')
					.get('/api/v2/ticket_fields')
					//.query({})
					.reply(200, res)
			})

			it('should send GET request to /api/v2/ticket_fields', function (done) {
				freshdesk.listAllTicketFields((err, data) => {
					expect(err).is.null
					expect(data).to.deep.equal(res)

					done()
				})
			})

			it('(explicit null) should send GET request to /api/v2/ticket_fields', function (done) {
				freshdesk.listAllTicketFields(null, (err, data, extra) => {
					expect(err).is.null
					expect(data).to.deep.equal(res)
					expect(extra).to.be.an('object')
						.that.have.property('requestId', '')

					done()
				})
			})
		})

		describe('with params', () => {

			let res = null

			beforeEach(() => {
				res = [{
					"id": 1,
					"description": "Ticket requester",
					"label": "Search a requester",
					"name": "requester",
					"position": 1,
					"portal_cc": false,
					"portal_cc_to": "company",
					"type": "default_requester",
				}]

				// SET UP expected request
				nock('https://test.freshdesk.com')
					.get('/api/v2/ticket_fields')
					.query({'type': 'default_requester'})
					.reply(200, res)
			})

			it('should send GET request to /api/v2/ticket_fields?type=xx', function (done) {

				const params = {'type': 'default_requester'}

				freshdesk.listAllTicketFields(params, (err, data) => {
					expect(err).is.null
					expect(data).to.deep.equal(res)

					done()
				})
			})

		})

	})

	describe('listAllTicket', () => {

		describe('without params', () => {

			let res = null
			let params = {}

			beforeEach(() => {
				res = [{
					"cc_emails": ["user@cc.com", "user2@cc.com"],
					"fwd_emails": [],
					"reply_cc_emails": ["user@cc.com", "user2@cc.com"],
					"fr_escalated": false,
					"spam": false,
					"email_config_id": null,
					"group_id": 2,
					"priority": 1,
					"requester_id": 5,
					"responder_id": 1,
					"source": 2,
					"status": 2,
					"subject": "Please help",
					"to_emails": null,
					"product_id": null,
					"id": 18,
					"type": "Lead",
					"created_at": "2015-08-17T12:02:50Z",
					"updated_at": "2015-08-17T12:02:51Z",
					"due_by": "2015-08-20T11:30:00Z",
					"fr_due_by": "2015-08-18T11:30:00Z",
					"is_escalated": false,
					"custom_fields": {
						"category": "Default",
					},
				}]

				// SET UP expected request
				nock('https://test.freshdesk.com')
					.get('/api/v2/tickets')
					.query(params)
					.reply(200, res)
			})

			it('should send GET request to /api/v2/tickets', function (done) {

				freshdesk.listAllTickets(params, (err, data) => {
					expect(err).is.null
					expect(data).to.deep.equal(res)

					done()
				})
			})

		})

		describe('with params', () => {

			let res = null
			let params = {'type': 'default_requester'}

			beforeEach(() => {
				res = [{
					"cc_emails": ["user@cc.com", "user2@cc.com"],
					"fwd_emails": [],
					"reply_cc_emails": ["user@cc.com", "user2@cc.com"],
					"fr_escalated": false,
					"spam": false,
					"email_config_id": null,
					"group_id": 2,
					"priority": 1,
					"requester_id": 5,
					"responder_id": 1,
					"source": 2,
					"status": 2,
					"subject": "Please help",
					"to_emails": null,
					"product_id": null,
					"id": 18,
					"type": "Lead",
					"created_at": "2015-08-17T12:02:50Z",
					"updated_at": "2015-08-17T12:02:51Z",
					"due_by": "2015-08-20T11:30:00Z",
					"fr_due_by": "2015-08-18T11:30:00Z",
					"is_escalated": false,
					"custom_fields": {
						"category": "Default",
					},
				}]

				// SET UP expected request
				nock('https://test.freshdesk.com')
					.get('/api/v2/tickets')
					.query(params)
					.reply(200, res)
			})

			it('should send GET request to /api/v2/tickets', function (done) {

				freshdesk.listAllTickets(params, (err, data) => {
					expect(err).is.null
					expect(data).to.deep.equal(res)

					done()
				})
			})

		})
	})

	describe('createTicket', () => {

		describe('with params', () => {

			let res = null
			let data = {
				"description": "Details about the issue...",
				"subject": "Support Needed...",
				"email": "tom@outerspace.com",
				"priority": 1,
				"status": 2,
				"cc_emails": ["ram@freshdesk.com", "diana@freshdesk.com"],
			}

			beforeEach(() => {
				res = {
					"cc_emails": ["ram@freshdesk.com", "diana@freshdesk.com"],
					"fwd_emails": [],
					"reply_cc_emails": ["ram@freshdesk.com", "diana@freshdesk.com"],
					"email_config_id": null,
					"group_id": null,
					"priority": 1,
					"requester_id": 129,
					"responder_id": null,
					"source": 2,
					"status": 2,
					"subject": "Support needed..",
					"company_id": 1,
					"id": 1,
					"type": "Question",
					"to_emails": null,
					"product_id": null,
					"fr_escalated": false,
					"spam": false,
					"urgent": false,
					"is_escalated": false,
					"created_at": "2015-07-09T13:08:06Z",
					"updated_at": "2015-07-23T04:41:12Z",
					"due_by": "2015-07-14T13:08:06Z",
					"fr_due_by": "2015-07-10T13:08:06Z",
					"description_text": "Some details on the issue ...",
					"description": "
Some details on the issue ..
",
					"tags": [],
					"attachments": [],
				}

				// SET UP expected request
				nock('https://test.freshdesk.com')
					.post(`/api/v2/tickets`, data)
					.reply(200, res)
			})

			it('should send POST request to /api/v2/tickets', function (done) {

				freshdesk.createTicket(data, (err, data) => {
					expect(err).is.null
					expect(data).to.deep.equal(res)

					done()
				})
			})

		})

	})

	describe('updateTicket', () => {

		describe('with params', () => {

			let res = null
			let ticket_id = 'ticket_id'
			let data = {
				"description": "Details about the issue...",
				"subject": "Support Needed...",
				"email": "tom@outerspace.com",
				"priority": 1,
				"status": 2,
				"cc_emails": ["ram@freshdesk.com", "diana@freshdesk.com"],
			}

			beforeEach(() => {
				res = {
					"cc_emails": ["ram@freshdesk.com", "diana@freshdesk.com"],
					"fwd_emails": [],
					"reply_cc_emails": ["ram@freshdesk.com", "diana@freshdesk.com"],
					"email_config_id": null,
					"group_id": null,
					"priority": 1,
					"requester_id": 129,
					"responder_id": null,
					"source": 2,
					"status": 2,
					"subject": "Support needed..",
					"company_id": 1,
					"id": 1,
					"type": "Question",
					"to_emails": null,
					"product_id": null,
					"fr_escalated": false,
					"spam": false,
					"urgent": false,
					"is_escalated": false,
					"created_at": "2015-07-09T13:08:06Z",
					"updated_at": "2015-07-23T04:41:12Z",
					"due_by": "2015-07-14T13:08:06Z",
					"fr_due_by": "2015-07-10T13:08:06Z",
					"description_text": "Some details on the issue ...",
					"description": "
Some details on the issue ..
",
					"tags": [],
					"attachments": [],
				}

				// SET UP expected request
				nock('https://test.freshdesk.com/')
					.put(`/api/v2/tickets/${ticket_id}`, data)
					.reply(200, res)
			})

			it('should send PUT request to /api/v2/tickets/id', function (done) {

				freshdesk.updateTicket(ticket_id, data, (err, data) => {
					expect(err).is.null
					expect(data).to.deep.equal(res)

					done()
				})
			})

		})

	})

	describe('deleteTicket', () => {

		describe('with params', () => {

			let res = null
			let ticket_id = 'ticket_id'

			beforeEach(() => {
				res = null

				// SET UP expected request
				nock('https://test.freshdesk.com/')
					.delete(`/api/v2/tickets/${ticket_id}`)
					.reply(204, res)
			})

			it('should send DELETE request to /api/v2/tickets/id', function (done) {

				freshdesk.deleteTicket(ticket_id, (err, data) => {
					expect(err).is.null
					expect(data).to.deep.equal(res)

					done()
				})
			})

		})

	})

	describe('restoreTicket', () => {

		describe('with params', () => {

			let res = null
			let ticket_id = 'ticket_id'

			beforeEach(() => {
				res = null

				// SET UP expected request
				nock('https://test.freshdesk.com/')
					.put(`/api/v2/tickets/${ticket_id}/restore`)
					.reply(204, res)
			})

			it('should send PUT request to /api/v2/tickets/id/restore', function (done) {

				freshdesk.restoreTicket(ticket_id, (err, data) => {
					expect(err).is.null
					expect(data).to.deep.equal(res)

					done()
				})
			})

		})

	})
})
<|endoftext|>


<commit_before>'use strict';

const path = require('path');
const helpers = require('yeoman-test');
const assert = require('yeoman-assert');

module.exports = () => {

  describe('linters', () => {

    before(done => {
      this.generator = helpers
        .run(path.join(__dirname, '../../generators/app'))
        .toPromise()
        .then(() => done());
    });

    it('should add HTMLHint rules', () => {
      assert.file('.htmlhintrc');
    });

    it('should add ESLint rules', () => {
      assert.file('.eslintrc');
      assert.file('.eslintignore');
    });

    it('should add SCSSLint rules', () => {

      before(done => {
        this.generator = helpers
          .run(path.join(__dirname, '../../generators/app'))
          .withPrompts({
            cssPreprocessor: 'sass'
          })
          .toPromise()
          .then(() => done());
      });

      assert.file('.scsslintrc');
    });

  });

};
<commit_msg>test(linters): csslint support<commit_after>'use strict';

const path = require('path');
const helpers = require('yeoman-test');
const assert = require('yeoman-assert');

module.exports = () => {

  describe('linters', () => {

    before(done => {
      this.generator = helpers
        .run(path.join(__dirname, '../../generators/app'))
        .toPromise()
        .then(() => done());
    });

    it('should add HTMLHint rules', () => {
      assert.file('.htmlhintrc');
    });

    it('should add ESLint rules', () => {
      assert.file('.eslintrc');
      assert.file('.eslintignore');
    });

    it('should use CSSLint rules', () => {

      before(done => {
        this.generator = helpers
          .run(path.join(__dirname, '../../generators/app'))
          .withPrompts({
            cssPreprocessor: 'css'
          })
          .toPromise()
          .then(() => done());
      });

      assert.file('.csslintrc');
      assert.fileContent('package.json', 'csslint src/styles/');
      assert.fileContent('package.json', '"csslint"');
    });

    it('should use SCSSLint rules', () => {

      before(done => {
        this.generator = helpers
          .run(path.join(__dirname, '../../generators/app'))
          .withPrompts({
            cssPreprocessor: 'sass'
          })
          .toPromise()
          .then(() => done());
      });

      assert.file('.scsslintrc');
      assert.fileContent('package.json', 'scss-lint src/styles/');
    });

  });

};
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var connect = require('connect'),
    helpers = require('./helpers'),
    assert = require('assert'),
    http = require('http');

module.exports = {
    'test urlencoded body': function(){
        var server = helpers.run(
            connect.bodyDecoder(),
            function(req, res){
                assert.eql({ user: { name: 'tj' }}, req.body, 'Test body-decoder urlencoded req.body');
                res.writeHead(200);
                res.end();
            }
        );
        var req = server.request('POST', '/', { 'Content-Type': 'application/x-www-form-urlencoded' });
        req.write('user[name]=tj');
        req.end();
    },

    'test json body': function(){
        var server = helpers.run(
            connect.bodyDecoder(),
            function(req, res){
                assert.eql({ user: { name: 'tj' }}, req.body, 'Test body-decoder json req.body');
                res.writeHead(200);
                res.end();
            }
        );
        var req = server.request('POST', '/', { 'Content-Type': 'application/json; charset=utf8' });
        req.write('{"user":{"name":"tj"}}');
        req.end();
    },

    'test empty body': function(){
        var server = helpers.run(
            connect.bodyDecoder(),
            function(req, res){
                assert.eql({}, req.body, 'Test body-decoder empty req.body');
                res.writeHead(200);
                res.end();
            }
        );
        var req = server.request('POST', '/', { 'Content-Type': 'application/json; charset=utf8' });
        req.write('');
        req.end();
    },

    'test invalid body': function(){
        var server = helpers.run(
            connect.bodyDecoder(),
            function(err, req, res, next){
                assert.equal('unexpected_eos', err.type, 'Test body-decoder invalid json error');
                assert.equal('{"user":{"name":"tj"', req.rawBody, 'Test body-decoder req.rawBody');
                assert.strictEqual(undefined, req.body, 'Test body-decoder invalid json req.body');
                res.writeHead(200);
                res.end();
            }
        );
        var req = server.request('POST', '/', { 'Content-Type': 'application/json' });
        req.write('{"user":{"name":"tj"');
        req.end();
    },

    'test custom decoder': function(){
        connect.bodyDecoder.decode['my/type'] = function(str){
            return str.replace(/ +/g, '');
        };
        var server = helpers.run(
            connect.bodyDecoder(),
            function(req, res){
                res.writeHead(200);
                res.end(req.body);
            }
        );
        var req = server.request('POST', '/', { 'Content-Type': 'my/type' });
        req.buffer = true;
        req.on('response', function(res){
            res.on('end', function(){
                assert.equal('foobar', res.body, 'Test custom decoder function');
            });
        });
        req.write('f o o b a r');
        req.end();
    }
}<commit_msg>Fixed bodyDecoder tests<commit_after>
/**
 * Module dependencies.
 */

var connect = require('connect'),
    assert = require('assert'),
    http = require('http');

var app = connect.createServer(
  connect.bodyDecoder(),
  function(req, res){
  res.writeHead(200);
  res.end(JSON.stringify(req.body));
});

module.exports = {
  'test x-www-form-urlencoded body': function(){
    assert.response(app,
      { url: '/'
      , data: 'foo=bar'
      , method: 'POST'
      , headers: { 'Content-Type': 'application/x-www-form-urlencoded' }},
      { body: '{"foo":"bar"}' });
  },

  'test PUT x-www-form-urlencoded body': function(){
    assert.response(app,
      { url: '/'
      , data: 'foo=bar'
      , method: 'PUT'
      , headers: { 'Content-Type': 'application/x-www-form-urlencoded' }},
      { body: '{"foo":"bar"}' });
  },

  'test json body': function(){
    assert.response(app,
      { url: '/'
      , data: '{"foo":"bar"}'
      , method: 'PUT'
      , headers: { 'Content-Type': 'application/json' }},
      { body: '{"foo":"bar"}' });
  },

  'test POST with no data': function(){
    assert.response(app,
      { url: '/', method: 'POST' },
      { body: '' });
  }
};<|endoftext|>


<commit_before>/* Copyright (c) 2012-2016 The TagSpaces Authors. All rights reserved.
 * Use of this source code is governed by a AGPL3 license that
 * can be found in the LICENSE file. */

define(function(require, exports, module) {
  'use strict';

  var TSCORE = require("tscore");

  var maxTmbSize = 300;
  var supportedImageExtensions = ["jpg", "jpeg", "png", "gif"];

  function makeMetaPathByName(name) {
    return TSCORE.currentPath + TSCORE.dirSeparator + TSCORE.metaFolder + name;
  }

  function getDirectoryMetaInformation() {
    var metaFolderPath = TSCORE.currentPath + TSCORE.dirSeparator + TSCORE.metaFolder;
    console.log("getDirectoryMetaInformation: " + metaFolderPath);
    return TSCORE.IO.listDirectoryPromise(metaFolderPath, true);
  }

  function findMetaFilebyPath(filePath, metaFileExtension) {
    var metaFilePath;
    var metaFolderPath = TSCORE.TagUtils.extractParentDirectoryPath(filePath) + TSCORE.dirSeparator + TSCORE.metaFolder;
    filePath = metaFolderPath + TSCORE.dirSeparator + TSCORE.TagUtils.extractFileName(filePath) + metaFileExtension;
    TSCORE.metaFileList.every(function(element) {
      if (filePath.indexOf(element.path) >= 0) {
        metaFilePath = element.path;
        return false;
      }
      return true;
    });
    return metaFilePath;
  }

  function findMetaObjectFromFileList(filePath) {
    var metaObj = null;
    TSCORE.fileList.every(function(element) {
      if (element.path === filePath) {
        metaObj = element.meta;
        return false;
      }
      return true;
    });
    return metaObj;
  }

  function saveMetaData(filePath, metaData) {
    var metaFilePath = findMetaFilebyPath(filePath, TSCORE.metaFileExt);
    var currentVersion = TSCORE.Config.DefaultSettings.appVersion + "." + TSCORE.Config.DefaultSettings.appBuild;
    if (!metaFilePath) {
      var name = TSCORE.Utils.baseName(filePath) + TSCORE.metaFileExt;
      var parentFolder = TSCORE.TagUtils.extractParentDirectoryPath(filePath);
      metaFilePath = parentFolder + TSCORE.dirSeparator + TSCORE.metaFolder + TSCORE.dirSeparator + name;
      var entry = {
        "name": name,
        "isFile": true,
        "path": metaFilePath,
      };
      TSCORE.metaFileList.push(entry);
      metaData.appVersionCreated = currentVersion;
    }

    metaData.appName = TSCORE.Config.DefaultSettings.appName;
    metaData.appVersionUpdated = currentVersion;
    metaData.lastUpdated = new Date();

    var content = JSON.stringify(metaData);
    TSCORE.IO.saveTextFilePromise(metaFilePath, content, true);
  }

  function updateMetaData(sourceFilePath, targetFilePath) {
    if (!targetFilePath || !sourceFilePath) {
      return false;
    }

    if (TSCORE.IO.stopWatchingDirectories) {
      TSCORE.IO.stopWatchingDirectories();
    }

    var fileInMetaFileList = false;
    var sourceFileName = TSCORE.Utils.baseName(sourceFilePath);
    var pathSource = TSCORE.Utils.dirName(sourceFilePath);
    var pathTarget = TSCORE.Utils.dirName(targetFilePath);
    TSCORE.metaFileList.forEach(function(metaElement, index) {
      if (metaElement.name.indexOf(sourceFileName) === 0) {
        fileInMetaFileList = true;

        var targetMetaName = TSCORE.Utils.baseName(targetFilePath) + "." + TSCORE.TagUtils.extractFileExtension(metaElement.name);
        var targetMetaFolderPath = pathTarget + TSCORE.dirSeparator + TSCORE.metaFolder;
        var targetMetaFilePath = targetMetaFolderPath + TSCORE.dirSeparator + targetMetaName;
        var sourceMetaFilePath = pathSource + TSCORE.dirSeparator + TSCORE.metaFolder + TSCORE.dirSeparator + metaElement.name;

        if (pathSource === pathTarget) {
          metaElement.name = targetMetaName;
          metaElement.path = targetMetaFilePath;
        } else {
          TSCORE.metaFileList.splice(index, 1);
        }

        createMetaFolderPromise(pathTarget).then(function() {
          TSCORE.IO.renameFilePromise(sourceMetaFilePath, targetMetaFilePath).then(function() {
            console.log('Meta file moved/renamed successfully to ' + targetMetaFilePath);
          });
        });
      }
    });
    if (!fileInMetaFileList) { // file is probably from a search list
      var sourceMetaPathTemplate = pathSource + TSCORE.dirSeparator + TSCORE.metaFolder + TSCORE.dirSeparator + TSCORE.Utils.baseName(sourceFilePath);
      var targetMetaPathTemplate = pathTarget + TSCORE.dirSeparator + TSCORE.metaFolder + TSCORE.dirSeparator + TSCORE.Utils.baseName(targetFilePath);
      TSCORE.IO.renameFilePromise(sourceMetaPathTemplate + TSCORE.metaFileExt, targetMetaPathTemplate + TSCORE.metaFileExt);
      TSCORE.IO.renameFilePromise(sourceMetaPathTemplate + TSCORE.thumbFileExt, targetMetaPathTemplate + TSCORE.thumbFileExt);
      TSCORE.IO.renameFilePromise(sourceMetaPathTemplate + TSCORE.contentFileExt, targetMetaPathTemplate + TSCORE.contentFileExt);
    }
  }

  // Deletes the meta data, the thumbs and the content file
  function deleteMetaData(sourceFileName) {
    if (!sourceFileName) {
      return false;
    }

    var name = TSCORE.Utils.baseName(sourceFileName);
    var fileInMetaFileList = false;
    TSCORE.metaFileList.forEach(function(element, index) {
      if (element.name.indexOf(name) >= 0) {
        fileInMetaFileList = true;
        // Deleting meta.json, thumb.png and content.txt files
        TSCORE.IO.deleteFilePromise(element.path).then(function() {
          TSCORE.metaFileList.splice(index, 1);
        });
      }
    });
    if (!fileInMetaFileList) { // file is probably from a search list
      var sourcePathTemplate = TSCORE.Utils.dirName(sourceFileName) + TSCORE.dirSeparator + TSCORE.metaFolder + TSCORE.dirSeparator + TSCORE.Utils.baseName(sourceFileName);
      TSCORE.IO.deleteFilePromise(sourcePathTemplate + TSCORE.metaFileExt);
      TSCORE.IO.deleteFilePromise(sourcePathTemplate + TSCORE.thumbFileExt);
      TSCORE.IO.deleteFilePromise(sourcePathTemplate + TSCORE.contentFileExt);
    }
  }

  // Copy only the meta data without the thumbs and extracted text content
  function copyMetaData(sourceFileName, targetFileName) {
    if (!sourceFileName || !targetFileName) {
      return false;
    }

    var pathSource = TSCORE.Utils.dirName(sourceFileName);
    var pathTarget = TSCORE.Utils.dirName(targetFileName);

    if (pathTarget.lastIndexOf(TSCORE.dirSeparator) === 0) {
      pathSource = pathSource + TSCORE.dirSeparator;
    }

    if (pathSource !== pathTarget) {
      var sourceFilePath = pathSource + TSCORE.dirSeparator + TSCORE.metaFolder + TSCORE.dirSeparator + TSCORE.Utils.baseName(sourceFileName) + TSCORE.metaFileExt;
      var targetFilePath = pathTarget + TSCORE.dirSeparator + TSCORE.metaFolder + TSCORE.dirSeparator + TSCORE.Utils.baseName(targetFileName) + TSCORE.metaFileExt;
      createMetaFolderPromise(pathTarget).then(function() {
        TSCORE.IO.copyFilePromise(sourceFilePath, targetFilePath);
      });
    }
  }

  function loadThumbnailPromise(filePath) {
    return new Promise(function(resolve, reject) {
      if (TSCORE.PRO && TSCORE.Config.getEnableMetaData() && TSCORE.Config.getUseGenerateThumbnails()) {
        TSCORE.PRO.getThumbnailURLPromise(filePath).then(function(dataURL) {
          resolve(dataURL);
        }).catch(function(err) {
          console.warn("Thumb generation failed for: " + filePath + " failed with: " + err);
          resolve(filePath);
        });
      } else {
        var metaFilePath = findMetaFilebyPath(filePath, TSCORE.thumbFileExt);
        if (metaFilePath && isChrome) {
          metaFilePath = "file://" + metaFilePath;
        }
        var fileExt = TSCORE.TagUtils.extractFileExtension(filePath);
        if (metaFilePath) {
          resolve(metaFilePath);
        } else if (supportedImageExtensions.indexOf(fileExt) >= 0) {
          if (isChrome) {
            filePath = "file://" + filePath;
          }
          generateImageThumbnail(filePath).then(function(dataURL) {
            resolve(dataURL);
          }).catch(function() {
            resolve();
          });
        }
      }
    });
  }

  // should be in sync with the function from the PRO version
  function generateImageThumbnail(fileURL) {
    return new Promise(function(resolve, reject) {
      var canvas = document.createElement("canvas");
      var ctx = canvas.getContext("2d");
      var img = new Image();

      var errorHandler = function(err) {
        console.warn("Error while generating thumbnail for: " + fileURL + " - " + JSON.stringify(err));
        resolve("");
      };

      try {
        img.crossOrigin = 'anonymous';
        img.onload = function() {
          if (img.width >= img.height) {
            canvas.width = maxTmbSize;
            canvas.height = (maxTmbSize * img.height) / img.width;
          } else {
            canvas.height = maxTmbSize;
            canvas.width = (maxTmbSize * img.width) / img.height;
          }
          ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
          resolve(canvas.toDataURL("image/png"));
          img = null;
          canvas = null;
        };
        img.src = fileURL;
      } catch (err) {
        errorHandler(err);
      }
    });
  }

  function loadMetaFileJsonPromise(entry) {
    return new Promise(function(resolve, reject) {
      var filePath = entry.path;
      var parentFolder = TSCORE.TagUtils.extractParentDirectoryPath(filePath);
      var metaFileJson = findMetaFilebyPath(filePath, TSCORE.metaFileExt);
      if (metaFileJson) { // file in the current directory
        TSCORE.IO.getFileContentPromise(metaFileJson, "text").then(function(result) {
          var metaData = JSON.parse(result);
          entry.meta.metaData = metaData;
          resolve(filePath);
        }).catch(function(err) {
          console.warn("Getting meta information failed for: " + filePath);
          resolve(filePath);
        });
      } else if (TSCORE.currentPath !== parentFolder) { // file in search results
        metaFileJson = parentFolder + TSCORE.dirSeparator + TSCORE.metaFolder + TSCORE.dirSeparator + TSCORE.Utils.baseName(filePath) + TSCORE.metaFileExt;
        TSCORE.IO.getFileContentPromise(metaFileJson, "text").then(function(result) {
          var metaData = JSON.parse(result);
          entry.meta.metaData = metaData;
          resolve(filePath);
        }).catch(function(err) {
          console.warn("Getting meta information failed for: " + filePath);
          resolve(filePath);
        });
      } else {
        console.log("No meta information found for: " + filePath);
        resolve(filePath);
      }
    });
  }

  function loadMetaFileJsonPromiseOld(entry) {
    return new Promise(function(resolve, reject) {
      var filePath = entry.path;
      var metaFileJson = findMetaFilebyPath(filePath, TSCORE.metaFileExt);
      if (metaFileJson) {
        TSCORE.IO.getFileContentPromise(metaFileJson, "text").then(function(result) {
          var metaData = JSON.parse(result);
          entry.meta.metaData = metaData;
          resolve(filePath);
        }).catch(function(err) {
          console.warn("Getting meta information failed for: " + filePath);
          resolve(filePath);
        });
      } else {
        console.log("No meta information found for: " + filePath);
        resolve(filePath);
      }
    });
  }

  function getTagsFromMetaFile(filePath) {
    var tags = [];
    var metaObj = findMetaObjectFromFileList(filePath);
    if (metaObj && metaObj.metaData && metaObj.metaData.tags) {
      metaObj.metaData.tags.forEach(function(elem) {
        tags.push({
          tag: elem.title,
          filepath: filePath,
          style: elem.style
        });
      });
    }
    return tags;
  }

  //meta tag utils
  function addMetaTags(filePath, tags) {
    var metaObj = findMetaObjectFromFileList(filePath);
    if (!metaObj) {
      metaObj = {
        thumbnailPath: "",
        metaData: null,
      };
    }

    if (!metaObj.metaData) {
      metaObj.metaData = {
        tags: []
      };
    }

    if (!metaObj.metaData.tags) {
      metaObj.metaData.tags = [];
    }

    tags.forEach(function(element) {
      var newTag = {
        "title": element,
        "type": "sidecar",
        "style": TSCORE.generateTagStyle(TSCORE.Config.findTag(element))
      };
      var isNewTag = true;
      metaObj.metaData.tags.forEach(function(oldTag) {
        if (oldTag.title === element) {
          isNewTag = false;
        }
      });
      if (isNewTag) {
        metaObj.metaData.tags.push(newTag);
      }
    });

    saveMetaData(filePath, metaObj.metaData);
  }

  function renameMetaTag(filePath, oldTag, newTag) {
    var metaObj = findMetaObjectFromFileList(filePath);
    if (metaObj.metaData) {
      metaObj.metaData.tags.forEach(function(tag, index) {
        if (tag.title === oldTag) {
          tag.title = newTag;
        }
      });
      saveMetaData(filePath, metaObj.metaData);
    }
  }

  function removeMetaTag(filePath, tagName) {
    var metaObj = findMetaObjectFromFileList(filePath);
    if (metaObj.metaData) {
      metaObj.metaData.tags.forEach(function(tag, index) {
        if (tag.title === tagName) {
          metaObj.metaData.tags.splice(index, 1);
        }
      });
      var metaFileJson = findMetaFilebyPath(filePath, TSCORE.metaFileExt);
      if (metaFileJson) {
        var content = JSON.stringify(metaObj.metaData);
        TSCORE.IO.saveTextFilePromise(metaFileJson, content, true);
      }
    }
  }

  function loadFolderMetaDataPromise(path) {
    return new Promise(function(resolve, reject) {
      var metadataPath = 'file://' + path + TSCORE.dirSeparator + TSCORE.metaFolder + TSCORE.dirSeparator + TSCORE.metaFolderFile;
      if (isWeb) {
        metadataPath = path + TSCORE.dirSeparator + TSCORE.metaFolder + TSCORE.dirSeparator + TSCORE.metaFolderFile;
      }

      TSCORE.IO.getFileContentPromise(metadataPath, "text").then(function(content) {
        var metadata = JSON.parse(content);
        console.log('Location Metadata: ' + JSON.stringify(metadata));
        resolve(metadata);
      }).catch(function(err) {
        reject("loadFolderMetaDataPromise: Error reading " + metadataPath);
      });
    });
  }

  function createMetaFolderPromise(dirPath) {
    return new Promise(function(resolve, reject) {
      if (dirPath.lastIndexOf(TSCORE.metaFolder) >= dirPath.length - TSCORE.metaFolder.length) {
        console.log("Can not create meta folder in a meta folder");
        reject();
        return;
      }
      var metaDirPath = dirPath + TSCORE.dirSeparator + TSCORE.metaFolder;
      TSCORE.IO.createDirectoryPromise(metaDirPath).then(function() {
        console.log("Metafolder created: " + metaDirPath);
        resolve(metaDirPath);
      }).catch(function(error) {
        resolve(metaDirPath);
        //reject("Creating metafolder failed, it was probably already created " + error);
      });
    });
  }

  exports.getDirectoryMetaInformation = getDirectoryMetaInformation;
  exports.findMetaFilebyPath = findMetaFilebyPath;
  exports.findMetaObjectFromFileList = findMetaObjectFromFileList;
  exports.saveMetaData = saveMetaData;
  exports.deleteMetaData = deleteMetaData;
  exports.updateMetaData = updateMetaData;
  exports.copyMetaData = copyMetaData;
  exports.loadMetaFileJsonPromise = loadMetaFileJsonPromise;
  exports.loadThumbnailPromise = loadThumbnailPromise;
  exports.getTagsFromMetaFile = getTagsFromMetaFile;
  exports.addMetaTags = addMetaTags;
  exports.renameMetaTag = renameMetaTag;
  exports.removeMetaTag = removeMetaTag;
  exports.loadFolderMetaDataPromise = loadFolderMetaDataPromise;
  exports.createMetaFolderPromise = createMetaFolderPromise;
});
<commit_msg>fixing sidecar issues with file renames<commit_after>/* Copyright (c) 2012-2016 The TagSpaces Authors. All rights reserved.
 * Use of this source code is governed by a AGPL3 license that
 * can be found in the LICENSE file. */

define(function(require, exports, module) {
  'use strict';

  var TSCORE = require("tscore");

  var maxTmbSize = 300;
  var supportedImageExtensions = ["jpg", "jpeg", "png", "gif"];

  function makeMetaPathByName(name) {
    return TSCORE.currentPath + TSCORE.dirSeparator + TSCORE.metaFolder + name;
  }

  function getDirectoryMetaInformation() {
    var metaFolderPath = TSCORE.currentPath + TSCORE.dirSeparator + TSCORE.metaFolder;
    console.log("getDirectoryMetaInformation: " + metaFolderPath);
    return TSCORE.IO.listDirectoryPromise(metaFolderPath, true);
  }

  function findMetaFilebyPath(filePath, metaFileExtension) {
    var metaFilePath;
    var metaFolderPath = TSCORE.TagUtils.extractParentDirectoryPath(filePath) + TSCORE.dirSeparator + TSCORE.metaFolder;
    filePath = metaFolderPath + TSCORE.dirSeparator + TSCORE.TagUtils.extractFileName(filePath) + metaFileExtension;
    TSCORE.metaFileList.every(function(element) {
      if (filePath.indexOf(element.path) >= 0) {
        metaFilePath = element.path;
        return false;
      }
      return true;
    });
    return metaFilePath;
  }

  function findMetaObjectFromFileList(filePath) {
    var metaObj = null;
    TSCORE.fileList.every(function(element) {
      if (element.path === filePath) {
        metaObj = element.meta;
        return false;
      }
      return true;
    });
    return metaObj;
  }

  function saveMetaData(filePath, metaData) {
    var metaFilePath = findMetaFilebyPath(filePath, TSCORE.metaFileExt);
    var currentVersion = TSCORE.Config.DefaultSettings.appVersion + "." + TSCORE.Config.DefaultSettings.appBuild;
    if (!metaFilePath) {
      var name = TSCORE.Utils.baseName(filePath) + TSCORE.metaFileExt;
      var parentFolder = TSCORE.TagUtils.extractParentDirectoryPath(filePath);
      metaFilePath = parentFolder + TSCORE.dirSeparator + TSCORE.metaFolder + TSCORE.dirSeparator + name;
      var entry = {
        "name": name,
        "isFile": true,
        "path": metaFilePath,
      };
      TSCORE.metaFileList.push(entry);
      metaData.appVersionCreated = currentVersion;
    }

    metaData.appName = TSCORE.Config.DefaultSettings.appName;
    metaData.appVersionUpdated = currentVersion;
    metaData.lastUpdated = new Date();

    var content = JSON.stringify(metaData);
    TSCORE.IO.saveTextFilePromise(metaFilePath, content, true);
  }

  function updateMetaData(sourceFilePath, targetFilePath) {
    if (!targetFilePath || !sourceFilePath) {
      return false;
    }

    if (TSCORE.IO.stopWatchingDirectories) {
      TSCORE.IO.stopWatchingDirectories();
    }

    var fileInMetaFileList = false;
    var sourceFileName = TSCORE.Utils.baseName(sourceFilePath);
    var pathSource = TSCORE.Utils.dirName(sourceFilePath);
    var pathTarget = TSCORE.Utils.dirName(targetFilePath);
    var metaIndexForRemove = [];
    TSCORE.metaFileList.forEach(function(metaElement, index) {
      if (metaElement.name.indexOf(sourceFileName) === 0) {
        fileInMetaFileList = true;

        var targetMetaName = TSCORE.Utils.baseName(targetFilePath) + "." + TSCORE.TagUtils.extractFileExtension(metaElement.name);
        var targetMetaFolderPath = pathTarget + TSCORE.dirSeparator + TSCORE.metaFolder;
        var targetMetaFilePath = targetMetaFolderPath + TSCORE.dirSeparator + targetMetaName;
        var sourceMetaFilePath = pathSource + TSCORE.dirSeparator + TSCORE.metaFolder + TSCORE.dirSeparator + metaElement.name;

        if (pathSource === pathTarget) {
          metaElement.name = targetMetaName;
          metaElement.path = targetMetaFilePath;
        } else {
          metaIndexForRemove.push(index);
        }

        createMetaFolderPromise(pathTarget).then(function() {
          TSCORE.IO.renameFilePromise(sourceMetaFilePath, targetMetaFilePath).then(function() {
            console.log('Meta file moved/renamed successfully to ' + targetMetaFilePath);
          });
        });
      }
    });

    // file is probably from a search list
    if (!fileInMetaFileList) {
      var sourceMetaPathTemplate = pathSource + TSCORE.dirSeparator + TSCORE.metaFolder + TSCORE.dirSeparator + TSCORE.Utils.baseName(sourceFilePath);
      var targetMetaPathTemplate = pathTarget + TSCORE.dirSeparator + TSCORE.metaFolder + TSCORE.dirSeparator + TSCORE.Utils.baseName(targetFilePath);
      TSCORE.IO.renameFilePromise(sourceMetaPathTemplate + TSCORE.metaFileExt, targetMetaPathTemplate + TSCORE.metaFileExt);
      TSCORE.IO.renameFilePromise(sourceMetaPathTemplate + TSCORE.thumbFileExt, targetMetaPathTemplate + TSCORE.thumbFileExt);
      TSCORE.IO.renameFilePromise(sourceMetaPathTemplate + TSCORE.contentFileExt, targetMetaPathTemplate + TSCORE.contentFileExt);
    }

    // Cleaning up meteFileList
    if (metaIndexForRemove.length > 0) {
      TSCORE.metaFileList.forEach(function(metaElement, index) {
        if (index in metaIndexForRemove) {
          TSCORE.metaFileList.splice(index, 1);
        }
      });
    }
  }

  // Deletes the meta data, the thumbs and the content file
  function deleteMetaData(sourceFileName) {
    if (!sourceFileName) {
      return false;
    }

    var name = TSCORE.Utils.baseName(sourceFileName);
    var fileInMetaFileList = false;
    TSCORE.metaFileList.forEach(function(element, index) {
      if (element.name.indexOf(name) >= 0) {
        fileInMetaFileList = true;
        // Deleting meta.json, thumb.png and content.txt files
        TSCORE.IO.deleteFilePromise(element.path).then(function() {
          TSCORE.metaFileList.splice(index, 1);
        });
      }
    });
    if (!fileInMetaFileList) { // file is probably from a search list
      var sourcePathTemplate = TSCORE.Utils.dirName(sourceFileName) + TSCORE.dirSeparator + TSCORE.metaFolder + TSCORE.dirSeparator + TSCORE.Utils.baseName(sourceFileName);
      TSCORE.IO.deleteFilePromise(sourcePathTemplate + TSCORE.metaFileExt);
      TSCORE.IO.deleteFilePromise(sourcePathTemplate + TSCORE.thumbFileExt);
      TSCORE.IO.deleteFilePromise(sourcePathTemplate + TSCORE.contentFileExt);
    }
  }

  // Copy only the meta data without the thumbs and extracted text content
  function copyMetaData(sourceFileName, targetFileName) {
    if (!sourceFileName || !targetFileName) {
      return false;
    }

    var pathSource = TSCORE.Utils.dirName(sourceFileName);
    var pathTarget = TSCORE.Utils.dirName(targetFileName);

    if (pathTarget.lastIndexOf(TSCORE.dirSeparator) === 0) {
      pathSource = pathSource + TSCORE.dirSeparator;
    }

    if (pathSource !== pathTarget) {
      var sourceFilePath = pathSource + TSCORE.dirSeparator + TSCORE.metaFolder + TSCORE.dirSeparator + TSCORE.Utils.baseName(sourceFileName) + TSCORE.metaFileExt;
      var targetFilePath = pathTarget + TSCORE.dirSeparator + TSCORE.metaFolder + TSCORE.dirSeparator + TSCORE.Utils.baseName(targetFileName) + TSCORE.metaFileExt;
      createMetaFolderPromise(pathTarget).then(function() {
        TSCORE.IO.copyFilePromise(sourceFilePath, targetFilePath);
      });
    }
  }

  function loadThumbnailPromise(filePath) {
    return new Promise(function(resolve, reject) {
      if (TSCORE.PRO && TSCORE.Config.getEnableMetaData() && TSCORE.Config.getUseGenerateThumbnails()) {
        TSCORE.PRO.getThumbnailURLPromise(filePath).then(function(dataURL) {
          resolve(dataURL);
        }).catch(function(err) {
          console.warn("Thumb generation failed for: " + filePath + " failed with: " + err);
          resolve(filePath);
        });
      } else {
        var metaFilePath = findMetaFilebyPath(filePath, TSCORE.thumbFileExt);
        if (metaFilePath && isChrome) {
          metaFilePath = "file://" + metaFilePath;
        }
        var fileExt = TSCORE.TagUtils.extractFileExtension(filePath);
        if (metaFilePath) {
          resolve(metaFilePath);
        } else if (supportedImageExtensions.indexOf(fileExt) >= 0) {
          if (isChrome) {
            filePath = "file://" + filePath;
          }
          generateImageThumbnail(filePath).then(function(dataURL) {
            resolve(dataURL);
          }).catch(function() {
            resolve();
          });
        }
      }
    });
  }

  // should be in sync with the function from the PRO version
  function generateImageThumbnail(fileURL) {
    return new Promise(function(resolve, reject) {
      var canvas = document.createElement("canvas");
      var ctx = canvas.getContext("2d");
      var img = new Image();

      var errorHandler = function(err) {
        console.warn("Error while generating thumbnail for: " + fileURL + " - " + JSON.stringify(err));
        resolve("");
      };

      try {
        img.crossOrigin = 'anonymous';
        img.onload = function() {
          if (img.width >= img.height) {
            canvas.width = maxTmbSize;
            canvas.height = (maxTmbSize * img.height) / img.width;
          } else {
            canvas.height = maxTmbSize;
            canvas.width = (maxTmbSize * img.width) / img.height;
          }
          ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
          resolve(canvas.toDataURL("image/png"));
          img = null;
          canvas = null;
        };
        img.src = fileURL;
      } catch (err) {
        errorHandler(err);
      }
    });
  }

  function loadMetaFileJsonPromise(entry) {
    return new Promise(function(resolve, reject) {
      var filePath = entry.path;
      var parentFolder = TSCORE.TagUtils.extractParentDirectoryPath(filePath);
      var metaFileJson = findMetaFilebyPath(filePath, TSCORE.metaFileExt);
      if (metaFileJson) { // file in the current directory
        TSCORE.IO.getFileContentPromise(metaFileJson, "text").then(function(result) {
          var metaData = JSON.parse(result);
          entry.meta.metaData = metaData;
          resolve(filePath);
        }).catch(function(err) {
          console.warn("Getting meta information failed for: " + filePath);
          resolve(filePath);
        });
      } else if (TSCORE.currentPath !== parentFolder) { // file in search results
        metaFileJson = parentFolder + TSCORE.dirSeparator + TSCORE.metaFolder + TSCORE.dirSeparator + TSCORE.Utils.baseName(filePath) + TSCORE.metaFileExt;
        TSCORE.IO.getFileContentPromise(metaFileJson, "text").then(function(result) {
          var metaData = JSON.parse(result);
          entry.meta.metaData = metaData;
          resolve(filePath);
        }).catch(function(err) {
          console.warn("Getting meta information failed for: " + filePath);
          resolve(filePath);
        });
      } else {
        console.log("No meta information found for: " + filePath);
        resolve(filePath);
      }
    });
  }

  function loadMetaFileJsonPromiseOld(entry) {
    return new Promise(function(resolve, reject) {
      var filePath = entry.path;
      var metaFileJson = findMetaFilebyPath(filePath, TSCORE.metaFileExt);
      if (metaFileJson) {
        TSCORE.IO.getFileContentPromise(metaFileJson, "text").then(function(result) {
          var metaData = JSON.parse(result);
          entry.meta.metaData = metaData;
          resolve(filePath);
        }).catch(function(err) {
          console.warn("Getting meta information failed for: " + filePath);
          resolve(filePath);
        });
      } else {
        console.log("No meta information found for: " + filePath);
        resolve(filePath);
      }
    });
  }

  function getTagsFromMetaFile(filePath) {
    var tags = [];
    var metaObj = findMetaObjectFromFileList(filePath);
    if (metaObj && metaObj.metaData && metaObj.metaData.tags) {
      metaObj.metaData.tags.forEach(function(elem) {
        tags.push({
          tag: elem.title,
          filepath: filePath,
          style: elem.style
        });
      });
    }
    return tags;
  }

  //meta tag utils
  function addMetaTags(filePath, tags) {
    var metaObj = findMetaObjectFromFileList(filePath);
    if (!metaObj) {
      metaObj = {
        thumbnailPath: "",
        metaData: null,
      };
    }

    if (!metaObj.metaData) {
      metaObj.metaData = {
        tags: []
      };
    }

    if (!metaObj.metaData.tags) {
      metaObj.metaData.tags = [];
    }

    tags.forEach(function(element) {
      var newTag = {
        "title": element,
        "type": "sidecar",
        "style": TSCORE.generateTagStyle(TSCORE.Config.findTag(element))
      };
      var isNewTag = true;
      metaObj.metaData.tags.forEach(function(oldTag) {
        if (oldTag.title === element) {
          isNewTag = false;
        }
      });
      if (isNewTag) {
        metaObj.metaData.tags.push(newTag);
      }
    });

    saveMetaData(filePath, metaObj.metaData);
  }

  function renameMetaTag(filePath, oldTag, newTag) {
    var metaObj = findMetaObjectFromFileList(filePath);
    if (metaObj.metaData) {
      metaObj.metaData.tags.forEach(function(tag, index) {
        if (tag.title === oldTag) {
          tag.title = newTag;
        }
      });
      saveMetaData(filePath, metaObj.metaData);
    }
  }

  function removeMetaTag(filePath, tagName) {
    var metaObj = findMetaObjectFromFileList(filePath);
    if (metaObj.metaData) {
      metaObj.metaData.tags.forEach(function(tag, index) {
        if (tag.title === tagName) {
          metaObj.metaData.tags.splice(index, 1);
        }
      });
      var metaFileJson = findMetaFilebyPath(filePath, TSCORE.metaFileExt);
      if (metaFileJson) {
        var content = JSON.stringify(metaObj.metaData);
        TSCORE.IO.saveTextFilePromise(metaFileJson, content, true);
      }
    }
  }

  function loadFolderMetaDataPromise(path) {
    return new Promise(function(resolve, reject) {
      var metadataPath = 'file://' + path + TSCORE.dirSeparator + TSCORE.metaFolder + TSCORE.dirSeparator + TSCORE.metaFolderFile;
      if (isWeb) {
        metadataPath = path + TSCORE.dirSeparator + TSCORE.metaFolder + TSCORE.dirSeparator + TSCORE.metaFolderFile;
      }

      TSCORE.IO.getFileContentPromise(metadataPath, "text").then(function(content) {
        var metadata = JSON.parse(content);
        console.log('Location Metadata: ' + JSON.stringify(metadata));
        resolve(metadata);
      }).catch(function(err) {
        reject("loadFolderMetaDataPromise: Error reading " + metadataPath);
      });
    });
  }

  function createMetaFolderPromise(dirPath) {
    return new Promise(function(resolve, reject) {
      if (dirPath.lastIndexOf(TSCORE.metaFolder) >= dirPath.length - TSCORE.metaFolder.length) {
        console.log("Can not create meta folder in a meta folder");
        reject();
        return;
      }
      var metaDirPath = dirPath + TSCORE.dirSeparator + TSCORE.metaFolder;
      TSCORE.IO.createDirectoryPromise(metaDirPath).then(function() {
        console.log("Metafolder created: " + metaDirPath);
        resolve(metaDirPath);
      }).catch(function(error) {
        resolve(metaDirPath);
        //reject("Creating metafolder failed, it was probably already created " + error);
      });
    });
  }

  exports.getDirectoryMetaInformation = getDirectoryMetaInformation;
  exports.findMetaFilebyPath = findMetaFilebyPath;
  exports.findMetaObjectFromFileList = findMetaObjectFromFileList;
  exports.saveMetaData = saveMetaData;
  exports.deleteMetaData = deleteMetaData;
  exports.updateMetaData = updateMetaData;
  exports.copyMetaData = copyMetaData;
  exports.loadMetaFileJsonPromise = loadMetaFileJsonPromise;
  exports.loadThumbnailPromise = loadThumbnailPromise;
  exports.getTagsFromMetaFile = getTagsFromMetaFile;
  exports.addMetaTags = addMetaTags;
  exports.renameMetaTag = renameMetaTag;
  exports.removeMetaTag = removeMetaTag;
  exports.loadFolderMetaDataPromise = loadFolderMetaDataPromise;
  exports.createMetaFolderPromise = createMetaFolderPromise;
});
<|endoftext|>


<commit_before>/* Copyright (c) 2013-2016 The TagSpaces Authors.
 * Use of this source code is governed by the MIT license which can be found in the LICENSE.txt file. */

define(function(require, exports, module) {
  'use strict';

  var TSCORE = require("tscore");

  var maxTmbSize = 300;
  var supportedImageExtensions = ["jpg", "jpeg", "png"];

  function makeMetaPathByName(name) {
    return TSCORE.currentPath + TSCORE.dirSeparator + TSCORE.metaFolder + name;
  }

  function getDirectoryMetaInformation() {
    var metaFolderPath = TSCORE.currentPath + TSCORE.dirSeparator + TSCORE.metaFolder;
    console.log("getDirectoryMetaInformation: " + metaFolderPath);
    return TSCORE.IO.listDirectoryPromise(metaFolderPath, true);
  }

  function findMetaFilebyPath(filePath, extension) {
    var metaFilePath = null;
    filePath = filePath + extension;
    TSCORE.metaFileList.every(function(element) {
      if (filePath.indexOf(element.name) > 0) {
        metaFilePath = TSCORE.currentPath + TSCORE.dirSeparator + TSCORE.metaFolder + TSCORE.dirSeparator + element.name;
        return false;
      }
      return true;
    });
    return metaFilePath;
  }

  function findMetaObjectFromFileList(filePath) {
    var metaObj = null;
    TSCORE.fileList.every(function(element) {
      if (element.path === filePath) {
        metaObj = element.meta;
        return false;
      }
      return true;
    });
    return metaObj;
  }

  function saveMetaData(filePath, metaData) {
    var metaFilePath = findMetaFilebyPath(filePath, TSCORE.metaFileExt);
    var currentVersion = TSCORE.Config.DefaultSettings.appVersion + "." + TSCORE.Config.DefaultSettings.appBuild;
    if (!metaFilePath) {
      var name = TSCORE.Utils.baseName(filePath) + TSCORE.metaFileExt;
      metaFilePath = TSCORE.currentPath + TSCORE.dirSeparator + TSCORE.metaFolder + TSCORE.dirSeparator + name;
      var entry = {
        "name": name,
        "isFile": true,
        "path": metaFilePath,
      };
      TSCORE.metaFileList.push(entry);
      metaData.appVersionCreated = currentVersion;
    }

    metaData.appName = TSCORE.Config.DefaultSettings.appName;
    metaData.appVersionUpdated = currentVersion;
    metaData.lastUpdated = new Date();

    var content = JSON.stringify(metaData);
    TSCORE.IO.saveTextFilePromise(metaFilePath, content, true);
  }

  function updateTsMetaData(oldFileName, newFileName)  {
    var name = TSCORE.Utils.baseName(oldFileName);
    TSCORE.metaFileList.forEach(function(element, index) {
      if (element.name.indexOf(name) >= 0) {
        if (newFileName) {
          var pathOld  = TSCORE.Utils.dirName(oldFileName);
          var pathNew = TSCORE.Utils.dirName(newFileName);
          var path = TSCORE.currentPath;

          if (pathNew.lastIndexOf(TSCORE.dirSeparator) === 0) {
            pathOld += TSCORE.dirSeparator;
          }

          if (pathOld != pathNew) {
            path = pathNew;
          }
          var newName = TSCORE.Utils.baseName(newFileName) + "." + element.name.split('.').pop();
          var newFilePath = path + TSCORE.dirSeparator + TSCORE.metaFolder + TSCORE.dirSeparator + newName;
          TSCORE.IO.renameFilePromise(element.path, newFilePath);

          if (pathOld == TSCORE.currentPath) {
            element.name = newName;
            element.path = newFilePath;
          } else {
            TSCORE.metaFileList.splice(index, 1);
          }

        } else {
          TSCORE.IO.deleteFilePromise(element.path).then(function() {
            TSCORE.metaFileList.splice(index, 1);
          });
        }
      }
    });
  }

  function loadThumbnailPromise(filePath) {
    return new Promise(function(resolve, reject) {
      if (TSCORE.PRO && TSCORE.Config.getEnableMetaData() && TSCORE.Config.getUseGenerateThumbnails()) {
        TSCORE.PRO.getThumbnailURLPromise(filePath).then(function(dataURL) {
          resolve(dataURL);
        }).catch(function(err) {
          console.warn("Thumb generation failed for: " + filePath + " failed with: " + err);
          resolve(filePath);
        });
      } else {
        var metaFilePath = findMetaFilebyPath(filePath, TSCORE.thumbFileExt);
        if (metaFilePath && isChrome) {
          metaFilePath = "file://" + metaFilePath;
        }
        var fileExt = TSCORE.TagUtils.extractFileExtension(filePath);
        if (metaFilePath) {
          resolve(metaFilePath);
        } else if (supportedImageExtensions.indexOf(fileExt) >= 0) {
          if (isChrome) {
            filePath = "file://" + filePath;
          }
          generateImageThumbnail(filePath).then(function(dataURL) {
            resolve(dataURL);
          }).catch(function() {
            resolve();
          });
        }
      }
    });
  }

  // should be in sync with the function from the PRO version
  function generateImageThumbnail(fileURL) {
    return new Promise(function(resolve, reject) {
      var canvas = document.createElement("canvas");
      var ctx = canvas.getContext("2d");
      var img = new Image();

      var errorHandler = function(err) {
        console.warn("Error while generating thumbnail for: " + fileURL + " - " + JSON.stringify(err));
        resolve("");
      };

      try {
        img.crossOrigin = 'anonymous';
        img.onload = function() {
          if (img.width >= img.height) {
            canvas.width = maxTmbSize;
            canvas.height = (maxTmbSize * img.height) / img.width;
          } else {
            canvas.height = maxTmbSize;
            canvas.width = (maxTmbSize * img.width) / img.height;
          }
          ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
          resolve(canvas.toDataURL("image/png"));
          img = null;
          canvas = null;
        };
        img.src = fileURL;
      } catch (err) {
        errorHandler(err);
      }
    });
  }

  function loadMetaFileJsonPromise(entry) {
    return new Promise(function(resolve, reject) {
      var filePath = entry.path;
      var metaFileJson = findMetaFilebyPath(filePath, TSCORE.metaFileExt);
      if (metaFileJson) {
        TSCORE.IO.getFileContentPromise(metaFileJson, "text").then(function(result) {
          var metaData = JSON.parse(result);
          entry.meta.metaData = metaData;
          resolve(filePath);
        }).catch(function(err) {
          console.warn("Getting meta information failed for: " + filePath);
          resolve(filePath);
        });
      } else {
        console.log("No meta information found for: " + filePath);
        resolve(filePath);
      }
    });
  }

  function getTagsFromMetaFile(filePath) {
    var tags = [];
    var metaObj = findMetaObjectFromFileList(filePath);
    if (metaObj && metaObj.metaData && metaObj.metaData.tags) {
      metaObj.metaData.tags.forEach(function(elem) {
        tags.push({
          tag: elem.title,
          filepath: filePath,
          style: elem.style
        });
      });
    }
    return tags;
  }

  //meta tag utils
  function addMetaTags(filePath, tags) {
    var metaObj = findMetaObjectFromFileList(filePath);
    if (!metaObj) {
      metaObj = {
        thumbnailPath: "",
        metaData: null,
      };
    }

    if (!metaObj.metaData) {
      metaObj.metaData = {
        tags: []
      };
    }

    if (!metaObj.metaData.tags) {
      metaObj.metaData.tags = [];
    }

    tags.forEach(function(element) {
      var newTag = {
        "title": element,
        "type":"sidecar",
        "style": TSCORE.generateTagStyle(TSCORE.Config.findTag(element))
      };
      var isNewTag = true;
      metaObj.metaData.tags.forEach(function(oldTag) {
        if (oldTag.title === element) {
          isNewTag = false;
        }
      });
      if (isNewTag) {
        metaObj.metaData.tags.push(newTag);
      }
    });

    saveMetaData(filePath, metaObj.metaData);
  }

  function renameMetaTag(filePath, oldTag, newTag) {
    var metaObj = findMetaObjectFromFileList(filePath);
    if (metaObj.metaData) {
      metaObj.metaData.tags.forEach(function(tag , index) {
        if (tag.title === oldTag) {
          tag.title = newTag;
        }
      });
      saveMetaData(filePath, metaObj.metaData);
    }
  }

  function removeMetaTag(filePath, tagName) {
    var metaObj = findMetaObjectFromFileList(filePath);
    if (metaObj.metaData) {
      metaObj.metaData.tags.forEach(function(tag , index) {
        if (tag.title === tagName) {
          metaObj.metaData.tags.splice(index , 1);
        }
      });
      var metaFileJson = findMetaFilebyPath(filePath, TSCORE.metaFileExt);
      if (metaFileJson) {
        var content = JSON.stringify(metaObj.metaData);
        TSCORE.IO.saveTextFilePromise(metaFileJson, content, true);
      }
    }
  }

  function loadFolderMetaDataPromise(path) {
    return new Promise(function(resolve, reject) {
      var metadataPath = 'file://' + path + TSCORE.dirSeparator + TSCORE.metaFolder + TSCORE.dirSeparator + TSCORE.metaFolderFile;
      if (isWeb) {
        metadataPath = path + TSCORE.dirSeparator + TSCORE.metaFolder + TSCORE.dirSeparator + TSCORE.metaFolderFile;
      }

      TSCORE.IO.getFileContentPromise(metadataPath, "text").then(function(content) {
        var metadata = JSON.parse(content);
        console.log('Location Metadata: ' + JSON.stringify(metadata));
        resolve(metadata);
      }).catch(function(err) {
        reject("loadFolderMetaDataPromise: Error reading " + metadataPath);
      });
    });
  }

  function createMetaFolder(dirPath) {
    if (dirPath.lastIndexOf(TSCORE.metaFolder) >= dirPath.length - TSCORE.metaFolder.length) {
      console.log("Can not create meta folder in a meta folder");
      return;
    }
    var metaDirPath = dirPath + TSCORE.dirSeparator + TSCORE.metaFolder;
    TSCORE.IO.createDirectoryPromise(metaDirPath).then(function() {
      console.log("Metafolder created: " + metaDirPath);
    }).catch(function(error) {
      console.log("Creating metafolder failed, it was probably already created " + error);
    });
  }

  exports.getDirectoryMetaInformation = getDirectoryMetaInformation;
  exports.findMetaFilebyPath  =  findMetaFilebyPath;
  exports.findMetaObjectFromFileList = findMetaObjectFromFileList;
  exports.saveMetaData = saveMetaData;
  exports.updateMetaData = updateTsMetaData;
  exports.loadMetaFileJsonPromise = loadMetaFileJsonPromise;
  exports.loadThumbnailPromise = loadThumbnailPromise;
  exports.getTagsFromMetaFile = getTagsFromMetaFile;
  //tag utils
  exports.addMetaTags = addMetaTags;
  exports.renameMetaTag = renameMetaTag;
  exports.removeMetaTag = removeMetaTag;
  exports.loadFolderMetaDataPromise = loadFolderMetaDataPromise;
  exports.createMetaFolder = createMetaFolder;
});
<commit_msg>refactoring, adding add existing file menu<commit_after>/* Copyright (c) 2013-2016 The TagSpaces Authors.
 * Use of this source code is governed by the MIT license which can be found in the LICENSE.txt file. */

define(function(require, exports, module) {
  'use strict';

  var TSCORE = require("tscore");

  var maxTmbSize = 300;
  var supportedImageExtensions = ["jpg", "jpeg", "png", "gif"];

  function makeMetaPathByName(name) {
    return TSCORE.currentPath + TSCORE.dirSeparator + TSCORE.metaFolder + name;
  }

  function getDirectoryMetaInformation() {
    var metaFolderPath = TSCORE.currentPath + TSCORE.dirSeparator + TSCORE.metaFolder;
    console.log("getDirectoryMetaInformation: " + metaFolderPath);
    return TSCORE.IO.listDirectoryPromise(metaFolderPath, true);
  }

  function findMetaFilebyPath(filePath, extension) {
    var metaFilePath = null;
    filePath = filePath + extension;
    TSCORE.metaFileList.every(function(element) {
      if (filePath.indexOf(element.name) > 0) {
        metaFilePath = TSCORE.currentPath + TSCORE.dirSeparator + TSCORE.metaFolder + TSCORE.dirSeparator + element.name;
        return false;
      }
      return true;
    });
    return metaFilePath;
  }

  function findMetaObjectFromFileList(filePath) {
    var metaObj = null;
    TSCORE.fileList.every(function(element) {
      if (element.path === filePath) {
        metaObj = element.meta;
        return false;
      }
      return true;
    });
    return metaObj;
  }

  function saveMetaData(filePath, metaData) {
    var metaFilePath = findMetaFilebyPath(filePath, TSCORE.metaFileExt);
    var currentVersion = TSCORE.Config.DefaultSettings.appVersion + "." + TSCORE.Config.DefaultSettings.appBuild;
    if (!metaFilePath) {
      var name = TSCORE.Utils.baseName(filePath) + TSCORE.metaFileExt;
      metaFilePath = TSCORE.currentPath + TSCORE.dirSeparator + TSCORE.metaFolder + TSCORE.dirSeparator + name;
      var entry = {
        "name": name,
        "isFile": true,
        "path": metaFilePath,
      };
      TSCORE.metaFileList.push(entry);
      metaData.appVersionCreated = currentVersion;
    }

    metaData.appName = TSCORE.Config.DefaultSettings.appName;
    metaData.appVersionUpdated = currentVersion;
    metaData.lastUpdated = new Date();

    var content = JSON.stringify(metaData);
    TSCORE.IO.saveTextFilePromise(metaFilePath, content, true);
  }

  function updateTsMetaData(oldFileName, newFileName)  {
    var name = TSCORE.Utils.baseName(oldFileName);
    TSCORE.metaFileList.forEach(function(element, index) {
      if (element.name.indexOf(name) >= 0) {
        if (newFileName) {
          var pathOld  = TSCORE.Utils.dirName(oldFileName);
          var pathNew = TSCORE.Utils.dirName(newFileName);
          var path = TSCORE.currentPath;

          if (pathNew.lastIndexOf(TSCORE.dirSeparator) === 0) {
            pathOld += TSCORE.dirSeparator;
          }

          if (pathOld != pathNew) {
            path = pathNew;
          }
          var newName = TSCORE.Utils.baseName(newFileName) + "." + element.name.split('.').pop();
          var newFilePath = path + TSCORE.dirSeparator + TSCORE.metaFolder + TSCORE.dirSeparator + newName;
          TSCORE.IO.renameFilePromise(element.path, newFilePath);

          if (pathOld == TSCORE.currentPath) {
            element.name = newName;
            element.path = newFilePath;
          } else {
            TSCORE.metaFileList.splice(index, 1);
          }

        } else {
          TSCORE.IO.deleteFilePromise(element.path).then(function() {
            TSCORE.metaFileList.splice(index, 1);
          });
        }
      }
    });
  }

  function loadThumbnailPromise(filePath) {
    return new Promise(function(resolve, reject) {
      if (TSCORE.PRO && TSCORE.Config.getEnableMetaData() && TSCORE.Config.getUseGenerateThumbnails()) {
        TSCORE.PRO.getThumbnailURLPromise(filePath).then(function(dataURL) {
          resolve(dataURL);
        }).catch(function(err) {
          console.warn("Thumb generation failed for: " + filePath + " failed with: " + err);
          resolve(filePath);
        });
      } else {
        var metaFilePath = findMetaFilebyPath(filePath, TSCORE.thumbFileExt);
        if (metaFilePath && isChrome) {
          metaFilePath = "file://" + metaFilePath;
        }
        var fileExt = TSCORE.TagUtils.extractFileExtension(filePath);
        if (metaFilePath) {
          resolve(metaFilePath);
        } else if (supportedImageExtensions.indexOf(fileExt) >= 0) {
          if (isChrome) {
            filePath = "file://" + filePath;
          }
          generateImageThumbnail(filePath).then(function(dataURL) {
            resolve(dataURL);
          }).catch(function() {
            resolve();
          });
        }
      }
    });
  }

  // should be in sync with the function from the PRO version
  function generateImageThumbnail(fileURL) {
    return new Promise(function(resolve, reject) {
      var canvas = document.createElement("canvas");
      var ctx = canvas.getContext("2d");
      var img = new Image();

      var errorHandler = function(err) {
        console.warn("Error while generating thumbnail for: " + fileURL + " - " + JSON.stringify(err));
        resolve("");
      };

      try {
        img.crossOrigin = 'anonymous';
        img.onload = function() {
          if (img.width >= img.height) {
            canvas.width = maxTmbSize;
            canvas.height = (maxTmbSize * img.height) / img.width;
          } else {
            canvas.height = maxTmbSize;
            canvas.width = (maxTmbSize * img.width) / img.height;
          }
          ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
          resolve(canvas.toDataURL("image/png"));
          img = null;
          canvas = null;
        };
        img.src = fileURL;
      } catch (err) {
        errorHandler(err);
      }
    });
  }

  function loadMetaFileJsonPromise(entry) {
    return new Promise(function(resolve, reject) {
      var filePath = entry.path;
      var metaFileJson = findMetaFilebyPath(filePath, TSCORE.metaFileExt);
      if (metaFileJson) {
        TSCORE.IO.getFileContentPromise(metaFileJson, "text").then(function(result) {
          var metaData = JSON.parse(result);
          entry.meta.metaData = metaData;
          resolve(filePath);
        }).catch(function(err) {
          console.warn("Getting meta information failed for: " + filePath);
          resolve(filePath);
        });
      } else {
        console.log("No meta information found for: " + filePath);
        resolve(filePath);
      }
    });
  }

  function getTagsFromMetaFile(filePath) {
    var tags = [];
    var metaObj = findMetaObjectFromFileList(filePath);
    if (metaObj && metaObj.metaData && metaObj.metaData.tags) {
      metaObj.metaData.tags.forEach(function(elem) {
        tags.push({
          tag: elem.title,
          filepath: filePath,
          style: elem.style
        });
      });
    }
    return tags;
  }

  //meta tag utils
  function addMetaTags(filePath, tags) {
    var metaObj = findMetaObjectFromFileList(filePath);
    if (!metaObj) {
      metaObj = {
        thumbnailPath: "",
        metaData: null,
      };
    }

    if (!metaObj.metaData) {
      metaObj.metaData = {
        tags: []
      };
    }

    if (!metaObj.metaData.tags) {
      metaObj.metaData.tags = [];
    }

    tags.forEach(function(element) {
      var newTag = {
        "title": element,
        "type":"sidecar",
        "style": TSCORE.generateTagStyle(TSCORE.Config.findTag(element))
      };
      var isNewTag = true;
      metaObj.metaData.tags.forEach(function(oldTag) {
        if (oldTag.title === element) {
          isNewTag = false;
        }
      });
      if (isNewTag) {
        metaObj.metaData.tags.push(newTag);
      }
    });

    saveMetaData(filePath, metaObj.metaData);
  }

  function renameMetaTag(filePath, oldTag, newTag) {
    var metaObj = findMetaObjectFromFileList(filePath);
    if (metaObj.metaData) {
      metaObj.metaData.tags.forEach(function(tag , index) {
        if (tag.title === oldTag) {
          tag.title = newTag;
        }
      });
      saveMetaData(filePath, metaObj.metaData);
    }
  }

  function removeMetaTag(filePath, tagName) {
    var metaObj = findMetaObjectFromFileList(filePath);
    if (metaObj.metaData) {
      metaObj.metaData.tags.forEach(function(tag , index) {
        if (tag.title === tagName) {
          metaObj.metaData.tags.splice(index , 1);
        }
      });
      var metaFileJson = findMetaFilebyPath(filePath, TSCORE.metaFileExt);
      if (metaFileJson) {
        var content = JSON.stringify(metaObj.metaData);
        TSCORE.IO.saveTextFilePromise(metaFileJson, content, true);
      }
    }
  }

  function loadFolderMetaDataPromise(path) {
    return new Promise(function(resolve, reject) {
      var metadataPath = 'file://' + path + TSCORE.dirSeparator + TSCORE.metaFolder + TSCORE.dirSeparator + TSCORE.metaFolderFile;
      if (isWeb) {
        metadataPath = path + TSCORE.dirSeparator + TSCORE.metaFolder + TSCORE.dirSeparator + TSCORE.metaFolderFile;
      }

      TSCORE.IO.getFileContentPromise(metadataPath, "text").then(function(content) {
        var metadata = JSON.parse(content);
        console.log('Location Metadata: ' + JSON.stringify(metadata));
        resolve(metadata);
      }).catch(function(err) {
        reject("loadFolderMetaDataPromise: Error reading " + metadataPath);
      });
    });
  }

  function createMetaFolder(dirPath) {
    if (dirPath.lastIndexOf(TSCORE.metaFolder) >= dirPath.length - TSCORE.metaFolder.length) {
      console.log("Can not create meta folder in a meta folder");
      return;
    }
    var metaDirPath = dirPath + TSCORE.dirSeparator + TSCORE.metaFolder;
    TSCORE.IO.createDirectoryPromise(metaDirPath).then(function() {
      console.log("Metafolder created: " + metaDirPath);
    }).catch(function(error) {
      console.log("Creating metafolder failed, it was probably already created " + error);
    });
  }

  exports.getDirectoryMetaInformation = getDirectoryMetaInformation;
  exports.findMetaFilebyPath  =  findMetaFilebyPath;
  exports.findMetaObjectFromFileList = findMetaObjectFromFileList;
  exports.saveMetaData = saveMetaData;
  exports.updateMetaData = updateTsMetaData;
  exports.loadMetaFileJsonPromise = loadMetaFileJsonPromise;
  exports.loadThumbnailPromise = loadThumbnailPromise;
  exports.getTagsFromMetaFile = getTagsFromMetaFile;
  //tag utils
  exports.addMetaTags = addMetaTags;
  exports.renameMetaTag = renameMetaTag;
  exports.removeMetaTag = removeMetaTag;
  exports.loadFolderMetaDataPromise = loadFolderMetaDataPromise;
  exports.createMetaFolder = createMetaFolder;
});
<|endoftext|>


<commit_before>var helpers = require('./helpers');
var assert = require('assert');

describe.skip('configurable arrays', function() {
  var res = { items: null };
  before(function(done) {
    var schema = {
      'defaults': [ 'default options apply' ],
      'hardcoded': {
        'zero': [ 0, 'should not appear' ],
        'normal': [ 3, '{{Number(counter())}}']
      },
      'random': {
        'field': [ '{{_.random(1, 1)}}', '{{chance.name()}}' ],
        'doc': [ '{{_.random(1, 3)}}', {
          'some_field': '{{chance.name()}}'
        } ]
      },
      'embedded': [ 1, [ '{{Number(chance.latitude())}}',
                         '{{Number(chance.longitude())}}' ] ]
    };
    var opts = {
      size: 50,
    };
    helpers.generate(schema, opts, function (err, items) {
      if (err) return done(err);
      res.items = items;
      done();
    });
  });

  it('should not affect un-configured array', function () {
    res.items.forEach(function (item) {
      assert.ok(Array.isArray(item.defaults));
      var l = item.defaults.length;
      assert.ok(l < 4 && l > 0);
    });
  });

  it('should support hardcoded array length', function () {
    res.items.forEach(function (item) {
      assert.ok(Array.isArray(item.hardcoded.zero));
      assert.ok(Array.isArray(item.hardcoded.normal));
      assert.equal(0, item.hardcoded.zero.length);
      assert.equal(3, item.hardcoded.normal.length);
    });
  });

  it('should support random array length', function () {
    res.items.forEach(function (item) {
      assert.ok(Array.isArray(item.random.field));
      assert.ok(Array.isArray(item.random.doc));
      assert.equal(1, item.random.field.length);
      var l = item.random.doc.length;
      assert.ok(l > 0 && l < 4);
    });
  });

  // it('should support array of any length as content', function () {
  //   console.log(res.items[0].embedded);
  //   res.items.forEach(function (item) {
  //     assert.ok(Array.isArray(item.embedded));
  //     assert.equal(1, item.embedded.length);
  //     assert.ok(Array.isArray(item.embedded[0]));
  //     assert.equal(2, item.embedded[0].length);
  //     assert.ok(typeof item.embedded[0][0] === 'number');
  //     assert.ok(typeof item.embedded[0][1] === 'number');
  //   });
  // });

});
<commit_msg>tests for conf array<commit_after>var helpers = require('./helpers');
var assert = require('assert');

describe('configurable arrays', function() {
  var res = { items: null };
  before(function(done) {
    var schema = {
      'normal': {
        'empty': [ ],
        'single': [ 0 ],
        'multi': [ 0, 1 ],
        'random': [
          '{{Number(chance.d10())}}',
          '{{chance.name()}}'
        ],
        'mix': [
          1,
          { 'doc': 'got it' },
          [ 0, 1 ]
        ]
      },
      'hardcoded': {
        'zero': [ '{{_$config}}',
          { size: 0 },
          'nope'
        ],
        'count': [ '{{_$config}}',
          { size: 3 },
          '{{counter()}}'
        ]
      },
      'range': {
        'names': [ '{{_$config}}',
          { size: [2, 4] },
          '{{chance.name()}}'
        ]
      }
    };
    var opts = {
      size: 10,
    };
    helpers.generate(schema, opts, function (err, items) {
      if (err) return done(err);
      res.items = items;
      done();
    });
  });

  it('should support constant normal array', function () {
    var normal = res.items[0].normal;
    assert.ok(Array.isArray(normal.empty));
    assert.equal(0, normal.empty.length);
    assert.ok(Array.isArray(normal.single));
    assert.equal(1, normal.single.length);
    assert.equal(0, normal.single[0]);
    assert.ok(Array.isArray(normal.multi));
    assert.equal(2, normal.multi.length);
    assert.equal(0, normal.multi[0]);
    assert.equal(1, normal.multi[1]);
  });

  it('should support normal array of mixed types', function () {
    var mix = res.items[0].normal.mix;
    assert.ok(Array.isArray(mix));
    assert.equal(3, mix.length);
    assert.equal(1, mix[0]);
    assert.ok(typeof mix[1] === 'object');
    assert.equal('got it', mix[1].doc);
    assert.ok(Array.isArray(mix[2]));
    assert.equal(2, mix[2].length);
    assert.equal(0, mix[2][0]);
    assert.equal(1, mix[2][1]);
  });

  it('should support random normal array', function (done) {
    var rand = res.items[0].normal.random;
    assert.ok(Array.isArray(rand));
    assert.equal(2, rand.length);
    assert.ok(typeof rand[0] === 'number');
    assert.ok(typeof rand[1] === 'string');
    helpers.sampleAndStrip(res.items, 3, function (sample) {
      var dices = sample.map(function (s) {
        return s.normal.random[0];
      });
      var names = sample.map(function (s) {
        return s.normal.random[1];
      });
      assert.ok(dices[0] !== dices[1] || dices[0] !== dices[2]);
      assert.ok(names[0] !== names[1] || names[0] !== names[2]);
      done();
    });
  });

  it('should support hardcoded length', function () {
    var hardcoded = res.items[0].hardcoded;
    assert.ok(Array.isArray(hardcoded.zero));
    assert.equal(0, hardcoded.zero.length);
    assert.ok(Array.isArray(hardcoded.count));
    assert.equal(3, hardcoded.count.length);
    assert.equal(0, hardcoded.count[0]);
    assert.equal(1, hardcoded.count[1]);
    assert.equal(2, hardcoded.count[2]);
  });

  it('should support random array length', function () {
    res.items.forEach(function (item) {
      assert.ok(Array.isArray(item.range.names));
      var l = item.range.names.length;
      assert.ok(l > 1 && l < 5);
    });
  });

});
<|endoftext|>