<commit_before>const {until, WebElement} = require('selenium-webdriver');
const SeleniumWebdriver = require('./');
const Transport = require('../');
const {Logger, isString} = require('../../utils');

module.exports = class MethodMappings {
  get driver() {
    return this.transport.driver;
  }

  get settings() {
    return this.transport.settings;
  }

  getWebElement(webElementOrString) {
    if (webElementOrString instanceof WebElement) {
      return webElementOrString;
    }

    if (isString(webElementOrString)) {
      return new WebElement(this.driver, webElementOrString);
    }
  }

  constructor(transport) {
    this.transport = transport;
  }

  get methods() {
    return {
      ///////////////////////////////////////////////////////////
      // Session related
      ///////////////////////////////////////////////////////////
      sessionAction(action) {
        switch (action) {
          case 'DELETE':
            return this.driver.quit();

          default:
            return this.driver.getSession();
        }
      },

      getSessions: '/sessions',
      getStatus: '/status',

      session: {
        ///////////////////////////////////////////////////////////
        // Timeouts
        ///////////////////////////////////////////////////////////
        async setTimeoutType(type, value) {
          await this.driver.manage().setTimeouts({
            [type]: value
          });

          return {
            value: null
          };
        },

        async setTimeoutsAsyncScript(value) {
          await this.driver.manage().setTimeouts({script: value});

          return  {
            value: null
          };
        },

        async setTimeoutsImplicitWait(value) {
          await this.driver.manage().setTimeouts({implicit: value});

          return  {
            value: null
          };
        },

        async getTimeouts() {
          const timeout = await this.driver.manage().getTimeouts();

          return {
            value: timeout
          };
        },

        ///////////////////////////////////////////////////////////
        // Session log
        ///////////////////////////////////////////////////////////
        async getSessionLogTypes() {
          const value =  await this.driver.manage().logs().getAvailableLogTypes();

          return {
            value
          };
        },

        async getLogContents(type) {
          const value = await this.driver.manage().logs().get(type);

          return {
            value
          };
        },

        ///////////////////////////////////////////////////////////
        // Navigation
        ///////////////////////////////////////////////////////////
        async navigateTo(url) {
          await this.driver.navigate().to(url);

          return {
            value: null
          };
        },

        async getCurrentUrl() {
          const url = await this.driver.getCurrentUrl();

          return {
            value: url
          };
        },

        async navigateBack() {
          await this.driver.navigate().back();

          return {
            value: null
          };
        },

        async navigateForward() {
          await this.driver.navigate().forward();

          return {
            value: null
          };
        },

        async pageRefresh() {
          await this.driver.navigate().refresh();

          return {
            value: null
          };
        },

        async getPageTitle() {
          const title = await this.driver.getTitle();

          return {
            value: title
          };
        },

        async getPageTitle() {
          const value = await this.driver.getTitle();

          return {
            value
          };
        },

        ///////////////////////////////////////////////////////////
        // Windows
        ///////////////////////////////////////////////////////////
        async switchToWindow(handle) {
          await this.driver.switchTo().window(handle);

          return {
            value: null
          };
        },

        async closeWindow() {
          await this.driver.close();

          return {
            value: null
          };
        },

        async getWindowHandle() {
          const value = await this.driver.getWindowHandle();

          return {
            value
          };
        },

        async getAllWindowHandles() {
          const value = await this.driver.getAllWindowHandles();

          return {
            value
          };
        },

        async getWindowPosition() {
          const {x, y} = await this.driver.manage().window().getRect();

          return {
            value: {
              x,
              y
            }
          };
        },

        async maximizeWindow(windowHandle) {
          await this.driver.manage().window().maximize();

          return {
            value: null
          };
        },

        async minimizeWindow() {
          await this.driver.manage().window().minimize();

          return {
            value: null
          };
        },

        async fullscreenWindow() {
          await this.driver.manage().window().fullscreen();

          return {
            value: null
          };
        },

        async openNewWindow() {
          // return TransportActions.post('/window/new');
          await this.driver.switchTo().newWindow('window');

          return {
            value: null
          };
        },

        //Kept windowHandle as params for backward comptability.
        async setWindowPosition(windowHandle, x, y) {
          await this.driver.manage().window().setRect({
            x,
            y
          });

          return {
            value: null
          };
        },

        async getWindowSize() {
          const {width, height} = await this.driver.manage().window().getRect();

          return {
            value: {
              width,
              height
            }
          };
        },

        //Kept windowHandle as params for backward compatibility.
        async setWindowSize(windowHandle, width, height) {
          await this.driver.manage().window().setRect({
            width,
            height
          });

          return {
            value: null
          };
        },

        async getWindowRect() {
          const value = await this.driver.manage().window().getRect();

          return {
            value
          };
        },

        async setWindowRect(data) {
          await this.driver.manage().window().setRect(data);

          return {
            value: null
          };
        },

        ///////////////////////////////////////////////////////////
        // Frames
        ///////////////////////////////////////////////////////////
        async switchToFrame(frameId) {
          if (frameId === undefined) {
            frameId = null;
          }

          await this.driver.manage().switchToFrame({
            id: frameId
          });

          return {
            value: null
          };
        },

        async switchToParentFrame() {
          await this.driver.manage().switchToParentFrame();

          return {
            value: null
          };
        },

        ///////////////////////////////////////////////////////////
        // Elements
        ///////////////////////////////////////////////////////////
        async locateSingleElement(element) {
          const locator = SeleniumWebdriver.createLocator(element);
          //const {waitForConditionTimeout, waitForConditionPollInterval}

          const webElement = await this.driver.wait(until.elementLocated(locator));
          const elementId = await webElement.getId();

          return {
            value: elementId,
            webElement
          };
        },

        async locateMultipleElements(element) {
          const locator = SeleniumWebdriver.createLocator(element);
          const resultValue = await this.driver.findElements(locator);
          const resultProcessed = await Promise.all(resultValue.map(async webElement => {
            const elementId = await webElement.getId();

            return {[Transport.WEB_ELEMENT_ID]: elementId};
          }));

          return {
            value: resultProcessed
          };
        },

        elementIdEquals(id, otherId) {
          return `/element/${id}/equals/${otherId}`;
        },

        async locateSingleElementByElementId({id, value}) {
          const locator = SeleniumWebdriver.createLocator(value);
          const element = await this.getWebElement(id);

          const webElement = await element.findElement(locator);

          const elementId = await webElement.getId();

          return {
            value: webElement,
            elementId
          };
        },

        async locateMultipleElementsByElementId({id, using, value}) {
          const locator = SeleniumWebdriver.createLocator(value);
          const element = await this.getWebElement(id);
          const resultValue = await element.findElements(locator);

          const resultProcessed = await Promise.all(resultValue.map(async webElement => {
            const elementId = await webElement.getId();

            return {[Transport.WEB_ELEMENT_ID]: elementId};
          }));

          return {
            value: resultProcessed
          };
        },

        async getActiveElement() {
          try {
            const activeElement = await this.driver.switchTo().activeElement();

            return {
              value: activeElement
            };
          } catch (error) {
            Logger.error(error);

            return {
              error,
              status: -1
            };
          }
        },

        async getElementAttribute(webElement, attributeName) {
          const element = this.getWebElement(webElement);
          const elementValue = await element.getAttribute(attributeName);

          return {
            value: elementValue
          };
        },

        async getElementCSSValue(id, cssPropertyName) {
          const element = this.getWebElement(id);
          const elementCssValue = await element.getCssValue(cssPropertyName);

          return {
            value: elementCssValue
          };
        },

        async getElementProperty(webElement, propertyName) {
          const element = this.getWebElement(webElement);
          const elementValue = await element.getAttribute(propertyName);

          return {
            value: elementValue
          };
        },

        async getElementTagName(id) {
          const element = this.getWebElement(id);
          const elementTagName = await element.getTagName();

          return {
            value: elementTagName
          };
        },

        async getElementSize(id) {
          const element = this.getWebElement(id);
          const elementSize = await element.getRect();

          return {
            value: elementSize
          };
        },

        async getElementText(id) {
          const element = this.getWebElement(id);
          const elementText = await element.getText();

          return {
            value: elementText
          };
        },

        // the value param is compulsory
        async getElementValue(webElement, value) {
          const element = this.getWebElement(webElement);
          const elementValue = await element.getAttribute(value);

          return {
            value: elementValue
          };
        },

        async getElementLocation(id) {
          const element = this.getWebElement(id);
          const {x, y} = await element.getRect();

          return {
            value: {
              x,
              y
            }
          };
        },

        isElementLocationInView(id) {
          return `/element/${id}/location_in_view`;
        },

        async isElementDisplayed(webElement) {
          try {
            const element = this.getWebElement(webElement);
            const value = await element.isDisplayed();

            return {
              value
            };
          } catch (error) {
            Logger.error(error);

            return {
              error,
              status: -1
            };
          }
        },

        async isElementEnabled(webElement) {
          try {
            const element = this.getWebElement(webElement);
            const value = await element.isEnabled();

            return {
              value
            };
          } catch (error) {
            Logger.error(error);

            return {
              error,
              status: -1
            };
          }
        },

        async isElementSelected(webElement) {
          try {
            const element = this.getWebElement(webElement);
            const value = await element.isSelected();

            return {
              value
            };
          } catch (error) {
            Logger.error(error);

            return {
              error,
              status: -1
            };
          }
        },

        async clearElementValue(webElement) {
          const element = this.getWebElement(webElement);
          await element.clear();

          return {
            value: null
          };
        },

        async setElementValue(webElement, value) {
          if (Array.isArray(value)) {
            value = value.join('');
          } else {
            value = String(value);
          }

          try {
            const element = this.getWebElement(webElement);
            await element.sendKeys(value);

            return {
              value: null
            };
          } catch (error) {
            Logger.error(error);

            return {
              error,
              status: -1
            };
          }
        },

        async clickElement(webElement) {
          try {
            const element = this.getWebElement(webElement);
            await element.click();

            return {
              value: null
            };
          } catch (error) {
            Logger.error(error);

            return {
              error,
              status: -1
            };
          }
        },

        async elementSubmit(webElement) {
          try {
            const element = this.getWebElement(webElement);
            await element.submit();

            return {
              value: null
            };
          } catch (error) {
            Logger.error(error);

            return {
              error,
              status: -1
            };
          }
        },

        sendKeys(keys) {
          return TransportActions.post({
            path: '/keys',
            data: {
              value: keys
            }
          });
        },

        ///////////////////////////////////////////////////////////
        // Document Handling
        ///////////////////////////////////////////////////////////
        getPageSource: '/source',

        async executeScript(script, args) {
          const value = await this.driver.executeScript(script, args);

          return {
            value
          };
        },

        async executeScriptAsync(fn, args) {
          const value = await this.driver.executeAsyncScript(fn, args);

          return {
            value
          };
        },

        ///////////////////////////////////////////////////////////
        // Cookies
        ///////////////////////////////////////////////////////////

        async setCookieString(cookie) {
          await this.driver.manage().addCookie(cookie);

          return {
            value: null
          };
        },

        async deleteCookie(cookieName) {
          await this.driver.manage().deleteCookie(cookieName);

          return {
            value: null
          };
        },

        async deleteAllCookies() {
          await this.driver.manage().deleteAllCookies();

          return {
            value: null
          };
        },

        async getCookieString() {
          const value = await this.driver.manage().getCookies();

          return {
            value
          };
        },

        ///////////////////////////////////////////////////////////
        // User Actions
        ///////////////////////////////////////////////////////////
        /**
         *
         * @param {WebElement|null|undefined} element
         * @param {{async: (boolean|undefined), bridge: (boolean|undefined)}} options
         */
        async doubleClick(element, options) {

          await this.driver.actions(options).doubleClick(element);

          return {
            value: null
          };
        },

        /**
         *
         * @param {WebElement|null|undefined} element
         * @param {{async: (boolean|undefined), bridge: (boolean|undefined)}} options
         */
        async mouseButtonClick(element, options) {
          await this.driver.actions(options).click(element);

          return {
            value: null
          };
        },

        mouseButtonUp(buttonIndex) {
          return TransportActions.post({
            path: '/buttonup',
            data: {
              button: buttonIndex
            }
          });
        },

        mouseButtonDown(buttonIndex) {
          return TransportActions.post({
            path: '/buttondown',
            data: {
              button: buttonIndex
            }
          });
        },

        //TODO: update parameters
        /**
         *
         * @param {{async: (boolean|undefined), bridge: (boolean|undefined)}} options
         * @param {number|undefined} duration
         * @param {Origin|WebElement|undefined} origin
         * @param {number|undefined} xOffset
         * @param {number|undefined} yOffset
         */
        async moveTo(options, duration, origin, xOffset, yOffset) {
          await this.driver.actions(options).move({duration, origin, xOffset, yOffset});

          return {
            value: null
          };

        },

        ///////////////////////////////////////////////////////////
        // User Prompts
        ///////////////////////////////////////////////////////////
        async acceptAlert() {
          await this.driver.switchTo().alert().accept();

          return {
            value: null
          };
        },

        async dismissAlert() {
          await this.driver.switchTo().alert().dismiss();

          return {
            value: null
          };
        },

        async getAlertText() {
          const value = await this.driver.switchTo().alert().getText();

          return {
            value
          };
        },

        async setAlertText(keys) {
          const alert = await this.driver.switchTo().alert();
          await alert.sendKeys(keys);
          const value = await alert.accept();

          return {
            value
          };
        },

        ///////////////////////////////////////////////////////////
        // Screen
        ///////////////////////////////////////////////////////////
        getScreenshot(logBase64Data) {
          return Promise.resolve('');

          return {
            path: '/screenshot',
            addtOpts: {
              suppressBase64Data: !logBase64Data
            }
          };
        },

        getScreenOrientation: '/orientation',

        setScreenOrientation(orientation) {
          return TransportActions.post({
            path: '/orientation',
            data: {
              orientation: orientation
            }
          });
        },

        getAvailableContexts: '/contexts',

        getCurrentContext: '/context',

        setCurrentContext(context) {
          return TransportActions.post({
            path: '/context',
            data: {
              name: context
            }
          });
        },

        ///////////////////////////////////////////////////////////////////////////
        // Selenium Webdriver
        ///////////////////////////////////////////////////////////////////////////
        async wait(conditionFn, timeMs) {
          await this.driver.wait(conditionFn(), timeMs);

          return {
            value: null
          };
        }
      }
    };
  }
};
<commit_msg>fixed a syntax error<commit_after>const {until, WebElement} = require('selenium-webdriver');
const SeleniumWebdriver = require('./');
const Transport = require('../');
const {Logger, isString} = require('../../utils');

