<commit_before>(function ($) {
    "use strict";

    var

        buildOpts = function (jqObj) {
            var
                wrapper = jqObj.closest(".do-ui-select"),
                select = wrapper.find("select"),
                list = wrapper.find("ul.do-ui-list"),
                options = select.find("option"),
                captionText = wrapper.find(".do-ui-caption-box .do-ui-caption-text"),
                option,
                li;

            options.each(function (i, tag) {
                option = $(tag);
                li = $("

");

                li.attr("data-value", option.attr("value"));
                li.text(option.text());
                list.append(li);

                if (option.attr("selected")) {
                    captionText.text(option.text());
                }
            });

        },

        toggleCaptionClass = function (jqObj) {
            jqObj.toggleClass("do-ui-arrow-expanded", "do-ui-arrow-retracted");
        },

        //select onclick
        setActionToSelect = function (jqObj) {

            jqObj.find("li").on("click", function () {
                var
                    wrapper = jqObj.closest(".do-ui-select"),
                    caption = wrapper.find(".do-ui-caption-box"),
                    value = $(this).data("value"),
                    select = wrapper.find("select"),
                    captionText = wrapper.find(".do-ui-caption-box .do-ui-caption-text"),
                    selected;

                // remove selection
                select.find("option:selected")
                    .attr("selected", false);

                // select
                selected = select.find("option[value='" + value + "']");
                selected.attr("selected", true);

                captionText.text(selected.text());

                // esconde opções
                wrapper.find(".do-ui-options-box").hide();

                toggleCaptionClass(caption);
            });
        },

        buildOptsWithSearch = function (jqObj) {
            var
                searchBox,
                searchTextBox,
                optionsBox,
                target,
                foundsList,
                options;

            jqObj.each(function (i, select) {
                optionsBox = $(select).closest(".do-ui-select")
                    .find(".do-ui-options-box");

                searchBox = $("

");
                searchBox.addClass("do-ui-search-box");
                searchTextBox = $("<input></input>");
                searchTextBox.attr("type", "text");
                searchBox.append(searchTextBox);

                optionsBox.prepend(searchBox);
                options = optionsBox.find("ul.do-ui-list li");

                searchTextBox.autocomplete(options, function (e, found) {

                    // target
                    target = $(e.target);
                    optionsBox = target.closest(".do-ui-options-box");
                    options = optionsBox.find("ul.do-ui-list li");

                    if (optionsBox.find("ul.do-ui-list-built-found").length) {
                        foundsList = optionsBox.find(".do-ui-list-built-found");
                        foundsList.empty();
                    } else {
                        foundsList = $("

")
                            .addClass("do-ui-list-built-found");
                        optionsBox.append(foundsList);
                    }

                    if (target.val()) {
                        options.parent().hide();
                        $(found).each(function (i, li) {
                            foundsList.append(li);
                        });
                        foundsList.show();

                        setActionToSelect(foundsList);

                    } else {
                        options.parent().show();
                        foundsList.hide();
                    }

                });

            });

        };

    $.fn.buildOptions = function (params) {

        var
            caption,
            captionText,
            listBox,
            list,
            wrapper;

        // imitar esta parte para as abas
        $(this).each(function (i, select) {
            select = $(select);
            select.hide();
            wrapper = $("

");
            wrapper.addClass("do-ui-select");
            select.parent().append(wrapper);
            wrapper.append(select);

            caption = $("

");
            captionText = $("

");
            listBox = $("

");

            list = $("

");

            caption.addClass("do-ui-caption-box do-ui-arrow-retracted");
            captionText.addClass("do-ui-caption-text");
            listBox.addClass("do-ui-options-box");
            list.addClass("do-ui-list");

            wrapper.append(caption);
            caption.append(captionText);
            wrapper.append(listBox);
            listBox.append(list);

            buildOpts(list);

            // toggle
            caption.on("click", function () {
                wrapper = $(this).closest(".do-ui-select");
                wrapper.find(".do-ui-options-box").toggle();
                toggleCaptionClass($(this));
            });

            setActionToSelect(list);
        });

        if (params) {
            if (params.enableSearch) {
                buildOptsWithSearch($(this));
            }
        }

        return $(this);

    };

    // click out
    $(document).on("click", function (e) {

        var
            wrapper = $(".do-ui-select"),
            optionsBoxes = wrapper.find(".do-ui-options-box"),
            captions = wrapper.find(".do-ui-caption-box");

        if (!$(e.target).closest(".do-ui-select").length) {

            if (optionsBoxes.is(":visible")) {
                optionsBoxes.hide();
                captions.removeClass("do-ui-arrow-expanded");
            }

        }

    });

}(jQuery));
<commit_msg>adequa select a nova sintaxe de autocomplete<commit_after>(function ($) {
    "use strict";

    $.fn.buildOptions = function (params) {

        var
            caption,
            captionText,
            listBox,
            list,
            wrapper,
            select,
            options,
            option,
            li,
            value,
            selected,
            optionsBox,
            searchBox,
            searchTextBox,
            target,
            foundsList,
            optionsBoxes,
            captions,

            buildOpts = function (jqObj) {
                wrapper = jqObj.closest(".do-ui-select");
                select = wrapper.find("select");
                list = wrapper.find("ul.do-ui-list");
                options = select.find("option");
                captionText = wrapper.find(".do-ui-caption-box .do-ui-caption-text");

                options.each(function (i, tag) {
                    option = $(tag);
                    li = $("

");

                    li.attr("data-value", option.attr("value"));
                    li.text(option.text());
                    list.append(li);

                    if (option.attr("selected")) {
                        captionText.text(option.text());
                    }
                });

            },

            toggleCaptionClass = function (jqObj) {
                jqObj.toggleClass("do-ui-arrow-expanded", "do-ui-arrow-retracted");
            },

            //select onclick
            setActionToSelect = function (jqObj) {

                jqObj.find("li").on("click", function () {
                    wrapper = jqObj.closest(".do-ui-select");
                    caption = wrapper.find(".do-ui-caption-box");
                    value = $(this).data("value");
                    select = wrapper.find("select");
                    captionText = wrapper.find(".do-ui-caption-box .do-ui-caption-text");

                    // remove selection
                    select.find("option:selected")
                        .attr("selected", false);

                    // select
                    selected = select.find("option[value='" + value + "']");
                    selected.attr("selected", true);

                    captionText.text(selected.text());

                    // esconde opções
                    wrapper.find(".do-ui-options-box").hide();

                    toggleCaptionClass(caption);
                });
            },

            buildOptsWithSearch = function (jqObj) {

                jqObj.each(function (i, select) {
                    optionsBox = $(select).closest(".do-ui-select")
                        .find(".do-ui-options-box");

                    searchBox = $("

");
                    searchBox.addClass("do-ui-search-box");
                    searchTextBox = $("<input></input>");
                    searchTextBox.attr("type", "text");
                    searchBox.append(searchTextBox);

                    optionsBox.prepend(searchBox);
                    options = optionsBox.find("ul.do-ui-list li");

                    searchTextBox.autocomplete(options, params.search, function (e, found) {

                        // target
                        target = $(e.target);
                        optionsBox = target.closest(".do-ui-options-box");
                        options = optionsBox.find("ul.do-ui-list li");

                        if (optionsBox.find("ul.do-ui-list-built-found").length) {
                            foundsList = optionsBox.find(".do-ui-list-built-found");
                            foundsList.empty();
                        } else {
                            foundsList = $("

")
                                .addClass("do-ui-list-built-found");
                            optionsBox.append(foundsList);
                        }

                        if (target.val()) {
                            options.parent().hide();
                            $(found).each(function (i, li) {
                                foundsList.append(li);
                            });
                            foundsList.show();

                            setActionToSelect(foundsList);

                        } else {
                            options.parent().show();
                            foundsList.hide();
                        }

                    });

                });

            };

        // click out
        $(document).on("click", function (e) {
            wrapper = $(".do-ui-select");
            optionsBoxes = wrapper.find(".do-ui-options-box");
            captions = wrapper.find(".do-ui-caption-box");

            if (!$(e.target).closest(".do-ui-select").length) {

                if (optionsBoxes.is(":visible")) {
                    optionsBoxes.hide();
                    captions.removeClass("do-ui-arrow-expanded");
                }

            }

        });

        // imitar esta parte para as abas
        $(this).each(function (i, select) {
            select = $(select);
            select.hide();
            wrapper = $("

");
            wrapper.addClass("do-ui-select");
            select.parent().append(wrapper);
            wrapper.append(select);

            caption = $("

");
            captionText = $("

");
            listBox = $("

");

            list = $("

");

            caption.addClass("do-ui-caption-box do-ui-arrow-retracted");
            captionText.addClass("do-ui-caption-text");
            listBox.addClass("do-ui-options-box");
            list.addClass("do-ui-list");

            wrapper.append(caption);
            caption.append(captionText);
            wrapper.append(listBox);
            listBox.append(list);

            buildOpts(list);

            // toggle
            caption.on("click", function () {
                wrapper = $(this).closest(".do-ui-select");
                wrapper.find(".do-ui-options-box").toggle();
                toggleCaptionClass($(this));
            });

            setActionToSelect(list);
        });

        if (params) {
            if (params.search) {
                buildOptsWithSearch($(this));
            }
        }

        return $(this);

    };

}(jQuery));
<|endoftext|>


<commit_before>import passport from 'passport';

function configureApp(app, loginRoute, logoutRoute, userDetailsExtractor, loadInitialData) {
  app.use(passport.initialize());
  app.use(passport.session());

  app.post(loginRoute, (req, res, next) => {
    passport.authenticate('local', (err, user, params) => {
      if (err) return next(err);
      if (!user) return res.status(401).json({error: params ? params.message : 'Invalid login'});
        req.login(user, {}, error => {
        if (error) return res.status(500).json({error});
        loadInitialData(user, req).then(initialData => {
          res.json({
            ...initialData,
            user: userDetailsExtractor(user),
            returnTo: (req.session && req.session.returnTo) ? req.session.returnTo : '/'
          });
          return null;
        });
      });
    })(req, res, next);
  });

  app.get(logoutRoute, (req, res) => {
    req.logout();
    res.redirect('/');
  })
}

export default configureApp;
<commit_msg>Fixed server error message<commit_after>import passport from 'passport';

function configureApp(app, loginRoute, logoutRoute, userDetailsExtractor, loadInitialData) {
  app.use(passport.initialize());
  app.use(passport.session());

  app.post(loginRoute, (req, res, next) => {
    passport.authenticate('local', (err, user, params) => {
      if (err) return next(err);
      if (!user) return res.status(401).json({error: params ? params.message : 'Invalid login'});
      req.login(user, {}, error => {
        if (error) return res.status(500).json({error: error.message});
        loadInitialData(user, req).then(initialData => {
          res.json({
            ...initialData,
            user: userDetailsExtractor(user),
            returnTo: (req.session && req.session.returnTo) ? req.session.returnTo : '/'
          });
          return null;
        });
      });
    })(req, res, next);
  });

  app.get(logoutRoute, (req, res) => {
    req.logout();
    res.redirect('/');
  })
}

export default configureApp;
<|endoftext|>


<commit_before>var MutationSummary = require('mutation-summary').MutationSummary;

function addButton(soundActions) {
  var url;
  try {
    var wrap = soundActions.parentElement;
    // different containers:
    if (wrap.classList.contains('sound__soundActions')) { /* STREAM */
      var soundEl = soundActions.parentElement.parentElement.parentElement;
      if (soundEl.parentElement.classList.contains('single')) { /* VISUAL PAGE */
        url = location.href;
      } else {
        url = soundEl.querySelector('a.soundTitle__title').href;
      }
    } else if (wrap.classList.contains('listenEngagement__actions')) { /* PAGE */
      url = location.href;
    } else if (wrap.classList.contains('soundBadge__actions')) { /* SIDEBAR */
      var soundBadgeEl = soundActions.parentElement.parentElement.parentElement.parentElement;
      url = soundBadgeEl.querySelector('a.soundTitle__title').href;
    } else {
      console.warn('add-to-sonos: cannot find container for soundActions:', soundActions);
      return;
    }
  } catch(e) {
    console.warn('add-to-sonos: cannot get url for soundActions:', soundActions, e);
    return;
  }

  if (soundActions.querySelector('.sc-button-addtoset') !== null) {
    addButtonToSound(soundActions, url);
  } else {
    addButtonToPlaylist(soundActions, url);
  }
}

function addButtonToPlaylist(soundActions, url) {
  var repostButton = soundActions.querySelector('.sc-button-repost');
  if (typeof repostButton === 'undefined' || repostButton === null) {
    console.warn('repost playlist button not found', soundActions);
    return;
  }

  var addToSonosButton = createButton(repostButton, url);
  repostButton.parentElement.insertBefore(addToSonosButton, repostButton.nextSibling);
}

function addButtonToSound(soundActions, url) {
  var addToSetButton = soundActions.querySelector('.sc-button-addtoset');
  addToSetButton.classList.add('ats-collapse');

  var addToSonosButton = createButton(addToSetButton, url);
  addToSetButton.parentElement.insertBefore(addToSonosButton, addToSetButton.nextSibling);
}

function createButton(prevButton, url) {
  var prevClasses = prevButton.className.replace(/sc-button-(addtoset|repost)/g, '');
  var addToSonosButton = document.createElement('button');
  addToSonosButton.className = prevClasses + ' ats-button ats-collapse';
  addToSonosButton.tabIndex = 0;
  addToSonosButton.title = 'Add to Sonos';
  addToSonosButton.innerHTML = 'Add to Sonos';

  addToSonosButton.addEventListener('click', function(ev) {
    ev.preventDefault();
    ev.stopPropagation();

    addToSonosButton.classList.remove('ats-success');
    addToSonosButton.classList.remove('ats-failure');
    addToSonosButton.classList.add('ats-loading');

    chrome.runtime.sendMessage({action: 'addToPlaylist', url: url}, function(response) {
      addToSonosButton.classList.remove('ats-loading');
      if (response.success) {
        addToSonosButton.classList.add('ats-success');
      } else {
        addToSonosButton.classList.add('ats-failure');
        if (response.setup) {
          chrome.runtime.sendMessage({action: 'openSettings'});
        }
      }
    });
  }, false);

  return addToSonosButton;
}

function handleSoundActionsChanges(summaries) {
  var soundActionsSummary = summaries[0];
  soundActionsSummary.added.forEach(addButton);
}

// triggers on new soundActions
var observer = new MutationSummary({
  callback: handleSoundActionsChanges,
  queries: [{ element: 'div.soundActions' }]
});

// handle already existing soundActions
[].forEach.call(document.querySelectorAll('div.soundActions'), addButton);<commit_msg>Add button to tracks on set pages<commit_after>var MutationSummary = require('mutation-summary').MutationSummary;

function addButton(soundActions) {
  var url;
  try {
    var wrap = soundActions.parentElement;
    // different containers:
    if (wrap.classList.contains('sound__soundActions')) { /* STREAM */
      var soundEl = soundActions.parentElement.parentElement.parentElement;
      if (soundEl.parentElement.classList.contains('single')) { /* VISUAL PAGE */
        url = location.href;
      } else {
        url = soundEl.querySelector('a.soundTitle__title').href;
      }
    } else if (wrap.classList.contains('listenEngagement__actions')) { /* PAGE */
      url = location.href;
    } else if (wrap.classList.contains('soundBadge__actions')) { /* SIDEBAR */
      var soundBadgeEl = soundActions.parentElement.parentElement.parentElement.parentElement;
      url = soundBadgeEl.querySelector('a.soundTitle__title').href;
    } else if (wrap.classList.contains('trackItem__actions')) { /* SET */
      var trackItem = soundActions.parentElement.parentElement.parentElement;
      url = trackItem.querySelector('a.trackItem__trackTitle').href;
    } else {
      console.warn('add-to-sonos: cannot find container for soundActions:', soundActions);
      return;
    }
  } catch(e) {
    console.warn('add-to-sonos: cannot get url for soundActions:', soundActions, e);
    return;
  }

  if (soundActions.querySelector('.sc-button-addtoset') !== null) {
    addButtonToSound(soundActions, url);
  } else {
    addButtonToPlaylist(soundActions, url);
  }
}

function addButtonToPlaylist(soundActions, url) {
  var repostButton = soundActions.querySelector('.sc-button-repost');
  if (typeof repostButton === 'undefined' || repostButton === null) {
    console.warn('repost playlist button not found', soundActions);
    return;
  }

  var addToSonosButton = createButton(repostButton, url);
  repostButton.parentElement.insertBefore(addToSonosButton, repostButton.nextSibling);
}

function addButtonToSound(soundActions, url) {
  var addToSetButton = soundActions.querySelector('.sc-button-addtoset');
  addToSetButton.classList.add('ats-collapse');

  var addToSonosButton = createButton(addToSetButton, url);
  addToSetButton.parentElement.insertBefore(addToSonosButton, addToSetButton.nextSibling);
}

function createButton(prevButton, url) {
  var prevClasses = prevButton.className.replace(/sc-button-(addtoset|repost)/g, '');
  var addToSonosButton = document.createElement('button');
  addToSonosButton.className = prevClasses + ' ats-button ats-collapse';
  addToSonosButton.tabIndex = 0;
  addToSonosButton.title = 'Add to Sonos';
  addToSonosButton.innerHTML = 'Add to Sonos';

  addToSonosButton.addEventListener('click', function(ev) {
    ev.preventDefault();
    ev.stopPropagation();

    addToSonosButton.classList.remove('ats-success');
    addToSonosButton.classList.remove('ats-failure');
    addToSonosButton.classList.add('ats-loading');

    chrome.runtime.sendMessage({action: 'addToPlaylist', url: url}, function(response) {
      addToSonosButton.classList.remove('ats-loading');
      if (response.success) {
        addToSonosButton.classList.add('ats-success');
      } else {
        addToSonosButton.classList.add('ats-failure');
        if (response.setup) {
          chrome.runtime.sendMessage({action: 'openSettings'});
        }
      }
    });
  }, false);

  return addToSonosButton;
}

function handleSoundActionsChanges(summaries) {
  var soundActionsSummary = summaries[0];
  soundActionsSummary.added.forEach(addButton);
}

// triggers on new soundActions
var observer = new MutationSummary({
  callback: handleSoundActionsChanges,
  queries: [{ element: 'div.soundActions' }]
});

// handle already existing soundActions
[].forEach.call(document.querySelectorAll('div.soundActions'), addButton);<|endoftext|>


<commit_before>/**
* Copyright (c) Microsoft.  All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/*
* You can test powerbi embedded commands get loaded by xplat by following steps:
* a. Copy the folder to '<repository root>\lib\commands\arm'
* b. Under <repository root>, run 'node bin/azure config mode arm'
* c. Run 'node bin/azure', you should see 'powerbi' listed as a command set
* d. Run 'node bin/azure powerbi', you should see 'create', "delete", etc
      showing up in the help text
*/

'use strict';

var util = require('util');

var profile = require('../../../util/profile');
var tagUtils = require('../tag/tagUtils');
var utils = require('../../../util/utils');

var $ = utils.getLocaleString;

exports.init = function (cli) {
  var log = cli.output;

  var powerbiembeddedcli = cli.category('powerbi')
    .description($('Commands to manage your Azure Power BI Embedded Workspace Collections'));

  /**
   * Create new workspace collection
   */
  powerbiembeddedcli.command('create <resourceGroup> <name> <location> [tags]')
    .description($('Create a new workspace collection'))
    .option('-g --resource-group <resourceGroup>', $('Name of the resource group'))
    .option('-n --name <name>', $('The name of the new workspace collection'))
    .option('-l --location <location>', $('The location (azure region/datacenter) where the workspace collection will be provisioned'))
    .option('-t --tags [tags]', $('Tags to set to the resource group. Can be multiple. ' +
        'In the format of \'name=value\'. Name is required and value is optional. ' +
        'For example, -t \'tag1=value1;tag2\'. Providing an empty string \'\' will delete the tags.'))
    .option('-s --subscription [subscription]', $('The subscription identifier'))
    .execute(function (resourceGroup, name, location, tags, options, _) {
      /** Normalize options */
      options.location = options.location || location;
      options.tags = options.tags || tags;

      /** Validate parameters */
      if (!resourceGroup) {
        return cli.missingArgument('resourceGroup');
      }
      if (!name) {
        return cli.missingArgument('name');
      }

      /** Create client */
      var subscription = profile.current.getSubscription(options.subscription);
      var client = utils.createPowerbiManagementClient(subscription);

      /** Invoke client method */
      var tagsObject = {}
      if(options.tags) {
        tagsObject = tagUtils.buildTagsParameter(null, options);
      }

      var workspaceCollectionCreationOptions = {
        location: options.location,
        tags: tagsObject,
        sku: {
          name: "S1",
          tier: "Standard"
        }
      };

      var progress = cli.interaction.progress(util.format($('Creating workspace collection: %s'), name));
      var workspaceCollection;
      try {
        workspaceCollection = client.workspaceCollections.create(resourceGroup, name, workspaceCollectionCreationOptions, _);
      }
      catch (e) {
        if(e.statusCode === 409) {
          log.error('Error occurred while attempting to creat workspace collection.\n'
          + 'The name: ' + name + ' is already in use.\n'
          + 'Please use a different name.');
          return;
        }

        throw e;
      }
      finally {
        progress.end();
      }

      log.info('WorkspaceCollection created:');
      cli.interaction.formatOutput(workspaceCollection, function (workspaceCollection) {
        var workspaceCollectionProperties = [
          { key: 'name', value: workspaceCollection.name },
          { key: 'location', value: workspaceCollection.location },
          // TODO: The api doesn't seem to be returning sku information, expose when it's fixed.
          // { key: 'sku', value: workspaceCollection.sku.name },
          // { key: 'tier', value: workspaceCollection.sku.tier },
          { key: 'tags', value: tagUtils.getTagsInfo(workspaceCollection.tags) }
        ];

        log.table(workspaceCollectionProperties, function (row, workspaceCollectionProperty) {
          row.cell($('Property'), workspaceCollectionProperty.key);
          row.cell($('Value'), workspaceCollectionProperty.value);
        });
      });
    });

  /**
   * Update existing workspace collection
   */
  // TODO: Uncomment when bugs in service are fixed and SDK is updated with support.
  // powerbiembeddedcli.command('set <resourceGroup> <name> <tags>')
  //   .description($('Update a workspace collection\'s tags'))
  //   .option('-g --resource-group <resourceGroup>', $('Name of the resource group'))
  //   .option('-n --name <name>', $('Name of workspace collection'))
  //   .option('-t --tags <tags>', $('Tags to set to the resource group. Can be multiple. ' +
  //       'In the format of \'name=value\'. Name is required and value is optional. ' +
  //       'For example, -t \'tag1=value1;tag2\'. Providing an empty string \'\' will delete the tags.'))
  //   .option('-s --subscription [subscription]', $('The subscription identifier'))
  //   .execute(function (resourceGroup, name, tags, options, _) {

  //     /** Validate parameters */
  //     if (!resourceGroup) {
  //       return cli.missingArgument('resourceGroup');
  //     }
  //     if (!name) {
  //       return cli.missingArgument('name');
  //     }
  //     if (!tags) {
  //       return cli.missingArgument('tags');
  //     }

  //    var tagsObject = {}
  //    if(options.tags) {
  //      tagsObject = tagUtils.buildTagsParameter(null, options);
  //    }

  //     /** Create client */
  //     var subscription = profile.current.updateSubscription(options.subscription);
  //     var client = utils.createPowerbiManagementClient(subscription);

  //     /** Invoke client method */
  //     var body = {
  //       tags: tagsObject,
  //       sku: {
  //         name: "S1"
  //       }
  //     };

  //     var progress = cli.interaction.progress(util.format($('Udating workspace collection: %s'), name));
  //     var workspaceCollection;
  //     try {
  //       workspaceCollection = client.workspaceCollections.update(resourceGroup, name, body, _);
  //     } finally {
  //       progress.end();
  //     }

  //     /** Display output */
  //     log.info('WorkspaceCollection updated!');
  //   });

  /**
   * Delete existing workspace collection
   */
  // TODO: Uncomment when bugs in service are fixed and SDK is updated with support.
  // powerbiembeddedcli.command('delete [resourceGroup] [name]')
  //   .description($('Delete existing workspace collection'))
  //   .option('-g --resource-group <resourceGroup>', $('Name of the resource group'))
  //   .option('-n --name <name>', $('Name of workspace collection'))
  //   .option('-s --subscription [subscription]', $('The subscription identifier'))
  //   .execute(function (resourceGroup, name, options, _) {
  //     /** Validate parameters */
  //     if (!resourceGroup) {
  //       return cli.missingArgument('resourceGroup');
  //     }
  //     if (!name) {
  //       return cli.missingArgument('name');
  //     }

  //     /** Create client */
  //     var subscription = profile.current.getSubscription(options.subscription);
  //     var client = utils.createPowerbiManagementClient(subscription);

  //     /** Invoke client method */
  //     var progress = cli.interaction.progress(util.format($('Deleting workspace collection %s'), name));

  //     var result;
  //     try {
  //       result = client.workspaceCollections.delete(resourceGroup, name, _);
  //     } finally {
  //       progress.end();
  //     }

  //     log.info('Workspace Collection: ' + name + ' was deleted.');
  //   });

  /**
   * List by Subscription or by Resource Group
   */
  powerbiembeddedcli.command('list [resourceGroup]')
    .description($('List workspace collections within subscription or within resource group'))
    .option('-g --resource-group [resourceGroup]', $('Name of the resource group'))
    .option('-s --subscription [subscription]', $('The subscription identifier'))
    .execute(function (resourceGroup, options, _) {
      /** Normalize Options */
      options.resourceGroup = options.resourceGroup || resourceGroup;

      /** Create client */
      var subscription = profile.current.getSubscription(options.subscription);
      var client = utils.createPowerbiManagementClient(subscription);

      /** Invoke client method */
      var workspaceCollections;

      if(options.resourceGroup) {
        var progress = cli.interaction.progress($('Getting workspace collections in subscription ' + subscription.id + ' and within resource group: ' + options.resourceGroup));
        try {
          workspaceCollections = client.workspaceCollections.listByResourceGroup(options.resourceGroup, _);
        } finally {
          progress.end();
        }
      }
      else {
        var progress = cli.interaction.progress($('Getting workspace collections in subscription: ' + subscription.id));
        try {
          workspaceCollections = client.workspaceCollections.listBySubscription(_);
        } finally {
          progress.end();
        }
      }

      /** Output result */
      cli.interaction.formatOutput(workspaceCollections, function (workspaceCollections) {
        if (workspaceCollections.length === 0) {
          log.info($('No workspace collections found.'));
          return;
        }

        log.table(workspaceCollections, function (row, workspaceCollection) {
          var resourceGroup = null;
          var resourceGroupMatches = workspaceCollection.id.match(/resourceGroups\/([^\/]+)/);
          if(resourceGroupMatches) {
            resourceGroup = resourceGroupMatches[1];
          }

          row.cell($('Name'), workspaceCollection.name);
          row.cell($('Group'), resourceGroup);
          row.cell($('Location'), workspaceCollection.location);
          row.cell($('Provisioning State'), workspaceCollection.properties.provisioningState);
          row.cell($('Tags'), tagUtils.getTagsInfo(workspaceCollection.tags));
        });
      });
    });

  /**
   * Get access keys for workspace collection
   */
  powerbiembeddedcli.command('get-keys <resourceGroup> <name>')
    .description($('Get access keys for a workspace collection'))
    .option('-g --resource-group <resourceGroup>', $('Name of the resource group'))
    .option('-n --name <name>', $('Name of workspace collection'))
    .option('-s --subscription [subscription]', $('The subscription identifier'))
    .execute(function (resourceGroup, name, options, _) {
      /** Validate parameters */
      if (!resourceGroup) {
        return cli.missingArgument('resourceGroup');
      }
      if (!name) {
        return cli.missingArgument('name');
      }

      /** Create client */
      var subscription = profile.current.getSubscription(options.subscription);
      var client = utils.createPowerbiManagementClient(subscription);

      /** Invoke client method */
      var progress = cli.interaction.progress($('Getting workspace collection access keys...'));
      var accessKeys;
      try {
        accessKeys = client.workspaceCollections.getAccessKeys(resourceGroup, name, _);
      } finally {
        progress.end();
      }

      /** Output result */
      cli.interaction.formatOutput(accessKeys, function (accessKeys) {
        var keys = [
          { name: 'key1 (Primary)', key: accessKeys.key1 },
          { name: 'key2 (Secondary)', key: accessKeys.key2 }
        ];

        log.table(keys, function (row, key) {
          row.cell($('Name'), key.name);
          row.cell($('Key'), key.key);
        });
      });
    });

  /**
   * Regenerage access key
   */
  powerbiembeddedcli.command('regenerate-key <resourceGroup> <name> <keyName>')
    .description($('Get access keys for a workspace collection'))
    .option('-g --resource-group <resourceGroup>', $('Name of the resource group'))
    .option('-n --name <name>', $('Name of workspace collection'))
    .option('-k --keyName <keyName>', $('Name of key you would like to regenerate. Accepted values: "key1" (Primary) or "key2" (Secondary)'))
    .option('-s --subscription [subscription]', $('The subscription identifier'))
    .execute(function (resourceGroup, name, keyName, options, _) {
      /** Validate parameters */
      if (!resourceGroup) {
        return cli.missingArgument('resourceGroup');
      }
      if (!name) {
        return cli.missingArgument('name');
      }
      if (!keyName) {
        return cli.missingArgument('keyName');
      }
      if (!/^key(1|2)$/.test(keyName)) {
        return log.error('keyName must be either: "key1" or "key2". You passed: ' + keyName);
      }

      /** Create client */
      var subscription = profile.current.getSubscription(options.subscription);
      var client = utils.createPowerbiManagementClient(subscription);

      /** Invoke client method */
      var progress = cli.interaction.progress($('Regenerate workspace collection access key: ' + keyName));
      var accessKeys;

      var body = {
        keyName: keyName
      };
      try {
        accessKeys = client.workspaceCollections.regenerateKey(resourceGroup, name, body, _);
      } finally {
        progress.end();
      }

      /** Output result */
      var key1name = 'key1 (Primary)';
      if(keyName === 'key1') {
        key1name += ' (Regenerated)';
      }

      var key2name = 'key2 (Secondary)';
      if(keyName === 'key2') {
        key2name += ' (Regenerated)';
      }

      cli.interaction.formatOutput(accessKeys, function (accessKeys) {
        var keys = [
          { name: key1name, key: accessKeys.key1 },
          { name: key2name, key: accessKeys.key2 }
        ];

        log.table(keys, function (row, key) {
          row.cell($('Name'), key.name);
          row.cell($('Key'), key.key);
        });
      });
    });

  /**
   * List workspaces within workspace collection
   */
  powerbiembeddedcli.command('list-workspaces <resourceGroup> <name>')
    .description($('Get workspaces within given workspace collection'))
    .option('-g --resource-group <resourceGroup>', $('Name of the resource group'))
    .option('-n --name <name>', $('Name of workspace collection'))
    .option('-s --subscription [subscription]', $('The subscription identifier'))
    .execute(function (resourceGroup, name, options, _) {
      /** Validate parameters */
      if (!resourceGroup) {
        return cli.missingArgument('resourceGroup');
      }
      if (!name) {
        return cli.missingArgument('name');
      }

      /** Create client */
      var subscription = profile.current.getSubscription(options.subscription);
      var client = utils.createPowerbiManagementClient(subscription);

      /** Invoke client method */
      var progress = cli.interaction.progress($('Fetching workspaces...'));
      var workspaces;

      try {
        workspaces = client.workspaces.list(resourceGroup, name, _);
      } finally {
        progress.end();
      }

      /** Output result */
      cli.interaction.formatOutput(workspaces, function (workspaces) {
        if (workspaces.length === 0) {
          log.info($('No workspaces found.'));
          return;
        }

        log.table(workspaces, function (row, workspace) {
          row.cell($('Name'), workspace.name);
        });
      });
    });
};
<commit_msg>Fix lint errors.<commit_after>/**
* Copyright (c) Microsoft.  All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/*
* You can test powerbi embedded commands get loaded by xplat by following steps:
* a. Copy the folder to '<repository root>\lib\commands\arm'
* b. Under <repository root>, run 'node bin/azure config mode arm'
* c. Run 'node bin/azure', you should see 'powerbi' listed as a command set
* d. Run 'node bin/azure powerbi', you should see 'create', "delete", etc
      showing up in the help text
*/

'use strict';

var util = require('util');

var profile = require('../../../util/profile');
var tagUtils = require('../tag/tagUtils');
var utils = require('../../../util/utils');

var $ = utils.getLocaleString;

exports.init = function (cli) {
  var log = cli.output;

  var powerbiembeddedcli = cli.category('powerbi')
    .description($('Commands to manage your Azure Power BI Embedded Workspace Collections'));

  /**
   * Create new workspace collection
   */
  powerbiembeddedcli.command('create <resourceGroup> <name> <location> [tags]')
    .description($('Create a new workspace collection'))
    .option('-g --resource-group <resourceGroup>', $('Name of the resource group'))
    .option('-n --name <name>', $('The name of the new workspace collection'))
    .option('-l --location <location>', $('The location (azure region/datacenter) where the workspace collection will be provisioned'))
    .option('-t --tags [tags]', $('Tags to set to the resource group. Can be multiple. ' +
        'In the format of \'name=value\'. Name is required and value is optional. ' +
        'For example, -t \'tag1=value1;tag2\'. Providing an empty string \'\' will delete the tags.'))
    .option('-s --subscription [subscription]', $('The subscription identifier'))
    .execute(function (resourceGroup, name, location, tags, options, _) {
      /** Normalize options */
      options.location = options.location || location;
      options.tags = options.tags || tags;

      /** Validate parameters */
      if (!resourceGroup) {
        return cli.missingArgument('resourceGroup');
      }
      if (!name) {
        return cli.missingArgument('name');
      }

      /** Create client */
      var subscription = profile.current.getSubscription(options.subscription);
      var client = utils.createPowerbiManagementClient(subscription);

      /** Invoke client method */
      var tagsObject = {};
      if(options.tags) {
        tagsObject = tagUtils.buildTagsParameter(null, options);
      }

      var workspaceCollectionCreationOptions = {
        location: options.location,
        tags: tagsObject,
        sku: {
          name: 'S1',
          tier: 'Standard'
        }
      };

      var progress = cli.interaction.progress(util.format($('Creating workspace collection: %s'), name));
      var workspaceCollection;
      try {
        workspaceCollection = client.workspaceCollections.create(resourceGroup, name, workspaceCollectionCreationOptions, _);
      }
      catch (e) {
        if(e.statusCode === 409) {
          log.error('Error occurred while attempting to creat workspace collection.\n' +
          'The name: ' + name + ' is already in use.\n' +
          'Please use a different name.');
          return;
        }

        throw e;
      }
      finally {
        progress.end();
      }

      log.info('WorkspaceCollection created:');
      cli.interaction.formatOutput(workspaceCollection, function (workspaceCollection) {
        var workspaceCollectionProperties = [
          { key: 'name', value: workspaceCollection.name },
          { key: 'location', value: workspaceCollection.location },
          // TODO: The api doesn't seem to be returning sku information, expose when it's fixed.
          // { key: 'sku', value: workspaceCollection.sku.name },
          // { key: 'tier', value: workspaceCollection.sku.tier },
          { key: 'tags', value: tagUtils.getTagsInfo(workspaceCollection.tags) }
        ];

        log.table(workspaceCollectionProperties, function (row, workspaceCollectionProperty) {
          row.cell($('Property'), workspaceCollectionProperty.key);
          row.cell($('Value'), workspaceCollectionProperty.value);
        });
      });
    });

  /**
   * Update existing workspace collection
   */
  // TODO: Uncomment when bugs in service are fixed and SDK is updated with support.
  // powerbiembeddedcli.command('set <resourceGroup> <name> <tags>')
  //   .description($('Update a workspace collection\'s tags'))
  //   .option('-g --resource-group <resourceGroup>', $('Name of the resource group'))
  //   .option('-n --name <name>', $('Name of workspace collection'))
  //   .option('-t --tags <tags>', $('Tags to set to the resource group. Can be multiple. ' +
  //       'In the format of \'name=value\'. Name is required and value is optional. ' +
  //       'For example, -t \'tag1=value1;tag2\'. Providing an empty string \'\' will delete the tags.'))
  //   .option('-s --subscription [subscription]', $('The subscription identifier'))
  //   .execute(function (resourceGroup, name, tags, options, _) {

  //     /** Validate parameters */
  //     if (!resourceGroup) {
  //       return cli.missingArgument('resourceGroup');
  //     }
  //     if (!name) {
  //       return cli.missingArgument('name');
  //     }
  //     if (!tags) {
  //       return cli.missingArgument('tags');
  //     }

  //    var tagsObject = {}
  //    if(options.tags) {
  //      tagsObject = tagUtils.buildTagsParameter(null, options);
  //    }

  //     /** Create client */
  //     var subscription = profile.current.updateSubscription(options.subscription);
  //     var client = utils.createPowerbiManagementClient(subscription);

  //     /** Invoke client method */
  //     var body = {
  //       tags: tagsObject,
  //       sku: {
  //         name: "S1"
  //       }
  //     };

  //     var progress = cli.interaction.progress(util.format($('Udating workspace collection: %s'), name));
  //     var workspaceCollection;
  //     try {
  //       workspaceCollection = client.workspaceCollections.update(resourceGroup, name, body, _);
  //     } finally {
  //       progress.end();
  //     }

  //     /** Display output */
  //     log.info('WorkspaceCollection updated!');
  //   });

  /**
   * Delete existing workspace collection
   */
  // TODO: Uncomment when bugs in service are fixed and SDK is updated with support.
  // powerbiembeddedcli.command('delete [resourceGroup] [name]')
  //   .description($('Delete existing workspace collection'))
  //   .option('-g --resource-group <resourceGroup>', $('Name of the resource group'))
  //   .option('-n --name <name>', $('Name of workspace collection'))
  //   .option('-s --subscription [subscription]', $('The subscription identifier'))
  //   .execute(function (resourceGroup, name, options, _) {
  //     /** Validate parameters */
  //     if (!resourceGroup) {
  //       return cli.missingArgument('resourceGroup');
  //     }
  //     if (!name) {
  //       return cli.missingArgument('name');
  //     }

  //     /** Create client */
  //     var subscription = profile.current.getSubscription(options.subscription);
  //     var client = utils.createPowerbiManagementClient(subscription);

  //     /** Invoke client method */
  //     var progress = cli.interaction.progress(util.format($('Deleting workspace collection %s'), name));

  //     var result;
  //     try {
  //       result = client.workspaceCollections.delete(resourceGroup, name, _);
  //     } finally {
  //       progress.end();
  //     }

  //     log.info('Workspace Collection: ' + name + ' was deleted.');
  //   });

  /**
   * List by Subscription or by Resource Group
   */
  powerbiembeddedcli.command('list [resourceGroup]')
    .description($('List workspace collections within subscription or within resource group'))
    .option('-g --resource-group [resourceGroup]', $('Name of the resource group'))
    .option('-s --subscription [subscription]', $('The subscription identifier'))
    .execute(function (resourceGroup, options, _) {
      /** Normalize Options */
      options.resourceGroup = options.resourceGroup || resourceGroup;

      /** Create client */
      var subscription = profile.current.getSubscription(options.subscription);
      var client = utils.createPowerbiManagementClient(subscription);

      /** Invoke client method */
      var workspaceCollections;
      var progress;
      if(options.resourceGroup) {
        progress = cli.interaction.progress($('Getting workspace collections in subscription ' + subscription.id + ' and within resource group: ' + options.resourceGroup));
        try {
          workspaceCollections = client.workspaceCollections.listByResourceGroup(options.resourceGroup, _);
        } finally {
          progress.end();
        }
      }
      else {
        progress = cli.interaction.progress($('Getting workspace collections in subscription: ' + subscription.id));
        try {
          workspaceCollections = client.workspaceCollections.listBySubscription(_);
        } finally {
          progress.end();
        }
      }

      /** Output result */
      cli.interaction.formatOutput(workspaceCollections, function (workspaceCollections) {
        if (workspaceCollections.length === 0) {
          log.info($('No workspace collections found.'));
          return;
        }

        log.table(workspaceCollections, function (row, workspaceCollection) {
          var resourceGroup = null;
          var resourceGroupMatches = workspaceCollection.id.match(/resourceGroups\/([^\/]+)/);
          if(resourceGroupMatches) {
            resourceGroup = resourceGroupMatches[1];
          }

          row.cell($('Name'), workspaceCollection.name);
          row.cell($('Group'), resourceGroup);
          row.cell($('Location'), workspaceCollection.location);
          row.cell($('Provisioning State'), workspaceCollection.properties.provisioningState);
          row.cell($('Tags'), tagUtils.getTagsInfo(workspaceCollection.tags));
        });
      });
    });

  /**
   * Get access keys for workspace collection
   */
  powerbiembeddedcli.command('get-keys <resourceGroup> <name>')
    .description($('Get access keys for a workspace collection'))
    .option('-g --resource-group <resourceGroup>', $('Name of the resource group'))
    .option('-n --name <name>', $('Name of workspace collection'))
    .option('-s --subscription [subscription]', $('The subscription identifier'))
    .execute(function (resourceGroup, name, options, _) {
      /** Validate parameters */
      if (!resourceGroup) {
        return cli.missingArgument('resourceGroup');
      }
      if (!name) {
        return cli.missingArgument('name');
      }

      /** Create client */
      var subscription = profile.current.getSubscription(options.subscription);
      var client = utils.createPowerbiManagementClient(subscription);

      /** Invoke client method */
      var progress = cli.interaction.progress($('Getting workspace collection access keys...'));
      var accessKeys;
      try {
        accessKeys = client.workspaceCollections.getAccessKeys(resourceGroup, name, _);
      } finally {
        progress.end();
      }

      /** Output result */
      cli.interaction.formatOutput(accessKeys, function (accessKeys) {
        var keys = [
          { name: 'key1 (Primary)', key: accessKeys.key1 },
          { name: 'key2 (Secondary)', key: accessKeys.key2 }
        ];

        log.table(keys, function (row, key) {
          row.cell($('Name'), key.name);
          row.cell($('Key'), key.key);
        });
      });
    });

  /**
   * Regenerage access key
   */
  powerbiembeddedcli.command('regenerate-key <resourceGroup> <name> <keyName>')
    .description($('Get access keys for a workspace collection'))
    .option('-g --resource-group <resourceGroup>', $('Name of the resource group'))
    .option('-n --name <name>', $('Name of workspace collection'))
    .option('-k --keyName <keyName>', $('Name of key you would like to regenerate. Accepted values: "key1" (Primary) or "key2" (Secondary)'))
    .option('-s --subscription [subscription]', $('The subscription identifier'))
    .execute(function (resourceGroup, name, keyName, options, _) {
      /** Validate parameters */
      if (!resourceGroup) {
        return cli.missingArgument('resourceGroup');
      }
      if (!name) {
        return cli.missingArgument('name');
      }
      if (!keyName) {
        return cli.missingArgument('keyName');
      }
      if (!/^key(1|2)$/.test(keyName)) {
        return log.error('keyName must be either: "key1" or "key2". You passed: ' + keyName);
      }

      /** Create client */
      var subscription = profile.current.getSubscription(options.subscription);
      var client = utils.createPowerbiManagementClient(subscription);

      /** Invoke client method */
      var progress = cli.interaction.progress($('Regenerate workspace collection access key: ' + keyName));
      var accessKeys;

      var body = {
        keyName: keyName
      };
      try {
        accessKeys = client.workspaceCollections.regenerateKey(resourceGroup, name, body, _);
      } finally {
        progress.end();
      }

      /** Output result */
      var key1name = 'key1 (Primary)';
      if(keyName === 'key1') {
        key1name += ' (Regenerated)';
      }

      var key2name = 'key2 (Secondary)';
      if(keyName === 'key2') {
        key2name += ' (Regenerated)';
      }

      cli.interaction.formatOutput(accessKeys, function (accessKeys) {
        var keys = [
          { name: key1name, key: accessKeys.key1 },
          { name: key2name, key: accessKeys.key2 }
        ];

        log.table(keys, function (row, key) {
          row.cell($('Name'), key.name);
          row.cell($('Key'), key.key);
        });
      });
    });

  /**
   * List workspaces within workspace collection
   */
  powerbiembeddedcli.command('list-workspaces <resourceGroup> <name>')
    .description($('Get workspaces within given workspace collection'))
    .option('-g --resource-group <resourceGroup>', $('Name of the resource group'))
    .option('-n --name <name>', $('Name of workspace collection'))
    .option('-s --subscription [subscription]', $('The subscription identifier'))
    .execute(function (resourceGroup, name, options, _) {
      /** Validate parameters */
      if (!resourceGroup) {
        return cli.missingArgument('resourceGroup');
      }
      if (!name) {
        return cli.missingArgument('name');
      }

      /** Create client */
      var subscription = profile.current.getSubscription(options.subscription);
      var client = utils.createPowerbiManagementClient(subscription);

      /** Invoke client method */
      var progress = cli.interaction.progress($('Fetching workspaces...'));
      var workspaces;

      try {
        workspaces = client.workspaces.list(resourceGroup, name, _);
      } finally {
        progress.end();
      }

      /** Output result */
      cli.interaction.formatOutput(workspaces, function (workspaces) {
        if (workspaces.length === 0) {
          log.info($('No workspaces found.'));
          return;
        }

        log.table(workspaces, function (row, workspace) {
          row.cell($('Name'), workspace.name);
        });
      });
    });
};
<|endoftext|>


<commit_before>var mongoose = require('mongoose'),
    models = require('../models/all.js');

module.exports = {
    put: function(req,res){
        var collection = models.entry,
            document = req.body.entry,
            query = { date: document.date },
            opts = { upsert: true },
            done = function(err){
                res.end();
            };

        collection.findOneAndUpdate(query, document, opts, done);
		collection.save();
    }
};<commit_msg>save is not required<commit_after>var mongoose = require('mongoose'),
    models = require('../models/all.js');

module.exports = {
    put: function(req,res){
        var collection = models.entry,
            document = req.body.entry,
            query = { date: document.date },
            opts = { upsert: true },
            done = function(err){
                res.end();
            };

        collection.findOneAndUpdate(query, document, opts, done);
    }
};<|endoftext|>


<commit_before>frappe.ui.form.on("Hub Settings", {
	refresh: function(frm) {
		frm.add_custom_button(__('Logs'),
			() => frappe.set_route('List', 'Data Migration Run', {
				data_migration_plan: 'Hub Sync'
			}));

		frm.trigger("enabled");
		if (frm.doc.enabled) {
			frm.add_custom_button(__('View Hub'),
				() => frappe.set_route('Hub', 'Item'));
			frm.add_custom_button(__('Sync'),
				() => frm.call('sync'));
		}
	},
	onload: function(frm) {
		let token = frappe.urllib.get_arg("access_token");
		if(token) {
			let email = frm.get_field("user");
			console.log('token', frappe.urllib.get_arg("access_token"));

			get_user_details(frm, token, email);
			let row = frappe.model.add_child(frm.doc, "Hub Users", "users");
			row.user = frappe.session.user;
		}

		if(!frm.doc.country) {
			frm.set_value("country", frappe.defaults.get_default("Country"));
		}
		if(!frm.doc.company) {
			frm.set_value("company", frappe.defaults.get_default("Company"));
		}
		if(!frm.doc.user) {
			frm.set_value("user", frappe.session.user);
		}
	},
	onload_post_render: function(frm) {
		if(frm.get_field("unregister_from_hub").$input)
			frm.get_field("unregister_from_hub").$input.addClass("btn-danger");
	},
	on_update: function(frm) {
	},
	enabled: function(frm) {
		if(!frm.doc.enabled) {
			frm.trigger("set_enable_hub_primary_button");
		} else {
			frm.page.set_primary_action(__("Save Settings"), () => {
				frm.save();
			});
		}
	},

	hub_user_email: function(frm) {
		if(frm.doc.hub_user_email){
			frm.set_value("hub_user_name", frappe.user.full_name(frm.doc.hub_user_email));
		}
	},

	set_enable_hub_primary_button: (frm) => {
		frm.page.set_primary_action(__("Enable Hub"), () => {
			if(frappe.session.user === "Administrator") {
				frappe.msgprint(__("Please login as another user."))
			} else {
				// frappe.verify_password(() => {

				// } );

				frm.trigger("call_pre_reg");
				// frm.trigger("call_register");

			}
		});
	},

	call_pre_reg: (frm) => {
		this.frm.call({
			doc: this.frm.doc,
			method: "pre_reg",
			args: {},
			freeze: true,
			callback: function(r) {
				console.log(r.message);
				authorize(frm, r.message.client_id, r.message.redirect_uri);
			},
			onerror: function() {
				frappe.msgprint(__("Wrong Password"));
				frm.set_value("enabled", 0);
			}
		});
	},

	call_register: (frm) => {
		this.frm.call({
			doc: this.frm.doc,
			method: "register",
			args: {},
			freeze: true,
			callback: function(r) {},
			onerror: function() {
				frappe.msgprint(__("Wrong Password"));
				frm.set_value("enabled", 0);
			}
		});
	},

	unregister_from_hub: (frm) => {
		frappe.verify_password(() => {
			var d = frappe.confirm(__('Are you sure you want to unregister?'), () => {
				frm.call('unregister');
			}, () => {}, __('Confirm Action'));
			d.get_primary_btn().addClass("btn-danger");
		});
	},
});

// let hub_url = 'https://hubmarket.org'
let hub_url = 'http://159.89.175.122'
// let hub_url = 'http://erpnext.hub:8000'

function authorize(frm, client_id, redirect_uri) {

    // queryStringData is details of OAuth Client (Implicit Grant) on Custom App
	var queryStringData = {
		response_type : "token",
		client_id : client_id,
        redirect_uri : redirect_uri
	}

    // Get current raw route and build url
    const route = "/desk#" + frappe.get_raw_route_str();
    localStorage.removeItem("route");  // Clear previously set route if any
	localStorage.setItem("route", route);

	// Go authorize!
	let api_route = "/api/method/frappe.integrations.oauth2.authorize?";
	let url = hub_url + api_route + $.param(queryStringData);
	window.location.replace(url, 'test');
}

function get_user_details(frm, token, email) {
	console.log('user_details');
    var route = localStorage.getItem("route");
    if (token && route) {
        // Clean up access token from route
		frappe.set_route(frappe.get_route().join("/"))

        // query protected resource e.g. Hub Items with token
        var call = {
            "async": true,
            "crossDomain": true,
            "url": hub_url + "/api/resource/User",
			"method": "GET",
			"data": {
				// "email": email,
				"fields": '["name", "first_name", "language"]',
				"limit_page_length": 1
			},
            "headers": {
                "authorization": "Bearer " + token,
                "content-type": "application/x-www-form-urlencoded"
            }
		}
        $.ajax(call).done(function (response) {
			// display openid profile
			console.log('response', response);

			let data = response.data[0];
			frm.set_value("enabled", 1);
			frm.set_value("hub_username", data.first_name);
			frm.set_value("hub_user_status", "Starter");
			frm.set_value("language", data.language);
			frm.save();

            // clear route from localStorage
            localStorage.removeItem("route");
        });
    }
}
<commit_msg>[hub] add hub settings access regardless<commit_after>frappe.ui.form.on("Hub Settings", {
	refresh: function(frm) {
		frm.add_custom_button(__('Logs'),
			() => frappe.set_route('List', 'Data Migration Run', {
				data_migration_plan: 'Hub Sync'
			}));

		frm.trigger("enabled");
		frm.add_custom_button(__('View Hub'),
			() => frappe.set_route('Hub', 'Item'));
		if (frm.doc.enabled) {
			frm.add_custom_button(__('Sync'),
				() => frm.call('sync'));
		}
	},
	onload: function(frm) {
		let token = frappe.urllib.get_arg("access_token");
		if(token) {
			let email = frm.get_field("user");
			console.log('token', frappe.urllib.get_arg("access_token"));

			get_user_details(frm, token, email);
			let row = frappe.model.add_child(frm.doc, "Hub Users", "users");
			row.user = frappe.session.user;
		}

		if(!frm.doc.country) {
			frm.set_value("country", frappe.defaults.get_default("Country"));
		}
		if(!frm.doc.company) {
			frm.set_value("company", frappe.defaults.get_default("Company"));
		}
		if(!frm.doc.user) {
			frm.set_value("user", frappe.session.user);
		}
	},
	onload_post_render: function(frm) {
		if(frm.get_field("unregister_from_hub").$input)
			frm.get_field("unregister_from_hub").$input.addClass("btn-danger");
	},
	on_update: function(frm) {
	},
	enabled: function(frm) {
		if(!frm.doc.enabled) {
			frm.trigger("set_enable_hub_primary_button");
		} else {
			frm.page.set_primary_action(__("Save Settings"), () => {
				frm.save();
			});
		}
	},

	hub_user_email: function(frm) {
		if(frm.doc.hub_user_email){
			frm.set_value("hub_user_name", frappe.user.full_name(frm.doc.hub_user_email));
		}
	},

	set_enable_hub_primary_button: (frm) => {
		frm.page.set_primary_action(__("Enable Hub"), () => {
			if(frappe.session.user === "Administrator") {
				frappe.msgprint(__("Please login as another user."))
			} else {
				// frappe.verify_password(() => {

				// } );

				frm.trigger("call_pre_reg");
				// frm.trigger("call_register");

			}
		});
	},

	call_pre_reg: (frm) => {
		this.frm.call({
			doc: this.frm.doc,
			method: "pre_reg",
			args: {},
			freeze: true,
			callback: function(r) {
				console.log(r.message);
				authorize(frm, r.message.client_id, r.message.redirect_uri);
			},
			onerror: function() {
				frappe.msgprint(__("Wrong Password"));
				frm.set_value("enabled", 0);
			}
		});
	},

	call_register: (frm) => {
		this.frm.call({
			doc: this.frm.doc,
			method: "register",
			args: {},
			freeze: true,
			callback: function(r) {},
			onerror: function() {
				frappe.msgprint(__("Wrong Password"));
				frm.set_value("enabled", 0);
			}
		});
	},

	unregister_from_hub: (frm) => {
		frappe.verify_password(() => {
			var d = frappe.confirm(__('Are you sure you want to unregister?'), () => {
				frm.call('unregister');
			}, () => {}, __('Confirm Action'));
			d.get_primary_btn().addClass("btn-danger");
		});
	},
});

// let hub_url = 'https://hubmarket.org'
let hub_url = 'http://159.89.175.122'
// let hub_url = 'http://erpnext.hub:8000'

function authorize(frm, client_id, redirect_uri) {

    // queryStringData is details of OAuth Client (Implicit Grant) on Custom App
	var queryStringData = {
		response_type : "token",
		client_id : client_id,
        redirect_uri : redirect_uri
	}

    // Get current raw route and build url
    const route = "/desk#" + frappe.get_raw_route_str();
    localStorage.removeItem("route");  // Clear previously set route if any
	localStorage.setItem("route", route);

	// Go authorize!
	let api_route = "/api/method/frappe.integrations.oauth2.authorize?";
	let url = hub_url + api_route + $.param(queryStringData);
	window.location.replace(url, 'test');
}

function get_user_details(frm, token, email) {
	console.log('user_details');
    var route = localStorage.getItem("route");
    if (token && route) {
        // Clean up access token from route
		frappe.set_route(frappe.get_route().join("/"))

        // query protected resource e.g. Hub Items with token
        var call = {
            "async": true,
            "crossDomain": true,
            "url": hub_url + "/api/resource/User",
			"method": "GET",
			"data": {
				// "email": email,
				"fields": '["name", "first_name", "language"]',
				"limit_page_length": 1
			},
            "headers": {
                "authorization": "Bearer " + token,
                "content-type": "application/x-www-form-urlencoded"
            }
		}
        $.ajax(call).done(function (response) {
			// display openid profile
			console.log('response', response);

			let data = response.data[0];
			frm.set_value("enabled", 1);
			frm.set_value("hub_username", data.first_name);
			frm.set_value("hub_user_status", "Starter");
			frm.set_value("language", data.language);
			frm.save();

            // clear route from localStorage
            localStorage.removeItem("route");
        });
    }
}
<|endoftext|>


<commit_before>var Event = require("mongoose").model("Event");
var Application = require("mongoose").model("Application");
var dateHelper = require("../../lib/date-helper.js");
var _ = require("lodash");

exports.getUpcomingEvents = function *() {

  var rawApplications = yield Application.find({
   'user':  this.passport.user._id
   }, {
     event: 1
   }).exec();

  // Map them in an array usable by mongo $nin
  var mappedApplications = rawApplications.map(function (a) {
    return a.event;
  });

  var events = yield Event.find({
    _id: { $nin: mappedApplications },
    startDate: { $gt:  dateHelper.getNextHourDate()},
    isClosed: false,
  }, '-isClosed').sort("startDate").exec();
  this.body = { events: events };
};

exports.create = function *() {
  if (!this.request.body) {
    this.throw("Le corps de la requête est vide", 400);
  }
  if (!this.request.body.event) {
    this.throw("Le corps doit contenir un événement", 400);
  }
  var event = new Event(this.request.body.event);

  yield event.save();
  this.body = { event: event };
};

exports.read = function *() {
  var event = yield Event.findById(this.params.id).exec();
  if (!event) {
    this.throw("L'événement n'existe pas", 404);
  }
  this.body = { event: event };
}

exports.readAll = function *() {
  var events = yield Event.find({}).sort("-startDate").exec();
  this.body = { events: events };
};

exports.update = function *() {
  if (!this.request.body) {
    this.throw("Le corps de la requête est vide", 400);
  }
  if (!this.request.body.event) {
    this.throw("Le corps doit contenir un événement", 400);
  }
  if (!this.params.id.match(/^[0-9a-fA-F]{24}$/)) {
    this.throw("L'événement n'existe pas", 404);
  }
  var event = yield Event.findById(this.params.id).exec();
  if (!event) {
    this.throw("L'événement n'existe pas", 404);
  }
  _.extend(event, this.request.body.event);
  yield event.save();
  this.body = { event: event };
};

exports.markPointsAttributed = function *() {
  if (!this.params.id.match(/^[0-9a-fA-F]{24}$/)) {
    this.throw("L'événement n'existe pas", 404);
  }
  var event = yield Event.findById(this.params.id).exec();
  if (!event) {
    this.throw("L'événement n'existe pas", 404);
  }
  event.isPointsAttributed = true;
  yield event.save();
  this.body = { event: event };
}
<commit_msg>better 404 in GET /evet<commit_after>var Event = require("mongoose").model("Event");
var Application = require("mongoose").model("Application");
var dateHelper = require("../../lib/date-helper.js");
var _ = require("lodash");

exports.getUpcomingEvents = function *() {

  var rawApplications = yield Application.find({
   'user':  this.passport.user._id
   }, {
     event: 1
   }).exec();

  // Map them in an array usable by mongo $nin
  var mappedApplications = rawApplications.map(function (a) {
    return a.event;
  });

  var events = yield Event.find({
    _id: { $nin: mappedApplications },
    startDate: { $gt:  dateHelper.getNextHourDate()},
    isClosed: false,
  }, '-isClosed').sort("startDate").exec();
  this.body = { events: events };
};

exports.create = function *() {
  if (!this.request.body) {
    this.throw("Le corps de la requête est vide", 400);
  }
  if (!this.request.body.event) {
    this.throw("Le corps doit contenir un événement", 400);
  }
  var event = new Event(this.request.body.event);

  yield event.save();
  this.body = { event: event };
};

exports.read = function *() {
  if (!this.params.id.match(/^[0-9a-fA-F]{24}$/)) {
    this.throw("L'événement n'existe pas", 404);
  }
  var event = yield Event.findById(this.params.id).exec();
  if (!event) {
    this.throw("L'événement n'existe pas", 404);
  }
  this.body = { event: event };
}

exports.readAll = function *() {
  var events = yield Event.find({}).sort("-startDate").exec();
  this.body = { events: events };
};

exports.update = function *() {
  if (!this.request.body) {
    this.throw("Le corps de la requête est vide", 400);
  }
  if (!this.request.body.event) {
    this.throw("Le corps doit contenir un événement", 400);
  }
  if (!this.params.id.match(/^[0-9a-fA-F]{24}$/)) {
    this.throw("L'événement n'existe pas", 404);
  }
  var event = yield Event.findById(this.params.id).exec();
  if (!event) {
    this.throw("L'événement n'existe pas", 404);
  }
  _.extend(event, this.request.body.event);
  yield event.save();
  this.body = { event: event };
};

exports.markPointsAttributed = function *() {
  if (!this.params.id.match(/^[0-9a-fA-F]{24}$/)) {
    this.throw("L'événement n'existe pas", 404);
  }
  var event = yield Event.findById(this.params.id).exec();
  if (!event) {
    this.throw("L'événement n'existe pas", 404);
  }
  event.isPointsAttributed = true;
  yield event.save();
  this.body = { event: event };
}
<|endoftext|>


<commit_before>/**
 * Convert structure to markdown format.
 */

'use strict';

/**
 * Structure to markdown
 * @param {URIDOM} uridom
 * @return {string}
 * @constructor
 */
module.exports = function (uridom) {
    let markdown = '\n---\n';

    markdown += `# ${uridom.method} ${uridom.uri}\n\n`;

    markdown += `${uridom.description.replace(/\n/gm, '\n\n')}\n\n`;

    /**
     * Make table.
     * @param {String} objectName
     * @param {Array} objectArray - Array of object which contain name, type and description.
     * @return {string}
     */
    function keyValueTable(objectName, objectArray) {
        let tableString = '';
        tableString += `### ${objectName} ⮷\n\n`;
        tableString += ''
            + 'Name | Description\n'
            + '---- | -----------\n';
        for (let line of objectArray) {
            tableString += `${line.key} | ${line.value}\n`;
        }
        tableString += '\n';
        return tableString;
    }

    function body2Markdown(body) {
        return '### BODY ⮷\n\n'
            + '```javascript\n'
            + body + '\n'
            + '```\n\n';
    }

    if (uridom.request) {
        markdown += '## REQUEST ⮚\n\n';
        if (uridom.request.headers) {
            markdown += keyValueTable('HEADERS', uridom.request.headers.table);
        }
        if (uridom.request.path) {
            markdown += keyValueTable('PATH', uridom.request.path.table);
        }
        if (uridom.request.query) {
            markdown += keyValueTable('QUERY', uridom.request.query.table);
        }
        if (uridom.request.body) {
            markdown += body2Markdown(uridom.request.body.bodyContent);
        }
    }
    if (uridom.response) {
        markdown += '## RESPONSE ⮘\n\n';
        if (uridom.response.headers) {
            markdown += keyValueTable('HEADERS', uridom.request.headers.table);
        }
        if (uridom.response.body) {
            markdown += body2Markdown(uridom.response.body.bodyContent)
        }
    }
    return markdown;
};
<commit_msg>Better markdown format<commit_after>/**
 * Convert structure to markdown format.
 */

'use strict';

/**
 * Structure to markdown
 * @param {URIDOM} uridom
 * @return {string}
 * @constructor
 */
module.exports = function (uridom) {
    let markdown = '\n---\n';

    markdown += `### ${uridom.method} ${uridom.uri}\n\n`;

    markdown += `${uridom.description.replace(/\n/gm, '\n\n')}\n\n`;

    /**
     * Make table.
     * @param {String} objectName
     * @param {Array} objectArray - Array of object which contain name, type and description.
     * @return {string}
     */
    function keyValueTable(objectName, objectArray) {
        let tableString = `
##### ${objectName}

Name | Description
---- | -----------
`;
        for (let line of objectArray) {
            tableString += `${line.key} | ${line.value}\n`;
        }
        tableString += '\n';
        return tableString;
    }

    function body2Markdown(body) {
        return `
##### Body

\`\`\`javascript
${body}
\`\`\`
`;
    }

    if (uridom.request) {
        markdown += '#### Request\n\n';
        if (uridom.request.headers) {
            markdown += keyValueTable('Headers', uridom.request.headers.table);
        }
        if (uridom.request.path) {
            markdown += keyValueTable('Path', uridom.request.path.table);
        }
        if (uridom.request.query) {
            markdown += keyValueTable('Query', uridom.request.query.table);
        }
        if (uridom.request.body) {
            markdown += body2Markdown(uridom.request.body.bodyContent);
        }
    }
    if (uridom.response) {
        markdown += '#### Response\n\n';
        if (uridom.response.headers) {
            markdown += keyValueTable('Headers', uridom.request.headers.table);
        }
        if (uridom.response.body) {
            markdown += body2Markdown(uridom.response.body.bodyContent);
        }
    }
    return markdown;
};
<|endoftext|>


<commit_before>(function ($, rho, rhoUtil) {
    'use strict';

    // === Rho.NewORM wrapper members ===
    Rho.NewORM.addModel = function(modelname, modeldef){
        var model = new Rho.NewORMModel(modelname);
        modeldef(model);
        model.initModel();
        return model;
    };
    Rho.NewORM.getModel = function(modelname){
        return Rho.NewORMModel.getModel(modelname);
    };

    // === Rho.NewORMModel wrapper members ===
    Rho.NewORMModel.prototype._normalize_complex_conditions = function(conditions, op){
        if(!conditions){
            return ['', []];
        };
        op = op || 'AND';
        if(conditions instanceof Array){
            var quests = [];
            var sqlRes = '';
            for (var item in conditions) {
                if (sqlRes.length > 0) {
                    sqlRes += ' ' + op + ' ';
                };
                if(item.hasOwnProperty('conditions')) {
                    var subCond = _normalize_complex_conditions(item.conditions, item.op);
                }
                else {
                    var subCond = _normalize_complex_condition(item);
                }
                sqlRes += '(' + subCond[0] + ')';
                quests = quests.concat(subCond[1]);
            }
            return [sqlRes, quests];
        }
        else {
            return _normalize_complex_condition(conditions);
        };
    };

    Rho.NewORMModel.prototype._normalize_complex_condition = function(item){
        var sqlRes = "";
        var condQuests = [];
        var itemOp = "=";
        var itemFunc = "";
        var itemName = "";
        var itemValues = "";
        for (var propName in item) {
            switch (propName) {
            case 'op'  :
                itemOp = item[propName];
                break;
            case 'func':
                itemFunc = item[propName];
                break;
            case 'name':
                itemName = item[propName];
                break;
            case 'value':
            case 'values':
                itemValues = item[propName];
            default:
                itemName = propName;
                itemValues = item[Values];
            };
        };
        if(itemValues instanceof String){
            itemValues = [itemValues];
        };

        subCond = buildComplexWhereCond(itemName, itemValues, itemOp, itemFunc);
        return [subCond[0], subCond.slice(1)];
    };

    Rho.NewORMModel.prototype._normalize_conditions = function(what, conditions, op){
        console.log("MZV_DEBUG : make_conditions : " + what + ", " + JSON.stringify(conditions) + ", " + op);
        if (!op) {
            var retV = [];
            if(!conditions) {
                retV = this.buildSimpleWhereCond(what, []);
            }
            else if(conditions instanceof String){
                retV = this.buildSimpleWhereCond(what, [conditions]);
            }
            else if(conditions instanceof Array){
                retV = this.buildSimpleWhereCond(what, conditions);
            };
            return [retV[0], retV.slice(1)];
        };
        return _normalize_complex_conditions(conditions, op);
    };

    Rho.NewORMModel.prototype._normalize_args_for_find = function(what, options, normalized_string_args, normalized_vector_args){
        // 1) Normalize LIMITS
        var limitArgs = this.buildFindLimits(what, options);
        for (var property in limitArgs) {
            normalized_string_args[property] = limitArgs[property];
        }

        // 2) Normalize ORDER BY
        var order_dir = options.orderdir || [];
        var order_attr = options.order || [];
        if (order_dir instanceof String){
            order_dir = [order_dir];
        };
        if (order_attr instanceof String){
            order_attr = [order_attr];
        };
        normalized_vector_args.order = this.buildFindOrder(order_attr, order_dir);

        // 3) Normalize SELECT
        var select_arr = options.select || [];
        normalized_vector_args.select = select_arr;

        // 4) Build Where Conditions
        var condVal = _normalize_conditions(what, options.conditions, options.op);
        console.log(" we have here : " + condVal[0] + ", " + JSON.stringify(condVal[1]));
        normalized_string_args.conditions = condVal[0] || "";
        normalized_vector_args.quests = condVal[1] || [];
    };

    Rho.NewORMModel.prototype.find = function(what, options){
        var normalized_vector_args = {};
        var normalized_string_args = {};
        _normalized_args_for_find(what, options, normalized_string_args, normalized_vector_args);
        var _found = this.findObjects(what, normalized_string_args,
                                        normalized_vector_args['quests'],
                                        normalized_vector_args['select'],
                                        normalized_vector_args['order']);
        switch (what) {
            case 'all'  : return _wrapORMInstances(_found);
            case 'count': return _found ;
            case 'first':
            default     : return _wrapORMInstance(_found[0]);
        };
    };

    Rho.NewORMModel.prototype.findBySql = function(sqlQuery){
        var _found = this.find_by_sql(sqlQuery);
        return _wrapORMInstances(_found);
    };

    Rho.NewORMModel.prototype.paginate = function(options){
        options['page'] = options['page'] || 0;
        options['per_page'] = options['per_page'] || 10;
        options['offset'] = options['page'] * options['per_page'];
        return find('all', options);
    };

    Rho.NewORMModel.prototype.delete_all = function(what, options){
        var normalized_vector_args = {};
        var normalized_string_args = {};
        _normalized_args_for_find(what, options, normalized_string_args, normalized_vector_args);
        return this.deleteObjects(what, normalized_string_args,
                                        normalized_vector_args['quests']);
    };

    Rho.NewORMModel.prototype._wrapORMInstance = function(objInst){
        var _new_instance = new _ORMObjectInstance(this, objInst);
        return _new_instance;
    };
    Rho.NewORMModel.prototype._wrapORMInstances = function(_objects){
        var _model_instances = [];
        for (var i = 0; i < _objects.length; i++) {
            var _object_instance = new _ORMObjectInstance(this, _objects[i]);
            _model_instances.pushObject(_object_instance);
        };
        return model_instances;
    };
    Rho.NewORMModel.prototype.create = function(objHash){
        var _new_instance = new _ORMObjectInstance(this, this.createObject(objHash));
        return _new_instance;
    };

    // === Rho.NewORMModel Object's wrapper methods ===
    var _ORMObjectInstance = function(model, obj){
        for (var attrname in obj) { this[attrname] = obj[attrname]; }
        this.source_id = model.source_id

        Object.defineProperty(this, '_klass_model', {
            value: function () {
                return model;
            },
            enumerable: false
        });
        Object.defineProperty(this, 'updateAttributes', {
            value: function (newAttrs) {
                var updatedAttrs = this._klass_model().updateObject(this.object, this, newAttrs);
                for (var attrname in updatedAttrs) { this[attrname] = updatedAttrs[attrname]; }
                console.log("and after update we have : " + JSON.stringify(this));
                return this;
            },
            enumerable: false
        });
        Object.defineProperty(this, 'save', {
            value: function () {
                var updatedAttrs = this._klass_model().saveObject(this.object, objAttrs);
                for (var attrname in updatedAttrs) { this[attrname] = updatedAttrs[attrname]; }
                return this;
            },
            enumerable: false
        });
        Object.defineProperty(this, 'destroy', {
            value: function () {
                this._klass_model().deleteObject(this.object);
                return this;
            },
            enumerable: false
        });
    };

    Rho.NewORM.dbPartitions = {};

    Rho.NewORM.dbConnection = function (partition){
        console.log('**** creating partition: ' + partition);
        //look for db connection, if not found create one
        var filepath = Rho.Application.databaseFilePath(partition);
        console.log('**** partition filepath: ' + filepath);

        var partitions = getDbPartitions();
        var db;
        console.log('**** partitions: ' + partitions);

        if(partitions && partitions[partition]){
            db = partitions[partition];
        }
        else{
            db = new Rho.Database(filepath, partition);
            partitions[partition] = db;
            console.log('**** partition created: ' + db);
        }
        console.log('returning from dbConnection: ' + partitions);
        return db;
    };

    Rho.NewORM.getDbPartitions = function() {
        return Rho.NewORM.dbPartitions;
    };

    console.log("Replacing Old Rho.ORM with new one!!!");
    Rho.ORM = Rho.NewORM;
    Rho.ORMModel = Rho.NewORMModel;
    Rho.ORM.dbConnection('local');
    Rho.ORM.dbConnection('user');
    Rho.ORM.dbConnection('app');

})(Rho.jQuery, Rho, Rho.util);

Rho.ORMHelper = Rho.NewORM;
<commit_msg>scoping of getDbPartitions() was wrong<commit_after>(function ($, rho, rhoUtil) {
    'use strict';

    // === Rho.NewORM wrapper members ===
    Rho.NewORM.addModel = function(modelname, modeldef){
        var model = new Rho.NewORMModel(modelname);
        modeldef(model);
        model.initModel();
        return model;
    };
    Rho.NewORM.getModel = function(modelname){
        return Rho.NewORMModel.getModel(modelname);
    };

    // === Rho.NewORMModel wrapper members ===
    Rho.NewORMModel.prototype._normalize_complex_conditions = function(conditions, op){
        if(!conditions){
            return ['', []];
        };
        op = op || 'AND';
        if(conditions instanceof Array){
            var quests = [];
            var sqlRes = '';
            for (var item in conditions) {
                if (sqlRes.length > 0) {
                    sqlRes += ' ' + op + ' ';
                };
                if(item.hasOwnProperty('conditions')) {
                    var subCond = _normalize_complex_conditions(item.conditions, item.op);
                }
                else {
                    var subCond = _normalize_complex_condition(item);
                }
                sqlRes += '(' + subCond[0] + ')';
                quests = quests.concat(subCond[1]);
            }
            return [sqlRes, quests];
        }
        else {
            return _normalize_complex_condition(conditions);
        };
    };

    Rho.NewORMModel.prototype._normalize_complex_condition = function(item){
        var sqlRes = "";
        var condQuests = [];
        var itemOp = "=";
        var itemFunc = "";
        var itemName = "";
        var itemValues = "";
        for (var propName in item) {
            switch (propName) {
            case 'op'  :
                itemOp = item[propName];
                break;
            case 'func':
                itemFunc = item[propName];
                break;
            case 'name':
                itemName = item[propName];
                break;
            case 'value':
            case 'values':
                itemValues = item[propName];
            default:
                itemName = propName;
                itemValues = item[Values];
            };
        };
        if(itemValues instanceof String){
            itemValues = [itemValues];
        };

        subCond = buildComplexWhereCond(itemName, itemValues, itemOp, itemFunc);
        return [subCond[0], subCond.slice(1)];
    };

    Rho.NewORMModel.prototype._normalize_conditions = function(what, conditions, op){
        console.log("MZV_DEBUG : make_conditions : " + what + ", " + JSON.stringify(conditions) + ", " + op);
        if (!op) {
            var retV = [];
            if(!conditions) {
                retV = this.buildSimpleWhereCond(what, []);
            }
            else if(conditions instanceof String){
                retV = this.buildSimpleWhereCond(what, [conditions]);
            }
            else if(conditions instanceof Array){
                retV = this.buildSimpleWhereCond(what, conditions);
            };
            return [retV[0], retV.slice(1)];
        };
        return _normalize_complex_conditions(conditions, op);
    };

    Rho.NewORMModel.prototype._normalize_args_for_find = function(what, options, normalized_string_args, normalized_vector_args){
        // 1) Normalize LIMITS
        var limitArgs = this.buildFindLimits(what, options);
        for (var property in limitArgs) {
            normalized_string_args[property] = limitArgs[property];
        }

        // 2) Normalize ORDER BY
        var order_dir = options.orderdir || [];
        var order_attr = options.order || [];
        if (order_dir instanceof String){
            order_dir = [order_dir];
        };
        if (order_attr instanceof String){
            order_attr = [order_attr];
        };
        normalized_vector_args.order = this.buildFindOrder(order_attr, order_dir);

        // 3) Normalize SELECT
        var select_arr = options.select || [];
        normalized_vector_args.select = select_arr;

        // 4) Build Where Conditions
        var condVal = _normalize_conditions(what, options.conditions, options.op);
        console.log(" we have here : " + condVal[0] + ", " + JSON.stringify(condVal[1]));
        normalized_string_args.conditions = condVal[0] || "";
        normalized_vector_args.quests = condVal[1] || [];
    };

    Rho.NewORMModel.prototype.find = function(what, options){
        var normalized_vector_args = {};
        var normalized_string_args = {};
        _normalized_args_for_find(what, options, normalized_string_args, normalized_vector_args);
        var _found = this.findObjects(what, normalized_string_args,
                                        normalized_vector_args['quests'],
                                        normalized_vector_args['select'],
                                        normalized_vector_args['order']);
        switch (what) {
            case 'all'  : return _wrapORMInstances(_found);
            case 'count': return _found ;
            case 'first':
            default     : return _wrapORMInstance(_found[0]);
        };
    };

    Rho.NewORMModel.prototype.findBySql = function(sqlQuery){
        var _found = this.find_by_sql(sqlQuery);
        return _wrapORMInstances(_found);
    };

    Rho.NewORMModel.prototype.paginate = function(options){
        options['page'] = options['page'] || 0;
        options['per_page'] = options['per_page'] || 10;
        options['offset'] = options['page'] * options['per_page'];
        return find('all', options);
    };

    Rho.NewORMModel.prototype.delete_all = function(what, options){
        var normalized_vector_args = {};
        var normalized_string_args = {};
        _normalized_args_for_find(what, options, normalized_string_args, normalized_vector_args);
        return this.deleteObjects(what, normalized_string_args,
                                        normalized_vector_args['quests']);
    };

    Rho.NewORMModel.prototype._wrapORMInstance = function(objInst){
        var _new_instance = new _ORMObjectInstance(this, objInst);
        return _new_instance;
    };
    Rho.NewORMModel.prototype._wrapORMInstances = function(_objects){
        var _model_instances = [];
        for (var i = 0; i < _objects.length; i++) {
            var _object_instance = new _ORMObjectInstance(this, _objects[i]);
            _model_instances.pushObject(_object_instance);
        };
        return model_instances;
    };
    Rho.NewORMModel.prototype.create = function(objHash){
        var _new_instance = new _ORMObjectInstance(this, this.createObject(objHash));
        return _new_instance;
    };

    // === Rho.NewORMModel Object's wrapper methods ===
    var _ORMObjectInstance = function(model, obj){
        for (var attrname in obj) { this[attrname] = obj[attrname]; }
        this.source_id = model.source_id

        Object.defineProperty(this, '_klass_model', {
            value: function () {
                return model;
            },
            enumerable: false
        });
        Object.defineProperty(this, 'updateAttributes', {
            value: function (newAttrs) {
                var updatedAttrs = this._klass_model().updateObject(this.object, this, newAttrs);
                for (var attrname in updatedAttrs) { this[attrname] = updatedAttrs[attrname]; }
                console.log("and after update we have : " + JSON.stringify(this));
                return this;
            },
            enumerable: false
        });
        Object.defineProperty(this, 'save', {
            value: function () {
                var updatedAttrs = this._klass_model().saveObject(this.object, objAttrs);
                for (var attrname in updatedAttrs) { this[attrname] = updatedAttrs[attrname]; }
                return this;
            },
            enumerable: false
        });
        Object.defineProperty(this, 'destroy', {
            value: function () {
                this._klass_model().deleteObject(this.object);
                return this;
            },
            enumerable: false
        });
    };

    Rho.NewORM.dbPartitions = {};

    Rho.NewORM.dbConnection = function (partition){
        console.log('**** creating partition: ' + partition);
        //look for db connection, if not found create one
        var filepath = Rho.Application.databaseFilePath(partition);
        console.log('**** partition filepath: ' + filepath);

        var partitions = Rho.NewORM.getDbPartitions();
        var db;
        console.log('**** partitions: ' + partitions);

        if(partitions && partitions[partition]){
            db = partitions[partition];
        }
        else{
            db = new Rho.Database(filepath, partition);
            partitions[partition] = db;
            console.log('**** partition created: ' + db);
        }
        console.log('returning from dbConnection: ' + partitions);
        return db;
    };

    Rho.NewORM.getDbPartitions = function() {
        return Rho.NewORM.dbPartitions;
    };

    console.log("Replacing Old Rho.ORM with new one!!!");
    Rho.ORM = Rho.NewORM;
    Rho.ORMModel = Rho.NewORMModel;
    Rho.ORM.dbConnection('local');
    Rho.ORM.dbConnection('user');
    Rho.ORM.dbConnection('app');

})(Rho.jQuery, Rho, Rho.util);

Rho.ORMHelper = Rho.NewORM;
<|endoftext|>


<commit_before>// Quark's Node Runtime and associated
/* jshint node: true */

(function () {
    "use strict";

    var assert = require("assert");

    var WebSocket = require("ws");

    // CLASS QuarkWebsocket
    function QuarkWebSocket(url, handler) {
        this.url = url;
        this.socket = new WebSocket(url);
        //this.handler = handler;
        this.isOpen = false;

        var self = this;
        handler.onInit(self);

        this.socket.on("open", function () {
            self.isOpen = true;
            handler.onConnected(self);
        });
        this.socket.on("message", function (message /*, flags */) {
            handler.onMessage(self, message);
        });
        this.socket.on("close", function (/* code, message */) {
            handler.onClosed(self);
            self.socket.terminate();
            handler.onFinal(self);
        });
        this.socket.on("error", function (/* error */) {
            handler.onError(self);
            self.socket.terminate();
            handler.onFinal(self);
        });
    }
    QuarkWebSocket.prototype.send = function (message) {
        if (this.isOpen) {
            this.socket.send(message);
            return 1;
        }
        return 0;
    };

    var http = require("http");
    var url = require("url");

    // CLASS QuarkRequest
    function QuarkRequest(request, handler) {
        var options = url.parse(request.url);
        options.method = request.method;

        handler.onInit(request);

        var req = http.request(options);
        req.on("response", function (response) {
            var body = "";
            response.on("data", function (data) {
                body += data;
            });
            response.on("end", function () {
                handler.onResponse(request, new QuarkResponse(response.statusCode, body));
                req.abort();
                handler.onFinal(request);
            });
        });

        req.on("error", function (/* error */) {
            handler.onError(request);
            req.abort();
            handler.onFinal(request);
        });

        if (request.body) {
            req.write(request.body);
        }
        req.end();
    }

    // CLASS QuarkResponse
    function QuarkResponse(code, body) {
        this.code = code;
        this.body = body;
    }
    QuarkResponse.prototype.getCode = function () {
        return this.code;
    };
    QuarkResponse.prototype.getBody = function () {
        return this.body;
    };

    // CLASS Runtime
    function Runtime() {
        this.locked = false;
    }
    Runtime.prototype.acquire = function () {
        assert(!this.locked);
        this.locked = true;
    };
    Runtime.prototype.release = function () {
        assert(this.locked);
        this.locked = false;
    };
    Runtime.prototype.wait = function (/* timeoutInSeconds */) {
        assert(this.locked);
        assert(false);
    };
    Runtime.prototype.open = function (url, handler) {
        new QuarkWebSocket(url, handler);
    };

    Runtime.prototype.request = function (request, handler) {
        new QuarkRequest(request, handler);
    };

    Runtime.prototype.schedule = function (handler, delayInSeconds) {
        var self = this;
        setTimeout(function () { handler.onExecute(self); },
                   delayInSeconds * 1000);
    };
    Runtime.prototype.launch = function () {};

    module.exports = new Runtime();

})();
<commit_msg>Support HTTPS protocol in JavaScript<commit_after>// Quark's Node Runtime and associated
/* jshint node: true */

(function () {
    "use strict";

    var assert = require("assert");

    var WebSocket = require("ws");

    // CLASS QuarkWebsocket
    function QuarkWebSocket(url, handler) {
        this.url = url;
        this.socket = new WebSocket(url);
        //this.handler = handler;
        this.isOpen = false;

        var self = this;
        handler.onInit(self);

        this.socket.on("open", function () {
            self.isOpen = true;
            handler.onConnected(self);
        });
        this.socket.on("message", function (message /*, flags */) {
            handler.onMessage(self, message);
        });
        this.socket.on("close", function (/* code, message */) {
            handler.onClosed(self);
            self.socket.terminate();
            handler.onFinal(self);
        });
        this.socket.on("error", function (/* error */) {
            handler.onError(self);
            self.socket.terminate();
            handler.onFinal(self);
        });
    }
    QuarkWebSocket.prototype.send = function (message) {
        if (this.isOpen) {
            this.socket.send(message);
            return 1;
        }
        return 0;
    };

    var http = require("http");
    var https = require("https");
    var url = require("url");

    // CLASS QuarkRequest
    function QuarkRequest(request, handler) {
        var options = url.parse(request.url);
        options.method = request.method;

        handler.onInit(request);

        var protocol = http;
        if (options.protocol == "https:") {
            protocol = https;
        }

        var req = protocol.request(options);
        req.on("response", function (response) {
            var body = "";
            response.on("data", function (data) {
                body += data;
            });
            response.on("end", function () {
                handler.onResponse(request, new QuarkResponse(response.statusCode, body));
                req.abort();
                handler.onFinal(request);
            });
        });

        req.on("error", function (/* error */) {
            handler.onError(request);
            req.abort();
            handler.onFinal(request);
        });

        if (request.body) {
            req.write(request.body);
        }
        req.end();
    }

    // CLASS QuarkResponse
    function QuarkResponse(code, body) {
        this.code = code;
        this.body = body;
    }
    QuarkResponse.prototype.getCode = function () {
        return this.code;
    };
    QuarkResponse.prototype.getBody = function () {
        return this.body;
    };

    // CLASS Runtime
    function Runtime() {
        this.locked = false;
    }
    Runtime.prototype.acquire = function () {
        assert(!this.locked);
        this.locked = true;
    };
    Runtime.prototype.release = function () {
        assert(this.locked);
        this.locked = false;
    };
    Runtime.prototype.wait = function (/* timeoutInSeconds */) {
        assert(this.locked);
        assert(false);
    };
    Runtime.prototype.open = function (url, handler) {
        new QuarkWebSocket(url, handler);
    };

    Runtime.prototype.request = function (request, handler) {
        new QuarkRequest(request, handler);
    };

    Runtime.prototype.schedule = function (handler, delayInSeconds) {
        var self = this;
        setTimeout(function () { handler.onExecute(self); },
                   delayInSeconds * 1000);
    };
    Runtime.prototype.launch = function () {};

    module.exports = new Runtime();

})();
<|endoftext|>