aboutsummaryrefslogtreecommitdiffstats
path: root/app/Controllers/Http/RecipeController.js
blob: 641f4ef4d3d7cb190888d20c571be4a4c637b0e7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
'use strict'

const Recipe = use('App/Models/Recipe');
const Helpers = use('Helpers')
const Drive = use('Drive')
const fetch = require('node-fetch');
const path = require('path');

class RecipeController {
  async list({
    response
  }) {
    const officialRecipes = JSON.parse(await (await fetch('https://api.franzinfra.com/v1/recipes')).text());
    const customRecipesArray = (await Recipe.all()).rows;
    const customRecipes = customRecipesArray.map(recipe => ({
      "id": recipe.recipeId,
      "name": recipe.name,
      ...JSON.parse(recipe.data)
    }))

    const recipes = [
      ...officialRecipes,
      ...customRecipes,
    ]

    return response.send(recipes)
  }

  async create({
    request,
    response
  }) {
    const data = request.all();

    const pkg = request.file('package')

    await pkg.move(path.join(Helpers.appRoot(), '/recipes/'), {
      name: data.id + '.tar.gz',
      overwrite: false
    })

    await Recipe.create({
      name: data.name,
      recipeId: data.id,
      data: JSON.stringify({
        "author": data.author,
        "featured": false,
        "version": "1.0.0",
        "icons": {
          "png": data.png,
          "svg": data.svg
        }
      })
    })

    return response.send('Created new recipe')
  }

  async search({
      request,
      response
  }) {
    const needle = request.input('needle')

    const remoteResults = JSON.parse(await (await fetch('https://api.franzinfra.com/v1/recipes/search?needle=' + needle)).text());
    const localResultsArray = (await Recipe.query().where('name', 'LIKE', '%' + needle + '%').fetch()).toJSON();
    const localResults = localResultsArray.map(recipe => ({
        "id": recipe.recipeId,
        "name": recipe.name,
        ...JSON.parse(recipe.data)
    }))

    const results = [
        ...localResults,
        ...remoteResults,
    ]

    return response.send(results);
  }

  // Download a recipe
  async download({
    request,
    response,
    params
  }) {
    const service = params.recipe;

    // Chack for invalid characters
    if (/\.{1,}/.test(service) || /\/{1,}/.test(service)) {
        return response.send('Invalid recipe name');
    }

    // Check if recipe exists in recipes folder
    if (await Drive.exists(service + '.tar.gz')) {
        response.send(await Drive.get(service + '.tar.gz'))
    } else {
        response.redirect('https://api.franzinfra.com/v1/recipes/download/' + service)
    }
  }
}

module.exports = RecipeController