module.exports = class MethodMappings {
  get driver() {
    return this.transport.driver;
  }

  get settings() {
    return this.transport.settings;
  }

  getWebElement(webElementOrString) {
    if (webElementOrString instanceof WebElement) {
      return webElementOrString;
    }

    if (isString(webElementOrString)) {
      return new WebElement(this.driver, webElementOrString);
    }
  }

  constructor(transport) {
    this.transport = transport;
  }

  get methods() {
    return {
      ///////////////////////////////////////////////////////////
      // Session related
      ///////////////////////////////////////////////////////////
      sessionAction(action) {
        switch (action) {
          case 'DELETE':
            return this.driver.quit();

          default:
            return this.driver.getSession();
        }
      },

      getSessions: '/sessions',
      getStatus: '/status',

      session: {
        ///////////////////////////////////////////////////////////
        // Timeouts
        ///////////////////////////////////////////////////////////
        async setTimeoutType(type, value) {
          await this.driver.manage().setTimeouts({
            [type]: value
          });

          return {
            value: null
          };
        },

        async setTimeoutsAsyncScript(value) {
          await this.driver.manage().setTimeouts({script: value});

          return  {
            value: null
          };
        },

        async setTimeoutsImplicitWait(value) {
          await this.driver.manage().setTimeouts({implicit: value});

          return  {
            value: null
          };
        },

        async getTimeouts() {
          const timeout = await this.driver.manage().getTimeouts();

          return {
            value: timeout
          };
        },

        ///////////////////////////////////////////////////////////
        // Session log
        ///////////////////////////////////////////////////////////
        async getSessionLogTypes() {
          const value =  await this.driver.manage().logs().getAvailableLogTypes();

          return {
            value
          };
        },

        async getLogContents(type) {
          const value = await this.driver.manage().logs().get(type);

          return {
            value
          };
        },

        ///////////////////////////////////////////////////////////
        // Navigation
        ///////////////////////////////////////////////////////////
        async navigateTo(url) {
          await this.driver.navigate().to(url);

          return {
            value: null
          };
        },

        async getCurrentUrl() {
          const url = await this.driver.getCurrentUrl();

          return {
            value: url
          };
        },

        async navigateBack() {
          await this.driver.navigate().back();

          return {
            value: null
          };
        },

        async navigateForward() {
          await this.driver.navigate().forward();

          return {
            value: null
          };
        },

        async pageRefresh() {
          await this.driver.navigate().refresh();

          return {
            value: null
          };
        },

        async getPageTitle() {
          const value = await this.driver.getTitle();

          return {
            value
          };
        },

        ///////////////////////////////////////////////////////////
        // Windows
        ///////////////////////////////////////////////////////////
        async switchToWindow(handle) {
          await this.driver.switchTo().window(handle);

          return {
            value: null
          };
        },

        async closeWindow() {
          await this.driver.close();

          return {
            value: null
          };
        },

        async getWindowHandle() {
          const value = await this.driver.getWindowHandle();

          return {
            value
          };
        },

        async getAllWindowHandles() {
          const value = await this.driver.getAllWindowHandles();

          return {
            value
          };
        },

        async getWindowPosition() {
          const {x, y} = await this.driver.manage().window().getRect();

          return {
            value: {
              x,
              y
            }
          };
        },

        async maximizeWindow(windowHandle) {
          await this.driver.manage().window().maximize();

          return {
            value: null
          };
        },

        async minimizeWindow() {
          await this.driver.manage().window().minimize();

          return {
            value: null
          };
        },

        async fullscreenWindow() {
          await this.driver.manage().window().fullscreen();

          return {
            value: null
          };
        },

        async openNewWindow() {
          // return TransportActions.post('/window/new');
          await this.driver.switchTo().newWindow('window');

          return {
            value: null
          };
        },

        //Kept windowHandle as params for backward comptability.
        async setWindowPosition(windowHandle, x, y) {
          await this.driver.manage().window().setRect({
            x,
            y
          });

          return {
            value: null
          };
        },

        async getWindowSize() {
          const {width, height} = await this.driver.manage().window().getRect();

          return {
            value: {
              width,
              height
            }
          };
        },

        //Kept windowHandle as params for backward compatibility.
        async setWindowSize(windowHandle, width, height) {
          await this.driver.manage().window().setRect({
            width,
            height
          });

          return {
            value: null
          };
        },

        async getWindowRect() {
          const value = await this.driver.manage().window().getRect();

          return {
            value
          };
        },

        async setWindowRect(data) {
          await this.driver.manage().window().setRect(data);

          return {
            value: null
          };
        },

        ///////////////////////////////////////////////////////////
        // Frames
        ///////////////////////////////////////////////////////////
        async switchToFrame(frameId) {
          if (frameId === undefined) {
            frameId = null;
          }

          await this.driver.manage().switchToFrame({
            id: frameId
          });

          return {
            value: null
          };
        },

        async switchToParentFrame() {
          await this.driver.manage().switchToParentFrame();

          return {
            value: null
          };
        },

        ///////////////////////////////////////////////////////////
        // Elements
        ///////////////////////////////////////////////////////////
        async locateSingleElement(element) {
          const locator = SeleniumWebdriver.createLocator(element);
          //const {waitForConditionTimeout, waitForConditionPollInterval}

          const webElement = await this.driver.wait(until.elementLocated(locator));
          const elementId = await webElement.getId();

          return {
            value: elementId,
            webElement
          };
        },

        async locateMultipleElements(element) {
          const locator = SeleniumWebdriver.createLocator(element);
          const resultValue = await this.driver.findElements(locator);
          const resultProcessed = await Promise.all(resultValue.map(async webElement => {
            const elementId = await webElement.getId();

            return {[Transport.WEB_ELEMENT_ID]: elementId};
          }));

          return {
            value: resultProcessed
          };
        },

        elementIdEquals(id, otherId) {
          return `/element/${id}/equals/${otherId}`;
        },

        async locateSingleElementByElementId({id, value}) {
          const locator = SeleniumWebdriver.createLocator(value);
          const element = await this.getWebElement(id);

          const webElement = await element.findElement(locator);

          const elementId = await webElement.getId();

          return {
            value: webElement,
            elementId
          };
        },

        async locateMultipleElementsByElementId({id, using, value}) {
          const locator = SeleniumWebdriver.createLocator(value);
          const element = await this.getWebElement(id);
          const resultValue = await element.findElements(locator);

          const resultProcessed = await Promise.all(resultValue.map(async webElement => {
            const elementId = await webElement.getId();

            return {[Transport.WEB_ELEMENT_ID]: elementId};
          }));

          return {
            value: resultProcessed
          };
        },

        async getActiveElement() {
          try {
            const activeElement = await this.driver.switchTo().activeElement();

            return {
              value: activeElement
            };
          } catch (error) {
            Logger.error(error);

            return {
              error,
              status: -1
            };
          }
        },

        async getElementAttribute(webElement, attributeName) {
          const element = this.getWebElement(webElement);
          const elementValue = await element.getAttribute(attributeName);

          return {
            value: elementValue
          };
        },

        async getElementCSSValue(id, cssPropertyName) {
          const element = this.getWebElement(id);
          const elementCssValue = await element.getCssValue(cssPropertyName);

          return {
            value: elementCssValue
          };
        },

        async getElementProperty(webElement, propertyName) {
          const element = this.getWebElement(webElement);
          const elementValue = await element.getAttribute(propertyName);

          return {
            value: elementValue
          };
        },

        async getElementTagName(id) {
          const element = this.getWebElement(id);
          const elementTagName = await element.getTagName();

          return {
            value: elementTagName
          };
        },

        async getElementSize(id) {
          const element = this.getWebElement(id);
          const elementSize = await element.getRect();

          return {
            value: elementSize
          };
        },

        async getElementText(id) {
          const element = this.getWebElement(id);
          const elementText = await element.getText();

          return {
            value: elementText
          };
        },

        // the value param is compulsory
        async getElementValue(webElement, value) {
          const element = this.getWebElement(webElement);
          const elementValue = await element.getAttribute(value);

          return {
            value: elementValue
          };
        },

        async getElementLocation(id) {
          const element = this.getWebElement(id);
          const {x, y} = await element.getRect();

          return {
            value: {
              x,
              y
            }
          };
        },

        isElementLocationInView(id) {
          return `/element/${id}/location_in_view`;
        },

        async isElementDisplayed(webElement) {
          try {
            const element = this.getWebElement(webElement);
            const value = await element.isDisplayed();

            return {
              value
            };
          } catch (error) {
            Logger.error(error);

            return {
              error,
              status: -1
            };
          }
        },

        async isElementEnabled(webElement) {
          try {
            const element = this.getWebElement(webElement);
            const value = await element.isEnabled();

            return {
              value
            };
          } catch (error) {
            Logger.error(error);

            return {
              error,
              status: -1
            };
          }
        },

        async isElementSelected(webElement) {
          try {
            const element = this.getWebElement(webElement);
            const value = await element.isSelected();

            return {
              value
            };
          } catch (error) {
            Logger.error(error);

            return {
              error,
              status: -1
            };
          }
        },

        async clearElementValue(webElement) {
          const element = this.getWebElement(webElement);
          await element.clear();

          return {
            value: null
          };
        },

        async setElementValue(webElement, value) {
          if (Array.isArray(value)) {
            value = value.join('');
          } else {
            value = String(value);
          }

          try {
            const element = this.getWebElement(webElement);
            await element.sendKeys(value);

            return {
              value: null
            };
          } catch (error) {
            Logger.error(error);

            return {
              error,
              status: -1
            };
          }
        },

        async clickElement(webElement) {
          try {
            const element = this.getWebElement(webElement);
            await element.click();

            return {
              value: null
            };
          } catch (error) {
            Logger.error(error);

            return {
              error,
              status: -1
            };
          }
        },

        async elementSubmit(webElement) {
          try {
            const element = this.getWebElement(webElement);
            await element.submit();

            return {
              value: null
            };
          } catch (error) {
            Logger.error(error);

            return {
              error,
              status: -1
            };
          }
        },

        sendKeys(keys) {
          return TransportActions.post({
            path: '/keys',
            data: {
              value: keys
            }
          });
        },

        ///////////////////////////////////////////////////////////
        // Document Handling
        ///////////////////////////////////////////////////////////
        getPageSource: '/source',

        async executeScript(script, args) {
          const value = await this.driver.executeScript(script, args);

          return {
            value
          };
        },

        async executeScriptAsync(fn, args) {
          const value = await this.driver.executeAsyncScript(fn, args);

          return {
            value
          };
        },

        ///////////////////////////////////////////////////////////
        // Cookies
        ///////////////////////////////////////////////////////////

        async setCookieString(cookie) {
          await this.driver.manage().addCookie(cookie);

          return {
            value: null
          };
        },

        async deleteCookie(cookieName) {
          await this.driver.manage().deleteCookie(cookieName);

          return {
            value: null
          };
        },

        async deleteAllCookies() {
          await this.driver.manage().deleteAllCookies();

          return {
            value: null
          };
        },

        async getCookieString() {
          const value = await this.driver.manage().getCookies();

          return {
            value
          };
        },

        ///////////////////////////////////////////////////////////
        // User Actions
        ///////////////////////////////////////////////////////////
        /**
         *
         * @param {WebElement|null|undefined} element
         * @param {{async: (boolean|undefined), bridge: (boolean|undefined)}} options
         */
        async doubleClick(element, options) {

          await this.driver.actions(options).doubleClick(element);

          return {
            value: null
          };
        },

        /**
         *
         * @param {WebElement|null|undefined} element
         * @param {{async: (boolean|undefined), bridge: (boolean|undefined)}} options
         */
        async mouseButtonClick(element, options) {
          await this.driver.actions(options).click(element);

          return {
            value: null
          };
        },

        mouseButtonUp(buttonIndex) {
          return TransportActions.post({
            path: '/buttonup',
            data: {
              button: buttonIndex
            }
          });
        },

        mouseButtonDown(buttonIndex) {
          return TransportActions.post({
            path: '/buttondown',
            data: {
              button: buttonIndex
            }
          });
        },

        //TODO: update parameters
        /**
         *
         * @param {{async: (boolean|undefined), bridge: (boolean|undefined)}} options
         * @param {number|undefined} duration
         * @param {Origin|WebElement|undefined} origin
         * @param {number|undefined} xOffset
         * @param {number|undefined} yOffset
         */
        async moveTo(options, duration, origin, xOffset, yOffset) {
          await this.driver.actions(options).move({duration, origin, xOffset, yOffset});

          return {
            value: null
          };

        },

        ///////////////////////////////////////////////////////////
        // User Prompts
        ///////////////////////////////////////////////////////////
        async acceptAlert() {
          await this.driver.switchTo().alert().accept();

          return {
            value: null
          };
        },

        async dismissAlert() {
          await this.driver.switchTo().alert().dismiss();

          return {
            value: null
          };
        },

        async getAlertText() {
          const value = await this.driver.switchTo().alert().getText();

          return {
            value
          };
        },

        async setAlertText(keys) {
          const alert = await this.driver.switchTo().alert();
          await alert.sendKeys(keys);
          const value = await alert.accept();

          return {
            value
          };
        },

        ///////////////////////////////////////////////////////////
        // Screen
        ///////////////////////////////////////////////////////////
        getScreenshot(logBase64Data) {
          return Promise.resolve('');

          return {
            path: '/screenshot',
            addtOpts: {
              suppressBase64Data: !logBase64Data
            }
          };
        },

        getScreenOrientation: '/orientation',

        setScreenOrientation(orientation) {
          return TransportActions.post({
            path: '/orientation',
            data: {
              orientation: orientation
            }
          });
        },

        getAvailableContexts: '/contexts',

        getCurrentContext: '/context',

        setCurrentContext(context) {
          return TransportActions.post({
            path: '/context',
            data: {
              name: context
            }
          });
        },

        ///////////////////////////////////////////////////////////////////////////
        // Selenium Webdriver
        ///////////////////////////////////////////////////////////////////////////
        async wait(conditionFn, timeMs) {
          await this.driver.wait(conditionFn(), timeMs);

          return {
            value: null
          };
        }
      }
    };
  }
};
<|endoftext|>


