<commit_before>import fs from 'fs';
import { ObjectID } from 'mongodb';
import Backbone from 'backbone';
import config from 'config';
import logger from '../lib/logger';
import userApi from './user';
import themeApi from './theme';
import nonOsmDataApi from './nonOsmData';
import osmCacheApi from './osmCache';
import fileApi from './file';
import overPassCacheApi from './overPassCache';
import ThemeCore from '../public/js/core/theme';
import ThemeModel from '../public/js/model/theme';

export default class Api {
  init(app, db, CONST, packageJson) {
    this.options = {
      rootApi: this,
      CONST,
      database: db,
      fileApi
    };

    userApi.setOptions(this.options);
    themeApi.setOptions(this.options);
    nonOsmDataApi.setOptions(this.options);
    osmCacheApi.setOptions(this.options);
    fileApi.setOptions(this.options);
    fileApi.initDirectories(app);
    overPassCacheApi.setOptions(this.options);

    app.get('/api/user/logout', userApi.Api.logout);
    // app.get('/api/user', userApi.Api.getAll);
    app.get('/api/user/:_id', userApi.Api.get);
    app.post('/api/user', Api.isLoggedIn, userApi.Api.post);
    app.put('/api/user/:_id', Api.isLoggedIn, userApi.Api.put);
    // app.delete(
    //     '/api/user/:_id',
    //     Api.isLoggedIn,
    //     this._isThemeOwner.bind(this),
    //     userApi.Api.delete
    // );

    app.get('/api/userThemes', themeApi.Api.getUserThemes);

    app.get('/api/theme', themeApi.Api.getAll);
    app.get('/api/theme/:_id', themeApi.Api.get);
    app.post('/api/theme', Api.isLoggedIn, themeApi.Api.post);
    app.put(
      '/api/theme/:_id',
      Api.isLoggedIn,
      this._isThemeOwner.bind(this),
      themeApi.Api.put
    );
    // app.delete(
    //     '/api/theme/:_id',
    //     Api.isLoggedIn,
    //     this._isThemeOwner.bind(this),
    //     themeApi.Api.delete
    // );

    app.get('/api/nonOsmData', nonOsmDataApi.Api.getAll);
    app.get('/api/nonOsmData/:_id', nonOsmDataApi.Api.get);
    app.post('/api/nonOsmData', Api.isLoggedIn, nonOsmDataApi.Api.post);
    app.put('/api/nonOsmData/:_id', Api.isLoggedIn, nonOsmDataApi.Api.put);

    app.get('/api/osmCache', osmCacheApi.Api.getAll);
    app.get('/api/osmCache/:_id', osmCacheApi.Api.get);
    app.post('/api/osmCache', Api.isLoggedIn, osmCacheApi.Api.post);
    app.put('/api/osmCache/:_id', Api.isLoggedIn, osmCacheApi.Api.put);
    app.delete('/api/osmCache/:_id', osmCacheApi.Api.delete);

    app.get('/', (req, res) => {
      const clientConfig = config.get('client');
      const templateVars = {
        user: req.session.user
          ? escape(JSON.stringify(req.session.user))
          : '{}',
        config: JSON.stringify(clientConfig),
        highlightList: '[]',
        version: packageJson.version,
        analyticScript: config.get('analyticScript')
      };

      const promises = [
        themeApi.Api.findFromUserSession(req.session.user),
        themeApi.Api.findFavoritesFromUserSession(req.session.user),
        Api.reloadSession(req)
      ];

      const highlightPromises = [];

      if (
        clientConfig.highlightedThemes &&
        clientConfig.highlightedThemes.length > 0
      ) {
        for (const fragment of clientConfig.highlightedThemes) {
          highlightPromises.push(themeApi.Api.findFromFragment(fragment));
        }
      }

      Promise.all(promises)
        .then(data => {
          templateVars.userThemes = escape(JSON.stringify(data[0]));
          templateVars.userFavoriteThemesData = escape(JSON.stringify(data[1]));

          return Promise.all(highlightPromises);
        })
        .then(data => {
          if (data.length > 0) {
            const highlightList = [];

            for (const themeObject of data) {
              highlightList.push(themeObject);
            }

            templateVars.highlightList = escape(JSON.stringify(highlightList));
          }

          res.render('home', templateVars);
        })
        .catch(Api.onPromiseError.bind(this, req, res));
    });

    app.get(/\/t\/(\w+)(-.*)?/, (req, res) => {
      const fragment = req.params['0'];
      const templateVars = {
        user: req.session.user
          ? escape(JSON.stringify(req.session.user))
          : '{}',
        config: JSON.stringify(config.get('client')),
        version: packageJson.version,
        analyticScript: config.get('analyticScript')
      };

      const promises = [
        themeApi.Api.findFromFragment(fragment),
        themeApi.Api.findFromUserSession(req.session.user),
        themeApi.Api.findFavoritesFromUserSession(req.session.user),
        nonOsmDataApi.Api.findFromFragment(fragment),
        osmCacheApi.Api.findFromFragment(fragment),
        Api.getiDPresets(CONST),
        Api.reloadSession(req)
      ];

      Promise.all(promises)
        .then(async data => {
          const theme = data[0];

          templateVars.theme = escape(JSON.stringify(theme));
          templateVars.themeAnalyticScript = theme.analyticScript;
          templateVars.userThemes = escape(JSON.stringify(data[1]));
          templateVars.userFavoriteThemesData = escape(JSON.stringify(data[2]));
          templateVars.nonOsmData = escape(JSON.stringify(data[3]));
          templateVars.osmCache = escape(JSON.stringify(data[4]));
          templateVars.iDPresets = escape(JSON.stringify(data[5]));

          if (req.session.user) {
            const userId = req.session.user._id.toString();
            const osmId = req.session.user.osmId.toString();

            if (ThemeCore.isThemeOwner(theme, userId, osmId) === true) {
              const knownOwners = await userApi.Api.findFromIds(
                req,
                res,
                theme.owners,
                theme.osmOwners
              );
              let unknownOwners = [];

              if (theme.osmOwners) {
                unknownOwners = theme.osmOwners.filter(
                  osmOwnerId =>
                    !knownOwners.find(
                      knownOwner => knownOwner.osmId === osmOwnerId
                    )
                );
              }

              templateVars.owners = JSON.stringify(knownOwners);
              templateVars.unknownOwners = JSON.stringify(unknownOwners);
            }
          } else {
            templateVars.owners = '[]';
          }

          res.render('theme', templateVars);
        })<commit_msg>Fix an undefined template variable<commit_after>import fs from 'fs';
import { ObjectID } from 'mongodb';
import Backbone from 'backbone';
import config from 'config';
import logger from '../lib/logger';
import userApi from './user';
import themeApi from './theme';
import nonOsmDataApi from './nonOsmData';
import osmCacheApi from './osmCache';
import fileApi from './file';
import overPassCacheApi from './overPassCache';
import ThemeCore from '../public/js/core/theme';
import ThemeModel from '../public/js/model/theme';

export default class Api {
  init(app, db, CONST, packageJson) {
    this.options = {
      rootApi: this,
      CONST,
      database: db,
      fileApi
    };

    userApi.setOptions(this.options);
    themeApi.setOptions(this.options);
    nonOsmDataApi.setOptions(this.options);
    osmCacheApi.setOptions(this.options);
    fileApi.setOptions(this.options);
    fileApi.initDirectories(app);
    overPassCacheApi.setOptions(this.options);

    app.get('/api/user/logout', userApi.Api.logout);
    // app.get('/api/user', userApi.Api.getAll);
    app.get('/api/user/:_id', userApi.Api.get);
    app.post('/api/user', Api.isLoggedIn, userApi.Api.post);
    app.put('/api/user/:_id', Api.isLoggedIn, userApi.Api.put);
    // app.delete(
    //     '/api/user/:_id',
    //     Api.isLoggedIn,
    //     this._isThemeOwner.bind(this),
    //     userApi.Api.delete
    // );

    app.get('/api/userThemes', themeApi.Api.getUserThemes);

    app.get('/api/theme', themeApi.Api.getAll);
    app.get('/api/theme/:_id', themeApi.Api.get);
    app.post('/api/theme', Api.isLoggedIn, themeApi.Api.post);
    app.put(
      '/api/theme/:_id',
      Api.isLoggedIn,
      this._isThemeOwner.bind(this),
      themeApi.Api.put
    );
    // app.delete(
    //     '/api/theme/:_id',
    //     Api.isLoggedIn,
    //     this._isThemeOwner.bind(this),
    //     themeApi.Api.delete
    // );

    app.get('/api/nonOsmData', nonOsmDataApi.Api.getAll);
    app.get('/api/nonOsmData/:_id', nonOsmDataApi.Api.get);
    app.post('/api/nonOsmData', Api.isLoggedIn, nonOsmDataApi.Api.post);
    app.put('/api/nonOsmData/:_id', Api.isLoggedIn, nonOsmDataApi.Api.put);

    app.get('/api/osmCache', osmCacheApi.Api.getAll);
    app.get('/api/osmCache/:_id', osmCacheApi.Api.get);
    app.post('/api/osmCache', Api.isLoggedIn, osmCacheApi.Api.post);
    app.put('/api/osmCache/:_id', Api.isLoggedIn, osmCacheApi.Api.put);
    app.delete('/api/osmCache/:_id', osmCacheApi.Api.delete);

    app.get('/', (req, res) => {
      const clientConfig = config.get('client');
      const templateVars = {
        user: req.session.user
          ? escape(JSON.stringify(req.session.user))
          : '{}',
        config: JSON.stringify(clientConfig),
        highlightList: '[]',
        version: packageJson.version,
        analyticScript: config.get('analyticScript')
      };

      const promises = [
        themeApi.Api.findFromUserSession(req.session.user),
        themeApi.Api.findFavoritesFromUserSession(req.session.user),
        Api.reloadSession(req)
      ];

      const highlightPromises = [];

      if (
        clientConfig.highlightedThemes &&
        clientConfig.highlightedThemes.length > 0
      ) {
        for (const fragment of clientConfig.highlightedThemes) {
          highlightPromises.push(themeApi.Api.findFromFragment(fragment));
        }
      }

      Promise.all(promises)
        .then(data => {
          templateVars.userThemes = escape(JSON.stringify(data[0]));
          templateVars.userFavoriteThemesData = escape(JSON.stringify(data[1]));

          return Promise.all(highlightPromises);
        })
        .then(data => {
          if (data.length > 0) {
            const highlightList = [];

            for (const themeObject of data) {
              highlightList.push(themeObject);
            }

            templateVars.highlightList = escape(JSON.stringify(highlightList));
          }

          res.render('home', templateVars);
        })
        .catch(Api.onPromiseError.bind(this, req, res));
    });

    app.get(/\/t\/(\w+)(-.*)?/, (req, res) => {
      const fragment = req.params['0'];
      const templateVars = {
        user: req.session.user
          ? escape(JSON.stringify(req.session.user))
          : '{}',
        config: JSON.stringify(config.get('client')),
        version: packageJson.version,
        analyticScript: config.get('analyticScript')
      };

      const promises = [
        themeApi.Api.findFromFragment(fragment),
        themeApi.Api.findFromUserSession(req.session.user),
        themeApi.Api.findFavoritesFromUserSession(req.session.user),
        nonOsmDataApi.Api.findFromFragment(fragment),
        osmCacheApi.Api.findFromFragment(fragment),
        Api.getiDPresets(CONST),
        Api.reloadSession(req)
      ];

      Promise.all(promises)
        .then(async data => {
          const theme = data[0];
          let owners = [];
          let unknownOwners = [];

          templateVars.theme = escape(JSON.stringify(theme));
          templateVars.themeAnalyticScript = theme.analyticScript;
          templateVars.userThemes = escape(JSON.stringify(data[1]));
          templateVars.userFavoriteThemesData = escape(JSON.stringify(data[2]));
          templateVars.nonOsmData = escape(JSON.stringify(data[3]));
          templateVars.osmCache = escape(JSON.stringify(data[4]));
          templateVars.iDPresets = escape(JSON.stringify(data[5]));

          if (req.session.user) {
            const userId = req.session.user._id.toString();
            const osmId = req.session.user.osmId.toString();

            if (ThemeCore.isThemeOwner(theme, userId, osmId) === true) {
              const owners = await userApi.Api.findFromIds(
                req,
                res,
                theme.owners,
                theme.osmOwners
              );

              if (theme.osmOwners) {
                unknownOwners = theme.osmOwners.filter(
                  osmOwnerId =>
                    !owners.find(owner => owner.osmId === osmOwnerId)
                );
              }
            }
          }

          templateVars.owners = JSON.stringify(owners);
          templateVars.unknownOwners = JSON.stringify(unknownOwners);

          res.render('theme', templateVars);
        })
{'fraction_non_alphanumeric': 0.14448639295265062, 'fraction_numerical': 0.0017303759635047978, 'mean_word_length': 2.3043139293139294, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 21, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3040819', 'n_tokens_mistral': 3968, 'n_tokens_neox': 3898, 'n_words': 563}