<commit_before>`use strict`

require('dotenv').config()
const express = require('express');
const path = require('path');
const logger = require('morgan');
const bodyParser = require('body-parser');
const routes = require('./routes/');

const app = express();
// This 'if' statement prevents application log messages from
// displaying in the stdout when the tests are run
if (process.env.NODE_ENV !== 'test') {
  app.use(logger('dev'));
}

// *** cross domain requests *** //
const allowCrossDomain = function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  next();
};

app.use(allowCrossDomain);

// require('dotenv').config()
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use('/api/v1/', routes)
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  let err = new Error('Not Found');
  err.status = 404;
  next(err);
});

if(app.get('env') === 'development' || app.get('env') === 'test') {
  app.use((err,req,res,next) => {
    console.log("error", err)
    res.status(err.status || 500)
    res.json({
      message: err.message,
      error: err
    })
  })
}

//default to production
app.use((err,req,res,next) => {
    console.log("error", err)
    res.status(err.status || 500)
    res.json({
      message: err.message,
      error: {}
    })
  })

const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`Listening on port ${port} in env: ${process.env.NODE_ENV}`);
});

module.exports = app;
<commit_msg>put cors plugin back into app<commit_after>`use strict`

require('dotenv').config()
const express = require('express');
const path = require('path');
const logger = require('morgan');
const bodyParser = require('body-parser');
const cors = require('cors')
const routes = require('./routes/');

const app = express();
app.use(cors())
// This 'if' statement prevents application log messages from
// displaying in the stdout when the tests are run
if (process.env.NODE_ENV !== 'test') {
  app.use(logger('dev'));
}

// *** cross domain requests *** //
const allowCrossDomain = function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE')
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization')
  next()
}

app.use(allowCrossDomain);

// require('dotenv').config()
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use('/api/v1/', routes)
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  let err = new Error('Not Found');
  err.status = 404;
  next(err);
});

if(app.get('env') === 'development' || app.get('env') === 'test') {
  app.use((err,req,res,next) => {
    console.log("error", err)
    res.status(err.status || 500)
    res.json({
      message: err.message,
      error: err
    })
  })
}

//default to production
app.use((err,req,res,next) => {
    console.log("error", err)
    res.status(err.status || 500)
    res.json({
      message: err.message,
      error: {}
    })
  })

const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`Listening on port ${port} in env: ${process.env.NODE_ENV}`);
});

module.exports = app;
<|endoftext|>


<commit_before>var express = require('express'),
    path = require('path'),
    fs = require('fs'),
    favicon = require('static-favicon'),
    logger = require('morgan'),
    cookieParser = require('cookie-parser'),
    bodyParser = require('body-parser'),
    _s = require('underscore.string'),
    moment = require('moment'),
    marked = require('marked'),
    validator = require('validator'),
    extend = require('extend'),
    raneto = require('raneto-core'),
    config = require('./config'),
    app = express();

// Setup views
app.set('views', path.join(__dirname, 'views'));
app.set('layout', 'layout');
app.set('view engine', 'html');
app.enable('view cache');
app.engine('html', require('hogan-express'));

// Setup Express
app.use(favicon(__dirname +'/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// Setup config
extend(raneto.config, config);

// Handle all requests
app.all('*', function(req, res, next) {
    if(req.query.search){
        var searchQuery = validator.toString(validator.escape(_s.stripTags(req.query.search))).trim(),
            searchResults = raneto.doSearch(searchQuery),
            pageListSearch = raneto.getPages('');

        return res.render('search', {
            config: config,
            pages: pageListSearch,
            search: searchQuery,
            searchResults: searchResults,
            body_class: 'page-search'
        });
    }
    else if(req.params[0]){
        var slug = req.params[0];
        if(slug == '/') slug = '/index';

        var pageList = raneto.getPages(slug),
            filePath = path.normalize(raneto.config.content_dir + slug);

        if(slug != '/index')
	    filePath = path.normalize(__basedir + "/content/" + slug);

	if(!fs.existsSync(filePath)) filePath += '.md';

        if(slug == '/index' && !fs.existsSync(filePath)){
            return res.render('home', {
                config: config,
                pages: pageList,
                body_class: 'page-home'
            });
        } else {
            fs.readFile(filePath, 'utf8', function(err, content) {
                if(err){
                    err.status = '404';
                    err.message = 'Whoops. Looks like this page doesn\'t exist.';
                    return next(err);
                }

                // Process Markdown files
                if(path.extname(filePath) == '.md'){
                    // File info
                    var stat = fs.lstatSync(filePath);
                    // Meta
                    var meta = raneto.processMeta(content);
                    content = raneto.stripMeta(content);
                    if(!meta.title) meta.title = raneto.slugToTitle(filePath);
                    // Content
                    content = raneto.processVars(content);
                    var html = marked(content);

                    return res.render('page', {
                        config: config,
                        pages: pageList,
                        meta: meta,
                        content: html,
                        body_class: 'page-'+ raneto.cleanString(slug),
                        last_modified: moment(stat.mtime).format('Do MMM YYYY')
                    });
                } else {
                    // Serve static file
                    res.sendfile(filePath);
                }
            });
        }
    } else {
        next();
    }
});

// Handle any errors
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        config: config,
        status: err.status,
        message: err.message,
        error: {},
        body_class: 'page-error'
    });
});

module.exports = app;
<commit_msg>more changes<commit_after>
var express = require('express'),
    path = require('path'),
    fs = require('fs'),
    favicon = require('static-favicon'),
    logger = require('morgan'),
    cookieParser = require('cookie-parser'),
    bodyParser = require('body-parser'),
    _s = require('underscore.string'),
    moment = require('moment'),
    marked = require('marked'),
    validator = require('validator'),
    extend = require('extend'),
    raneto = require('raneto-core'),
    config = require('./config'),
    app = express();

// Setup views
app.set('views', path.join(__dirname, 'views'));
app.set('layout', 'layout');
app.set('view engine', 'html');
app.enable('view cache');
app.engine('html', require('hogan-express'));

// Setup Express
app.use(favicon(__dirname +'/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// Setup config
extend(raneto.config, config);

// Handle all requests
app.all('*', function(req, res, next) {
    if(req.query.search){
        var searchQuery = validator.toString(validator.escape(_s.stripTags(req.query.search))).trim(),
            searchResults = raneto.doSearch(searchQuery),
            pageListSearch = raneto.getPages('');

        return res.render('search', {
            config: config,
            pages: pageListSearch,
            search: searchQuery,
            searchResults: searchResults,
            body_class: 'page-search'
        });
    }
    else if(req.params[0]){
        var slug = req.params[0];
        if(slug == '/') slug = '/index';

        var pageList = raneto.getPages(slug),
            filePath = path.resolve(raneto.config.content_dir + slug);

	if(!fs.existsSync(filePath)) filePath += '.md';

        if(slug == '/index' && !fs.existsSync(filePath)){
            return res.render('home', {
                config: config,
                pages: pageList,
                body_class: 'page-home'
            });
        } else {
            fs.readFile(filePath, 'utf8', function(err, content) {
                if(err){
                    err.status = '404';
                    err.message = 'Whoops. Looks like this page doesn\'t exist.';
                    return next(err);
                }

                // Process Markdown files
                if(path.extname(filePath) == '.md'){
                    // File info
                    var stat = fs.lstatSync(filePath);
                    // Meta
                    var meta = raneto.processMeta(content);
                    content = raneto.stripMeta(content);
                    if(!meta.title) meta.title = raneto.slugToTitle(filePath);
                    // Content
                    content = raneto.processVars(content);
                    var html = marked(content);

                    return res.render('page', {
                        config: config,
                        pages: pageList,
                        meta: meta,
                        content: html,
                        body_class: 'page-'+ raneto.cleanString(slug),
                        last_modified: moment(stat.mtime).format('Do MMM YYYY')
                    });
                } else {
                    // Serve static file
                    res.sendfile(filePath);
                }
            });
        }
    } else {
        next();
    }
});

// Handle any errors
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        config: config,
        status: err.status,
        message: err.message,
        error: {},
        body_class: 'page-error'
    });
});

module.exports = app;
<|endoftext|>


<commit_before>// Import the discord.js module
const Discord = require("discord.js")
const fs = require("fs")
var schedule = require("node-schedule")
var moment = require("moment")
var https = require ("https")
var crypto = require("crypto")
var glob = require("glob")
var path = require("path")
var tools = require("./tools")

const CHAN_ID_DKC_GENERAL = "349976478538268674";
const CHAN_ID_DKC_FLAAMLOGS = "350728940501073924"
const CHAN_ID_QGS_FLAAMCHAN = "330420560972742656"

var FLAAMBOT_KHRID_ID = process.env.FLAAMBOT_KHRID_ID
var FLAAMBOT_AERIN_ID = process.env.FLAAMBOT_AERIN_ID

var action = ""
var client = new Discord.Client();
var ext = ""

tools.client = client;
tools.CHAN_ID_DKC_FLAAMLOGS = CHAN_ID_DKC_FLAAMLOGS;

client.on("ready", () => {
	var revision = require("child_process")
	  .execSync("git rev-parse HEAD")
	  .toString().trim();
	var bootMessage = "";
	bootMessage += ":smirk_cat: Flaambot starting :smirk_cat:"+"\n"
	bootMessage += "rev : " + revision+"\n"
	bootMessage += "ready :heart_eyes_cat:"
	tools.sendToLogChannel(bootMessage)
	client.fetchUser(FLAAMBOT_KHRID_ID).then(user => {user.send("Flaambot (re)démarré !")})

	var rule = new schedule.RecurrenceRule()
    //rule.minute = 30
    //rule.hour = 6
    rule.second = 30

    var j = schedule.scheduleJob(rule, function() {

    	/**
		 * Processing what"s need to
		 */

    	glob("./images/today.*", function (err, files) {
    		//console.log(files[0].split(".").pop())
	    	fs.stat("./images/"+files, function(err, stat) {

	    		if(err == null) {
	    			filetime = moment(stat.birthtimeMs).format("YYYYMMDD");
	    			today = moment().format("YYYYMMDD");
	    			// today = moment(today).add(1, "days").format("YYYYMMDD");
	    			console.log(filetime + " - " + today)
	    			if(filetime < today) {
	    				action = "Replacing the picture"
	    				fs.rename("./images/"+files, "./images/used/"+files, function (err) {
	    					if(!err) {
	    						fs.readdir("./images/available/", function (err, files) {
	    							if(files.length > 0) {
	    								key = Math.floor(Math.random() * files.length)
	    								target = files[key]
	    								fs.rename("./images/available/"+target, "./images/"+target), function (success) {
	    									fs.stat("./images/"+target, function(err, stat) {
	    										if(err == null) {
	    											action = "today's pic updated"
	    										} else {
	    											action = ":scream_cat: Could not create today's pic :scream_cat:"
	    										}
	    									})
	    								}
	    								if(files.length < 2) {
	        		    					client.fetchUser(FLAAMBOT_KHRID_ID).then(user => {user.send("Il ne rest plus beaucoup de photos de Flaam :crying_cat_face:")})
	    								}
	    							} else {
	    								action = ":scream_cat: No more pics :scream_cat:";
	    		    					client.fetchUser(FLAAMBOT_KHRID_ID).then(user => {user.send(action)})
	    							}
	    						})
	    					} else {
	    						action = ":scream_cat: Could not move old today to used folder :scream_cat:"
	    					}
	    				})
	    			} else {
	    				action = "No need to change the picture yet"
	    			}
	    		} else {
	    			fs.readdir("./images/available/", function (err, files) {
	    				if(files.length > 0) {
	    					key = Math.floor(Math.random() * files.length)
	    					target = files[key]
	    					fs.rename("./images/available/"+target, "./images/"+target), function (success) {
	    						fs.stat("./images/"+target, function(err, stat) {
	    							if(err == null) {
	    								action = "today's pic updated"
	    							} else {
	    								action = ":scream_cat: Could not create today's pic :scream_cat:"
	    							}
	    						})
	    					}
	    				} else {
	    					action = ":scream_cat: No more pics :scream_cat:";
	    					client.fetchUser(FLAAMBOT_KHRID_ID).then(user => {user.send(action)})
	    				}
	    			})
	    		}
	        	tools.sendToLogChannel("Action : " + action);
	    	})
	        // client.channels.get(CHAN_ID_DKC_GENERAL).send("Testing change");
	        client.channels.get(CHAN_ID_DKC_GENERAL).send("Photo de Flaam du jour :heart_eyes_cat:", {
	            files: [
	              "./images/"+files
	            ]
	          });
    	})
    });
});

// Create an event listener for messages
client.on("message", message => {

	if(message.author.id == FLAAMBOT_KHRID_ID || message.author.id == FLAAMBOT_AERIN_ID) {
		if(message.attachments.size > 0) {
			if(message.attachments.size < 2) {
				if(message.attachments.first().filename.endsWith(".jpg")
						|| message.attachments.first().filename.endsWith(".png")
						|| message.attachments.first().filename.endsWith(".gif")) {
					var newFile = crypto.randomBytes(20).toString("hex")+"."+message.attachments.first().filename.split(".").pop()
					var download = function(url, dest, cb) {
					  var file = fs.createWriteStream(dest);
					  var request = https.get(url, function(response) {
					    response.pipe(file);
					    file.on("finish", function() {
					      file.close(cb);  // close() is async, call cb after close completes.
					      fs.stat("./images/available/"+newFile, function(err, stat) {
					    		if(err == null) {
					    			message.channel.send("Photo ajoutée !", {
					    	            files: [
					    	            	"./images/available/"+newFile
					    	            ]
					    	          });

					            	tools.sendImageToLogChannel("New pic uploaded ("+newFile+")", "./images/available/"+newFile);
					    		}
					    })
					    });
					  }).on("error", function(err) { // Handle errors
					    fs.unlink(dest); // Delete the file async. (But we don"t check the result)
					    if (cb) cb(err.message);
					    console.log(err.message);
					  });
					};
					download(message.attachments.first().url, "./images/available/"+newFile, null);
				} else {
					message.channel.send("Format d\'image pas supporté :smile_cat:");
				}
			} else {
				message.channel.send("Une à la fois :smile_cat:");
			}
		}
	}
});

// Log our bot in
client.login(process.env.FLAAMBOT_DISCORD_TOKEN);
<commit_msg>image ou opas<commit_after>// Import the discord.js module
const Discord = require("discord.js")
const fs = require("fs")
var schedule = require("node-schedule")
var moment = require("moment")
var https = require ("https")
var crypto = require("crypto")
var glob = require("glob")
var path = require("path")
var tools = require("./tools")

const CHAN_ID_DKC_GENERAL = "349976478538268674";
const CHAN_ID_DKC_FLAAMLOGS = "350728940501073924"
const CHAN_ID_QGS_FLAAMCHAN = "330420560972742656"

var FLAAMBOT_KHRID_ID = process.env.FLAAMBOT_KHRID_ID
var FLAAMBOT_AERIN_ID = process.env.FLAAMBOT_AERIN_ID

var action = ""
var client = new Discord.Client();
var ext = ""

tools.client = client;
tools.CHAN_ID_DKC_FLAAMLOGS = CHAN_ID_DKC_FLAAMLOGS;

client.on("ready", () => {
	var revision = require("child_process")
	  .execSync("git rev-parse HEAD")
	  .toString().trim();
	var bootMessage = "";
	bootMessage += ":smirk_cat: Flaambot starting :smirk_cat:"+"\n"
	bootMessage += "rev : " + revision+"\n"
	bootMessage += "ready :heart_eyes_cat:"
	tools.sendToLogChannel(bootMessage)
	client.fetchUser(FLAAMBOT_KHRID_ID).then(user => {user.send("Flaambot (re)démarré !")})

	var rule = new schedule.RecurrenceRule()
    //rule.minute = 30
    //rule.hour = 6
    rule.second = 30

    var j = schedule.scheduleJob(rule, function() {

    	/**
		 * Processing what"s need to
		 */

    	glob("./images/today.*", function (err, files) {
    		console.log(files[0])
	    	fs.stat("./images/"+files, function(err, stat) {

	    		if(err == null) {
	    			filetime = moment(stat.birthtimeMs).format("YYYYMMDD");
	    			today = moment().format("YYYYMMDD");
	    			// today = moment(today).add(1, "days").format("YYYYMMDD");
	    			console.log(filetime + " - " + today)
	    			if(filetime < today) {
	    				action = "Replacing the picture"
	    				fs.rename("./images/"+files, "./images/used/"+files, function (err) {
	    					if(!err) {
	    						fs.readdir("./images/available/", function (err, files) {
	    							if(files.length > 0) {
	    								key = Math.floor(Math.random() * files.length)
	    								target = files[key]
	    								fs.rename("./images/available/"+target, "./images/"+target), function (success) {
	    									fs.stat("./images/"+target, function(err, stat) {
	    										if(err == null) {
	    											action = "today's pic updated"
	    										} else {
	    											action = ":scream_cat: Could not create today's pic :scream_cat:"
	    										}
	    									})
	    								}
	    								if(files.length < 2) {
	        		    					client.fetchUser(FLAAMBOT_KHRID_ID).then(user => {user.send("Il ne rest plus beaucoup de photos de Flaam :crying_cat_face:")})
	    								}
	    							} else {
	    								action = ":scream_cat: No more pics :scream_cat:";
	    		    					client.fetchUser(FLAAMBOT_KHRID_ID).then(user => {user.send(action)})
	    							}
	    						})
	    					} else {
	    						action = ":scream_cat: Could not move old today to used folder :scream_cat:"
	    					}
	    				})
	    			} else {
	    				action = "No need to change the picture yet"
	    			}
	    		} else {
	    			fs.readdir("./images/available/", function (err, files) {
	    				if(files.length > 0) {
	    					key = Math.floor(Math.random() * files.length)
	    					target = files[key]
	    					fs.rename("./images/available/"+target, "./images/"+target), function (success) {
	    						fs.stat("./images/"+target, function(err, stat) {
	    							if(err == null) {
	    								action = "today's pic updated"
	    							} else {
	    								action = ":scream_cat: Could not create today's pic :scream_cat:"
	    							}
	    						})
	    					}
	    				} else {
	    					action = ":scream_cat: No more pics :scream_cat:";
	    					client.fetchUser(FLAAMBOT_KHRID_ID).then(user => {user.send(action)})
	    				}
	    			})
	    		}
	        	tools.sendToLogChannel("Action : " + action);
	    	})
	        // client.channels.get(CHAN_ID_DKC_GENERAL).send("Testing change");
	        client.channels.get(CHAN_ID_DKC_GENERAL).send("Photo de Flaam du jour :heart_eyes_cat:", {
	            files: [
	              "./images/"+files
	            ]
	          });
    	})
    });
});

// Create an event listener for messages
client.on("message", message => {

	if(message.author.id == FLAAMBOT_KHRID_ID || message.author.id == FLAAMBOT_AERIN_ID) {
		if(message.attachments.size > 0) {
			if(message.attachments.size < 2) {
				if(message.attachments.first().filename.endsWith(".jpg")
						|| message.attachments.first().filename.endsWith(".png")
						|| message.attachments.first().filename.endsWith(".gif")) {
					var newFile = crypto.randomBytes(20).toString("hex")+"."+message.attachments.first().filename.split(".").pop()
					var download = function(url, dest, cb) {
					  var file = fs.createWriteStream(dest);
					  var request = https.get(url, function(response) {
					    response.pipe(file);
					    file.on("finish", function() {
					      file.close(cb);  // close() is async, call cb after close completes.
					      fs.stat("./images/available/"+newFile, function(err, stat) {
					    		if(err == null) {
					    			message.channel.send("Photo ajoutée !", {
					    	            files: [
					    	            	"./images/available/"+newFile
					    	            ]
					    	          });

					            	tools.sendImageToLogChannel("New pic uploaded ("+newFile+")", "./images/available/"+newFile);
					    		}
					    })
					    });
					  }).on("error", function(err) { // Handle errors
					    fs.unlink(dest); // Delete the file async. (But we don"t check the result)
					    if (cb) cb(err.message);
					    console.log(err.message);
					  });
					};
					download(message.attachments.first().url, "./images/available/"+newFile, null);
				} else {
					message.channel.send("Format d\'image pas supporté :smile_cat:");
				}
			} else {
				message.channel.send("Une à la fois :smile_cat:");
			}
		}
	}
});

// Log our bot in
client.login(process.env.FLAAMBOT_DISCORD_TOKEN);
<|endoftext|>


<commit_before>var config  = require('./config')
var app     = require('http').createServer(wrapper)
var qs      = require('querystring')
var mongo   = require('mongodb')
var request = require('request')

var db = new mongo.Db( config.mongo.db
                     , new mongo.Server( config.mongo.host
                                       , 27017
                                       , {auto_reconnect: true} )
                     , {w: 0} )                             // TODO: change safety params!

function wrapper(req, res) {
  try {
    return handler(req, res)
  } catch(err) {
    return onError('Borked request', err)
  }
}

function handler (req, res) {
  var body = ''
  var appjson = {'Content-Type': 'application/json'}
  var status = function(str) {return JSON.stringify({'status': str})}

  log('req.url: ', req.url)

  req.on('data', function(chunk) {
    body += chunk
    if(body.length > 5E6) req.connection.destroy()          // 5MB-ish
  })

  req.on('end', function() {
    if(req.method == 'GET') {
      res.writeHead(200, 'OK', appjson)
      res.end(status('ok'))
      return false
    }

    var post = qs.parse(body)

    log('post', post)

    if(!post) {
      onError('Invalid request', post)
      res.writeHead(400, 'OK', appjson)
      res.end(status('Invalid POST request'))
      return false
    }

    function cb() {
      post['_id'] = 1
      edit_the_data_okay('rmdata', post)

      res.writeHead(200, 'OK', appjson)
      res.end()
    }

    add('rmhistory', post, cb)

  })
}

function edit_the_data_okay(collection, item) {
  try {
    db.collection(collection, function(err, c) {

      c.save(item)

    })
  } catch (err) {
    onError('Edit error', err)
  }
}

function add(collection, item, cb) {
  try {
    db.collection(collection, function(err, c) {

      if(!item || !Object.keys(item).length) {
        onError('Invalid item found!!!', item)
        return cb()
      }

      log('added: ', item)

      c.save(item)

      return cb(item)

    })
  } catch (err) {
    onError('Insertion error', err)
    return cb()
  }
}

function onError() {
  log('ERROR!', arguments)
}

function log() {
  if(config.logit) {
    console.log(JSON.stringify([].slice.call(arguments), 0, 2))
  }
}

db.open(function(err, db) {
  if(err)
    return onError('DB refused to open', err)

  if(config.mongo.username) {
    db.authenticate(config.mongo.username, config.mongo.password, function(err, result) {
      app.listen(config.port)
    })
  } else {
    app.listen(config.port)
  }
})
<commit_msg>add CORS headers<commit_after>var config  = require('./config')
var app     = require('http').createServer(wrapper)
var qs      = require('querystring')
var mongo   = require('mongodb')
var request = require('request')

var db = new mongo.Db( config.mongo.db
                     , new mongo.Server( config.mongo.host
                                       , 27017
                                       , {auto_reconnect: true} )
                     , {w: 0} )                             // TODO: change safety params!

function wrapper(req, res) {
  try {
    return handler(req, res)
  } catch(err) {
    return onError('Borked request', err)
  }
}

function handler (req, res) {
  var body = ''
  var appjson = {'Content-Type': 'application/json'}
  var status = function(str) {return JSON.stringify({'status': str})}

  log('req.url: ', req.url)

  // yuck make this less horrible
  res.setHeader('Access-Control-Allow-Origin', '*')
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE, CONNECT')
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept')
  res.setHeader('Access-Control-Allow-Credentials', true)
  res.setHeader('Access-Control-Max-Age', '86400') // 24 hours

  req.on('data', function(chunk) {
    body += chunk
    if(body.length > 5E6) req.connection.destroy()          // 5MB-ish
  })

  req.on('end', function() {
    if(req.method == 'GET') {
      res.writeHead(200, 'OK', appjson)
      res.end(status('ok'))
      return false
    }

    var post = qs.parse(body)

    log('post', post)

    if(!post) {
      onError('Invalid request', post)
      res.writeHead(400, 'OK', appjson)
      res.end(status('Invalid POST request'))
      return false
    }

    function cb() {
      post['_id'] = 1
      edit_the_data_okay('rmdata', post)

      res.writeHead(200, 'OK', appjson)
      res.end()
    }

    add('rmhistory', post, cb)

  })
}

function edit_the_data_okay(collection, item) {
  try {
    db.collection(collection, function(err, c) {

      c.save(item)

    })
  } catch (err) {
    onError('Edit error', err)
  }
}

function add(collection, item, cb) {
  try {
    db.collection(collection, function(err, c) {

      if(!item || !Object.keys(item).length) {
        onError('Invalid item found!!!', item)
        return cb()
      }

      log('added: ', item)

      c.save(item)

      return cb(item)

    })
  } catch (err) {
    onError('Insertion error', err)
    return cb()
  }
}

function onError() {
  log('ERROR!', arguments)
}

function log() {
  if(config.logit) {
    console.log(JSON.stringify([].slice.call(arguments), 0, 2))
  }
}

db.open(function(err, db) {
  if(err)
    return onError('DB refused to open', err)

  if(config.mongo.username) {
    db.authenticate(config.mongo.username, config.mongo.password, function(err, result) {
      app.listen(config.port)
    })
  } else {
    app.listen(config.port)
  }
})
<|endoftext|>


<commit_before>import { Template } from 'meteor/templating';
import { Recipes } from '/imports/api/recipe/RecipeCollection';
import { Tags } from '/imports/api/tag/TagCollection';
import { _ } from 'meteor/underscore';
import { Meteor } from 'meteor/meteor';
import { ReactiveVar } from 'meteor/reactive-var';

Template.Home_Page.onCreated(function onCreated() {
  this.subscribe(Tags.getPublicationName());
  this.subscribe(Recipes.getPublicationName());
  this.dataUrl = new ReactiveVar();
});

Template.Home_Page.helpers({

  /**
   * Produces top recipes for the homepage
   *
   */
  top_recipes() {
    return _.sample(Recipes.find({}, { sort: { viewcount: -1, limit: 16 } }).fetch(), 6);
  },

  /**
   * Produces top tags for homepage
   *
   */
  top_tags() {
    const allTags = Tags.find({}, { fields: { tagName: 1 } }).fetch();
    const namesOnly = _.pluck(_.values(allTags), 'tagName');
    const frequency = _.countBy(namesOnly, function (each) { return each; });
    const result = _.first(_.sortBy(_.uniq(namesOnly),
        function (frequencyKey) { return -frequency[frequencyKey]; }), 8);
    return result;
  },

  /**
   * Produces image for a tag
   *
   */
  load_tag_image(theTagName) {
    const recipesWithTag = Tags.find({ tagName: theTagName }, { fields: { recipeID: 1 } }).fetch();
    const randomRecipe = _.sample(recipesWithTag);
    return Recipes.find({ recipeID: randomRecipe.recipeID }, {}).fetch();
  },

  /**
   * Produces tags for a recipe
   *
   */
  recipe_tag(theRecipeID) {
    return Tags.find({ recipeID: theRecipeID }, {}).fetch();
  },

  convert_publish_date(publishDate) {
    const date = new Date(0);
    date.setUTCSeconds(publishDate);
    return date.toLocaleDateString();
  },

  get_recipe_url(recipeID) {
    return `/recipe/${recipeID}/view`;
  },
});

Template.Home_Page.events({
  'submit .search-recipe'(event) {
    // Prevent default browser form submit
    event.preventDefault();

    // Get value from form element
    const target = event.target;
    const text = target.text.value;
    window.location.replace(`search/${text}/view`);
    // Clear form
    target.text.value = '';
  },
  "change input[type='file']":function(event,template){
    var files=event.target.files;
    if(files.length===0){
      return;
    }
    var file=files[0];
    //
    var fileReader=new FileReader();
    fileReader.onload=function(event){
      var dataUrl=event.target.result;
      template.dataUrl.set(dataUrl);
    };
    fileReader.readAsDataURL(file);
  },
  'submit .test-imgur'(event, template) {
    event.preventDefault();
    const image = template.dataUrl.get();
    Imgur.upload({
      image: image,
      apiKey: Meteor.settings.public.ClientID,
    }, function (error, data) {
      if (error) {
        throw error;
      } else {
        console.log(data.link);
      }
    });
  },
});
<commit_msg>Add some comments about using the imgur upload and fix eslint errors<commit_after>import { Template } from 'meteor/templating';
import { Recipes } from '/imports/api/recipe/RecipeCollection';
import { Tags } from '/imports/api/tag/TagCollection';
import { _ } from 'meteor/underscore';
import { Meteor } from 'meteor/meteor';
import { ReactiveVar } from 'meteor/reactive-var';

/* eslint-disable no-undef, object-shorthand, no-shadow*/

Template.Home_Page.onCreated(function onCreated() {
  this.subscribe(Tags.getPublicationName());
  this.subscribe(Recipes.getPublicationName());
  /* IMGUR UPLOAD REACTIVE VARIABLE */
  this.dataUrl = new ReactiveVar();
});

Template.Home_Page.helpers({

  /**
   * Produces top recipes for the homepage
   *
   */
  top_recipes() {
    return _.sample(Recipes.find({}, { sort: { viewcount: -1, limit: 16 } }).fetch(), 6);
  },

  /**
   * Produces top tags for homepage
   *
   */
  top_tags() {
    const allTags = Tags.find({}, { fields: { tagName: 1 } }).fetch();
    const namesOnly = _.pluck(_.values(allTags), 'tagName');
    const frequency = _.countBy(namesOnly, function each(each) { return each; });
    const result = _.first(_.sortBy(_.uniq(namesOnly),
        function frequencyKey(frequencyKey) { return -frequency[frequencyKey]; }), 8);
    return result;
  },

  /**
   * Produces image for a tag
   *
   */
  load_tag_image(theTagName) {
    const recipesWithTag = Tags.find({ tagName: theTagName }, { fields: { recipeID: 1 } }).fetch();
    const randomRecipe = _.sample(recipesWithTag);
    return Recipes.find({ recipeID: randomRecipe.recipeID }, {}).fetch();
  },

  /**
   * Produces tags for a recipe
   *
   */
  recipe_tag(theRecipeID) {
    return Tags.find({ recipeID: theRecipeID }, {}).fetch();
  },

  convert_publish_date(publishDate) {
    const date = new Date(0);
    date.setUTCSeconds(publishDate);
    return date.toLocaleDateString();
  },

  get_recipe_url(recipeID) {
    return `/recipe/${recipeID}/view`;
  },
});

Template.Home_Page.events({
  'submit .search-recipe'(event) {
    // Prevent default browser form submit
    event.preventDefault();

    // Get value from form element
    const target = event.target;
    const text = target.text.value;
    window.location.replace(`search/${text}/view`);
    // Clear form
    target.text.value = '';
  },
  /* IMGUR UPLOAD EVENTS */
  "change input[type='file']": function upload(event, instance) {
    const files = event.target.files;
    if (files.length === 0) {
      return;
    }
    const file = files[0];
    //
    const fileReader = new FileReader();
    fileReader.onload = function onload(event) {
      const dataUrl = event.target.result;
      instance.dataUrl.set(dataUrl);
    };
    fileReader.readAsDataURL(file);
  },
  'submit .test-imgur'(event, instance) {
    event.preventDefault();
    const image = instance.dataUrl.get();
    Imgur.upload({
      image: image,
      apiKey: Meteor.settings.public.ClientID,
    }, function error(error, data) {
      if (error) {
        throw error;
      } else {
        console.log(data.link); /* Do things with the link here (replace console.log) */
      }
    });
  },
  /* END IMGUR UPLOAD EVENTS */
});
<|endoftext|>


<commit_before>//
// Tools for performance debugging, only enabled in development mode.
// Open up Chrome Dev Tools, then Timeline, then User Timing to see output.
// Also see config/webpack/loaders/mark.js for the webpack loader marks.
//

let marky;

if (process.env.NODE_ENV === 'development') {
  marky = require('marky');
  require('react-addons-perf').start();
}

export function start(name) {
  if (process.env.NODE_ENV === 'development') {
    marky.mark(name);
  }
}

export function stop(name) {
  if (process.env.NODE_ENV === 'development') {
    marky.stop(name);
  }
}
<commit_msg>Fix Firefox issue with performance marks (#3315)<commit_after>//
// Tools for performance debugging, only enabled in development mode.
// Open up Chrome Dev Tools, then Timeline, then User Timing to see output.
// Also see config/webpack/loaders/mark.js for the webpack loader marks.
//

let marky;

if (process.env.NODE_ENV === 'development') {
  if (typeof performance !== 'undefined' && performance.setResourceTimingBufferSize) {
    // Increase Firefox's performance entry limit; otherwise it's capped to 150.
    // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1331135
    performance.setResourceTimingBufferSize(Infinity);
  }
  marky = require('marky');
  require('react-addons-perf').start();
}

export function start(name) {
  if (process.env.NODE_ENV === 'development') {
    marky.mark(name);
  }
}

export function stop(name) {
  if (process.env.NODE_ENV === 'development') {
    marky.stop(name);
  }
}
<|endoftext|>


<commit_before>import axios from 'axios';

const DATASET = process.env.COUNTRIES_PAGE_DATASET;
const REQUEST_URL = `${process.env.GFW_API_HOST_PROD}/query/${DATASET}?sql=`;
const CARTO_REQUEST_URL = `${process.env.CARTO_API_URL}/sql?q=`;

const SQL_QUERIES = {
  extent:
    "SELECT SUM({extentYear}) as value, SUM(area_gadm28) as total_area FROM data WHERE {location} AND thresh = {threshold} AND polyname = '{indicator}'",
  plantationsExtent:
    "SELECT SUM({extentYear}) AS plantation_extent FROM data WHERE {location} AND thresh = {threshold} AND polyname = 'plantations' GROUP BY {type} ORDER BY plantation_extent DESC",
  gain:
    "SELECT {calc} as value FROM data WHERE {location} AND polyname = '{indicator}' AND thresh = {threshold}",
  gainExtent:
    "SELECT {region} as region, SUM(area_gain) AS gain, SUM({extentYear}) AS extent FROM data WHERE {location} AND polyname = '{polyname}' AND extent <> -9999 AND thresh = 0 GROUP BY region",
  loss:
    "SELECT polyname, year_data.year as year, SUM(year_data.area_loss) as area, SUM(year_data.emissions) as emissions FROM data WHERE polyname = '{indicator}' AND {location} AND thresh= {threshold} GROUP BY polyname, iso, nested(year_data.year)",
  locations:
    "SELECT {location} as region, {extentYear} as extent, {extent} as total FROM data WHERE iso = '{iso}' AND thresh = {threshold} AND polyname = '{indicator}' {grouping}",
  fao:
    "SELECT fao.iso, fao.name, forest_planted, forest_primary, forest_regenerated, fao.forest_primary, fao.extent, a.land as area_ha FROM gfw2_countries as fao INNER JOIN umd_nat_staging as a ON fao.iso = a.iso WHERE fao.forest_primary is not null AND fao.iso = '{country}' AND a.year = 2001 AND a.thresh = 30",
  faoExtent:
    'SELECT country AS iso, name, year, reforest AS rate, forest*1000 AS extent FROM table_1_forest_area_and_characteristics as fao WHERE fao.year = {period} AND reforest > 0 ORDER BY rate DESC'
};

const getExtentYear = year =>
  (year === 2000 ? 'area_extent_2000' : 'area_extent');

const getLocationQuery = (country, region, subRegion) =>
  `iso = '${country}'${region ? ` AND adm1 = ${region}` : ''}${
    subRegion ? ` AND adm2 = ${subRegion}` : ''
  }`;

export const getLocations = ({
  country,
  region,
  indicator,
  threshold,
  extentYear
}) => {
  const url = `${REQUEST_URL}${SQL_QUERIES.locations}`
    .replace('{location}', region ? 'adm2' : 'adm1')
    .replace(
      '{extentYear}',
      `${!region ? 'sum(' : ''}${getExtentYear(extentYear)}${
        !region ? ')' : ''
      }`
    )
    .replace('{extent}', region ? 'area_gadm28' : 'sum(area_gadm28)')
    .replace('{iso}', country)
    .replace('{threshold}', threshold)
    .replace('{indicator}', indicator)
    .replace('{grouping}', region ? `AND adm1 = '${region}'` : 'GROUP BY adm1');
  return axios.get(url);
};

export const getExtent = ({
  country,
  region,
  subRegion,
  indicator,
  threshold,
  extentYear
}) => {
  const url = `${REQUEST_URL}${SQL_QUERIES.extent}`
    .replace('{location}', getLocationQuery(country, region, subRegion))
    .replace('{threshold}', threshold)
    .replace('{indicator}', indicator)
    .replace(
      '{extentYear}',
      `area_extent${extentYear === 2000 ? `_${extentYear}` : ''}`
    );
  return axios.get(url);
};

export const getPlantationsExtent = ({
  country,
  region,
  subRegion,
  threshold,
  extentYear,
  type
}) => {
  const url = `${REQUEST_URL}${SQL_QUERIES.plantationsExtent}`
    .replace('{location}', getLocationQuery(country, region, subRegion))
    .replace('{threshold}', threshold)
    .replace('{type}', type)
    .replace(
      '{extentYear}',
      `area_extent${extentYear === 2000 ? `_${extentYear}` : ''}`
    );
  return axios.get(url);
};

export const getGain = ({
  country,
  region,
  subRegion,
  indicator,
  threshold
}) => {
  const url = `${REQUEST_URL}${SQL_QUERIES.gain}`
    .replace('{location}', getLocationQuery(country, region, subRegion))
    .replace('{threshold}', threshold)
    .replace('{calc}', region ? 'area_gain' : 'SUM(area_gain)')
    .replace('{indicator}', indicator);
  return axios.get(url);
};

export const getLoss = ({
  country,
  region,
  subRegion,
  indicator,
  threshold
}) => {
  const url = `${REQUEST_URL}${SQL_QUERIES.loss}`
    .replace('{location}', getLocationQuery(country, region, subRegion))
    .replace('{threshold}', threshold)
    .replace('{indicator}', indicator);
  return axios.get(url);
};

export const getFAO = ({ country }) => {
  const url = `${CARTO_REQUEST_URL}${SQL_QUERIES.fao}`.replace(
    '{country}',
    country
  );
  return axios.get(url);
};

export const getFAOExtent = ({ period }) => {
  const url = `${CARTO_REQUEST_URL}${SQL_QUERIES.faoExtent}`.replace(
    '{period}',
    period
  );
  return axios.get(url);
};

export const getGainExtent = ({
  country,
  region,
  subRegion,
  indicator,
  extentYear
}) => {
  let regionValue = 'iso';
  if (subRegion) {
    regionValue = 'adm2';
  } else if (region) {
    regionValue = 'adm1';
  }

  const location = region
    ? `iso = '${country}' ${subRegion ? `AND adm1 = ${region}` : ''}`
    : '1 = 1';

  const url = `${REQUEST_URL}${SQL_QUERIES.gainExtent}`
    .replace('{region}', regionValue)
    .replace('{location}', location)
    .replace(
      '{extentYear}',
      extentYear === 2000 ? 'area_extent_2000' : 'area_extent'
    )
    .replace('{polyname}', indicator);
  return axios.get(url);
};
<commit_msg>resolve conflicts<commit_after>import axios from 'axios';

const DATASET = process.env.COUNTRIES_PAGE_DATASET;
const REQUEST_URL = `${process.env.GFW_API_HOST_PROD}/query/${DATASET}?sql=`;
const CARTO_REQUEST_URL = `${process.env.CARTO_API_URL}/sql?q=`;

const SQL_QUERIES = {
  extent:
    "SELECT {region} as region, SUM({extentYear}) as value, SUM(area_gadm28) as total_area FROM data WHERE {location} AND thresh = {threshold} AND polyname = '{indicator}' {groupBy}",
  gain:
    "SELECT {calc} as value FROM data WHERE {location} AND polyname = '{indicator}' AND thresh = {threshold}",
  gainExtent:
    "SELECT {region} as region, SUM(area_gain) AS gain, SUM({extentYear}) AS extent FROM data WHERE {location} AND polyname = '{polyname}' AND extent <> -9999 AND thresh = 0 GROUP BY region",
  loss:
    "SELECT polyname, year_data.year as year, SUM(year_data.area_loss) as area, SUM(year_data.emissions) as emissions FROM data WHERE polyname = '{indicator}' AND {location} AND thresh= {threshold} GROUP BY polyname, iso, nested(year_data.year)",
  locations:
    "SELECT {location} as region, {extentYear} as extent, {extent} as total FROM data WHERE iso = '{iso}' AND thresh = {threshold} AND polyname = '{indicator}' {grouping}",
  fao:
    "SELECT fao.iso, fao.name, forest_planted, forest_primary, forest_regenerated, fao.forest_primary, fao.extent, a.land as area_ha FROM gfw2_countries as fao INNER JOIN umd_nat_staging as a ON fao.iso = a.iso WHERE fao.forest_primary is not null AND fao.iso = '{country}' AND a.year = 2001 AND a.thresh = 30",
  faoExtent:
    'SELECT country AS iso, name, year, reforest AS rate, forest*1000 AS extent FROM table_1_forest_area_and_characteristics as fao WHERE fao.year = {period} AND reforest > 0 ORDER BY rate DESC'
};

const getExtentYear = year =>
  (year === 2000 ? 'area_extent_2000' : 'area_extent');

const getLocationQuery = (country, region, subRegion) =>
  `iso = '${country}'${region ? ` AND adm1 = ${region}` : ''}${
    subRegion ? ` AND adm2 = ${subRegion}` : ''
  }`;
const getRegionQuery = (region, subRegion) => {
  if (subRegion) {
    return 'adm2';
  } else if (region) {
    return 'adm1';
  }
  return 'iso';
};

export const getLocations = ({
  country,
  region,
  indicator,
  threshold,
  extentYear
}) => {
  const url = `${REQUEST_URL}${SQL_QUERIES.locations}`
    .replace('{location}', region ? 'adm2' : 'adm1')
    .replace(
      '{extentYear}',
      `${!region ? 'sum(' : ''}${getExtentYear(extentYear)}${
        !region ? ')' : ''
      }`
    )
    .replace('{extent}', region ? 'area_gadm28' : 'sum(area_gadm28)')
    .replace('{iso}', country)
    .replace('{threshold}', threshold)
    .replace('{indicator}', indicator)
    .replace('{grouping}', region ? `AND adm1 = '${region}'` : 'GROUP BY adm1');
  return axios.get(url);
};

export const getExtent = ({
  country,
  region,
  subRegion,
  indicator,
  threshold,
  extentYear,
  groupBy
}) => {
  const regionValue = getRegionQuery(region, subRegion);

  const url = `${REQUEST_URL}${SQL_QUERIES.extent}`
    .replace('{region}', regionValue)
    .replace('{location}', getLocationQuery(country, region, subRegion))
    .replace('{threshold}', threshold)
    .replace('{indicator}', indicator)
    .replace(
      '{extentYear}',
      `area_extent${extentYear === 2000 ? `_${extentYear}` : ''}`
    )
    .replace(
      '{groupBy}',
      groupBy ? `GROUP BY ${regionValue} ORDER BY ${regionValue}` : ''
    );

  return axios.get(url);
};

export const getGain = ({
  country,
  region,
  subRegion,
  indicator,
  threshold
}) => {
  const url = `${REQUEST_URL}${SQL_QUERIES.gain}`
    .replace('{location}', getLocationQuery(country, region, subRegion))
    .replace('{threshold}', threshold)
    .replace('{calc}', region ? 'area_gain' : 'SUM(area_gain)')
    .replace('{indicator}', indicator);
  return axios.get(url);
};

export const getLoss = ({
  country,
  region,
  subRegion,
  indicator,
  threshold
}) => {
  const url = `${REQUEST_URL}${SQL_QUERIES.loss}`
    .replace('{location}', getLocationQuery(country, region, subRegion))
    .replace('{threshold}', threshold)
    .replace('{indicator}', indicator);
  return axios.get(url);
};

export const getFAO = ({ country }) => {
  const url = `${CARTO_REQUEST_URL}${SQL_QUERIES.fao}`.replace(
    '{country}',
    country
  );
  return axios.get(url);
};

export const getFAOExtent = ({ period }) => {
  const url = `${CARTO_REQUEST_URL}${SQL_QUERIES.faoExtent}`.replace(
    '{period}',
    period
  );
  return axios.get(url);
};

export const getGainExtent = ({
  country,
  region,
  subRegion,
  indicator,
  extentYear
}) => {
  const location = region
    ? `iso = '${country}' ${subRegion ? `AND adm1 = ${region}` : ''}`
    : '1 = 1';

  const url = `${REQUEST_URL}${SQL_QUERIES.gainExtent}`
    .replace('{region}', getRegionQuery(region, subRegion))
    .replace('{location}', location)
    .replace(
      '{extentYear}',
      extentYear === 2000 ? 'area_extent_2000' : 'area_extent'
    )
    .replace('{polyname}', indicator);
  return axios.get(url);
};
<|endoftext|>


<commit_before>soundcloudPlayer.ng.controller('playerController', ['$scope', '$http', '$log', function ($scope, $http, $log) {
	$log.info('[playerController] Ctrl Loaded');

	$scope.clientId = '6aeca16577b6acfd3e76ab35ac241d81';
	$scope.url = 'http://api.soundcloud.com/tracks.json?q=';
	$scope.trackList = [];
	$scope.data = {};
	$scope.currentIndex = 0;

	$scope.formSubmitted = false;
	$scope.formSuccess = false;
	$scope.status = null;

	var audioPlayer = document.getElementsByTagName('audio')[0];

	$scope.init = (function () {
		SC.initialize({
			client_id: $scope.clientId
		});

	})();

	$scope.submitForm = function () {
		$scope.formSubmitted = true;
		$scope.encodedString = encodeURI($scope.searchQuery);

		$scope.querySoundcloud();
	};

	$scope.querySoundcloud = function () {

		$http.jsonp($scope.url + $scope.encodedString + '&client_id=' + $scope.clientId + '&callback=JSON_CALLBACK').
		success($scope.processSoundcloudData).
		error (function (data, status) {
			$scope.data = data || "Request Failed";
			$scope.status = status;
		});
	};

	$scope.processSoundcloudData = function(data) {
		$scope.formSuccess = true;
		$scope.data = data;

		$scope.data.forEach (function (track) {
			var uri = track.uri + '/stream?client_id=' + $scope.clientId;

			$scope.trackList.unshift({
				title: track.title,
				uri: uri
			});
		});

		$scope.addTrackToPlayer();
	};

	$scope.addTrackToPlayer = function () {
		audioPlayer.setAttribute('src', $scope.trackList[$scope.currentIndex].uri);
	};

	audioPlayer.addEventListener('error', function (e) {
		$scope.nextSong();
		$scope.addTrackToPlayer();
	});

	audioPlayer.addEventListener('ended', function (e) {
		$log.info('[playerCtrl] Song Ended');

		$scope.nextSong();
		$scope.addTrackToPlayer();
	});

	$scope.nextSong = function () {
		++$scope.currentIndex;
	};

}]);
<commit_msg>cleaning up<commit_after>soundcloudPlayer.ng.controller('playerController', ['$scope', '$http', '$log', function ($scope, $http, $log) {
	$log.info('[playerCtrl] Ctrl Loaded');

	$scope.clientId = '6aeca16577b6acfd3e76ab35ac241d81';
	$scope.url = 'http://api.soundcloud.com/tracks.json?q=';
	$scope.trackList = [];
	$scope.data = {};
	$scope.currentIndex = 0;

	$scope.formSubmitted = false;
	$scope.formSuccess = false;
	$scope.status = null;

	var audioPlayer = document.getElementsByTagName('audio')[0];

	$scope.init = (function () {
		SC.initialize({
			client_id: $scope.clientId
		});

	})();

	$scope.submitForm = function () {
		$scope.formSubmitted = true;
		$scope.encodedString = encodeURI($scope.searchQuery);

		$scope.querySoundcloud();
	};

	$scope.querySoundcloud = function () {

		$http.jsonp($scope.url + $scope.encodedString + '&client_id=' + $scope.clientId + '&callback=JSON_CALLBACK').
		success($scope.processSoundcloudData).
		error (function (data, status) {
			$scope.data = data || "Request Failed";
			$scope.status = status;
		});
	};

	$scope.processSoundcloudData = function(data) {
		$scope.formSuccess = true;
		$scope.data = data;

		$scope.data.forEach (function (track) {
			var uri = track.uri + '/stream?client_id=' + $scope.clientId;

			$scope.trackList.unshift({
				title: track.title,
				uri: uri
			});
		});

		$scope.addTrackToPlayer();
	};

	$scope.addTrackToPlayer = function () {
		audioPlayer.setAttribute('src', $scope.trackList[$scope.currentIndex].uri);
	};

	$scope.nextSong = function () {
		++$scope.currentIndex;
	};

	audioPlayer.addEventListener('error', function (e) {
		$log.error('[playerCtrl] Song Error');

		$scope.nextSong();
		$scope.addTrackToPlayer();
	});

	audioPlayer.addEventListener('ended', function (e) {
		$log.info('[playerCtrl] Song Ended');

		$scope.nextSong();
		$scope.addTrackToPlayer();
	});

}]);
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2019 - present Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

import $ from 'jquery'
import axios from 'axios'
import I18n from 'i18n!DefaultToolForm'
import PropTypes from 'prop-types'
import React, {useState, useEffect} from 'react'

import SelectContentDialog from '../../../public/javascripts/select_content_dialog.js'
import usePostMessage from './hooks/usePostMessage'

import { Alert } from '@instructure/ui-alerts'
import { Button } from '@instructure/ui-buttons'
import { Text } from '@instructure/ui-elements'
import { View } from '@instructure/ui-layout'

export function toolSubmissionType(submissionType) {
  const toolTypes = ['default_external_tool']
  return toolTypes.includes(submissionType) ? 'external_tool' : submissionType
}

const DefaultToolForm = props => {
  const [launchDefinitions, setLaunchDefinitions] = useState([])
  const toolMessageData = usePostMessage('defaultToolContentReady')

  const defaultToolData = launchDefinitions.find(definition =>
    Object.values(definition.placements).find(placement => placement.url === props.toolUrl)
  )

  const launchDefinitionUrl = () =>
    `/api/v1/courses/${props.courseId}/lti_apps/launch_definitions?per_page=100&placements%5B%5D=assignment_selection&placements%5B%5D=resource_selection`

  const contentTitle = () => {
    if (toolMessageData) {
      return toolMessageData.content && toolMessageData.content.title
    }
    return props.toolName
  }
  useEffect(() => {
    const fetchData = async () => {
      const result = await axios.get(launchDefinitionUrl())
      setLaunchDefinitions(result.data)
    }
    fetchData()
  }, [])

  useEffect(() => {
    $('#default-tool').data('tool', defaultToolData)
  }, [launchDefinitions])

  const handleLaunchButton = event => {
    SelectContentDialog.Events.onContextExternalToolSelect(event, $('#default-tool'))
  }

  if(!defaultToolData && launchDefinitions.length > 0) {
    return(
      <View display="block" padding="medium none small small">
        <Alert variant="error" margin="small small 0 0">
          <Text weight="bold">{I18n.t('Tool Not Found')}</Text>

          <Text>{I18n.t('The tool is not installed in the course or account')}</Text>
        </Alert>
      </View>
    )
  }

  return (
    <View display="block" padding="medium none small small">
      <Button id="default-tool-launch-button" name="default-tool-launch-button" onClick={handleLaunchButton}>
        {props.toolButtonText}
      </Button>

      {toolMessageData || props.previouslySelected ? (
        <Alert variant="success" margin="small small 0 0">
          <Text weight="bold">{contentTitle()}</Text>

          <Text>{I18n.t('Successfully Added')}</Text>
        </Alert>
      ) : (
        <Alert variant="info" margin="small small 0 0">
          {props.toolInfoMessage}
        </Alert>
      )}

      {defaultToolData && (

                {defaultToolData.name}

This is a Sample Tool Provider.

      )}
    </View>
  )
}

DefaultToolForm.propTypes = {
  toolUrl: PropTypes.string.isRequired,
  courseId: PropTypes.number.isRequired,
  toolName: PropTypes.string.isRequired,
  previouslySelected: PropTypes.bool.isRequired,
  toolButtonText: PropTypes.string,
  toolInfoMessage: PropTypes.string
}

DefaultToolForm.defaultProps = {
  toolButtonText: I18n.t('Add Content'),
  toolInfoMessage: I18n.t('Click the button above to add content')
}

export default DefaultToolForm
<commit_msg>Add live region info to default tool alerts<commit_after>/*
 * Copyright (C) 2019 - present Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

import $ from 'jquery'
import axios from 'axios'
import I18n from 'i18n!DefaultToolForm'
import PropTypes from 'prop-types'
import React, {useState, useEffect} from 'react'

import SelectContentDialog from '../../../public/javascripts/select_content_dialog.js'
import usePostMessage from './hooks/usePostMessage'

import {Alert} from '@instructure/ui-alerts'
import {Button} from '@instructure/ui-buttons'
import {Text} from '@instructure/ui-elements'
import {View} from '@instructure/ui-layout'

export function toolSubmissionType(submissionType) {
  const toolTypes = ['default_external_tool']
  return toolTypes.includes(submissionType) ? 'external_tool' : submissionType
}

const DefaultToolForm = props => {
  const [launchDefinitions, setLaunchDefinitions] = useState([])
  const toolMessageData = usePostMessage('defaultToolContentReady')

  const defaultToolData = launchDefinitions.find(definition =>
    Object.values(definition.placements).find(placement => placement.url === props.toolUrl)
  )

  const launchDefinitionUrl = () =>
    `/api/v1/courses/${props.courseId}/lti_apps/launch_definitions?per_page=100&placements%5B%5D=assignment_selection&placements%5B%5D=resource_selection`

  const contentTitle = () => {
    if (toolMessageData) {
      return toolMessageData.content && toolMessageData.content.title
    }
    return props.toolName
  }
  useEffect(() => {
    const fetchData = async () => {
      const result = await axios.get(launchDefinitionUrl())
      setLaunchDefinitions(result.data)
    }
    fetchData()
  }, [])

  useEffect(() => {
    $('#default-tool').data('tool', defaultToolData)
  }, [launchDefinitions])

  const handleLaunchButton = event => {
    SelectContentDialog.Events.onContextExternalToolSelect(event, $('#default-tool'))
  }

  if (!defaultToolData && launchDefinitions.length > 0) {
    return (
      <View display="block" padding="medium none small small">
        <Alert variant="error" margin="small small 0 0">
          <Text weight="bold">{I18n.t('Tool Not Found')}</Text>

          <Text>{I18n.t('The tool is not installed in the course or account')}</Text>
        </Alert>
      </View>
    )
  }

  if (toolMessageData) {
    $.screenReaderFlashMessage(I18n.t('%{content} successfully added', {content: contentTitle()}))
  }

  return (
    <View display="block" padding="medium none small small">
      <Button
        id="default-tool-launch-button"
        name="default-tool-launch-button"
        onClick={handleLaunchButton}
      >
        {props.toolButtonText}
      </Button>

      {toolMessageData || props.previouslySelected ? (
        <Alert
          variant="success"
          margin="small small 0 0"
        >
          <Text weight="bold">{contentTitle()}</Text>

          <Text>{I18n.t('Successfully Added')}</Text>
        </Alert>
      ) : (
        <Alert
          variant="info"
          margin="small small 0 0"
        >
          {props.toolInfoMessage}
        </Alert>
      )}

      {defaultToolData && (

                {defaultToolData.name}

This is a Sample Tool Provider.

      )}
    </View>
  )
}

DefaultToolForm.propTypes = {
  toolUrl: PropTypes.string.isRequired,
  courseId: PropTypes.number.isRequired,
  toolName: PropTypes.string.isRequired,
  previouslySelected: PropTypes.bool.isRequired,
  toolButtonText: PropTypes.string,
  toolInfoMessage: PropTypes.string
}

DefaultToolForm.defaultProps = {
  toolButtonText: I18n.t('Add Content'),
  toolInfoMessage: I18n.t('Click the button above to add content')
}

export default DefaultToolForm
<|endoftext|>