-
Notifications
You must be signed in to change notification settings - Fork 1
/
app_ct_handler.go
391 lines (344 loc) · 9.64 KB
/
app_ct_handler.go
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
// ThingsConstruction, a code generator for WoT-based models
// Copyright (C) 2017,2018 @aschmidt75
//
// This program 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, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 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/>.
//
// This program is dual-licensed. For commercial licensing options, please
// contact the author(s).
//
//
package main
// app_ct_handler.go
//
// app_ct_handler is responsible for delivering the starting page of the app, where
// users can create a new thing with a basic name and description.
// It generates a UUID and saves the basic definition in a JSON file, redirecting users
// to the next step of adding properties etc. to the Thing Description.
import (
"fmt"
"github.com/gorilla/mux"
"github.com/satori/go.uuid"
"io/ioutil"
"net/http"
"path/filepath"
"strings"
)
type appEntryData struct {
AppPageData
CtfName string
CtfDesc string
CtfType string
AllowTypeSelection bool
AllowFromTemplate bool
Templates map[string]string
}
func AppCreateThingHandleGet(w http.ResponseWriter, req *http.Request) {
if ServerConfig.Features.App == false {
http.Redirect(w, req, "/", 302)
return
}
data := &appEntryData{
AppPageData: AppPageData{
PageData: PageData{
Title: "Create Thing Description",
},
},
}
data.SetFeaturesFromConfig()
data.InApp = true
data.UpdateFeaturesFromContext(req.Context())
vars := mux.Vars(req)
data.AppPageData.ThingId = vars["id"]
if data.AppPageData.ThingId != "" {
Debug.Printf("Loading data for id=%s\n", data.AppPageData.ThingId)
data.AllowTypeSelection = false
data.AllowFromTemplate = false
if err := data.Deserialize(); err != nil {
Error.Printf("Unable to load data, err=%s\n", err)
} else {
data.CtfName = data.AppPageData.wtd.Name
data.CtfDesc = *data.AppPageData.wtd.Description
data.CtfType = data.AppPageData.wtd.Type
}
} else {
data.AllowTypeSelection = true
data.AllowFromTemplate = true
// read templates
var err error
data.Templates, err = appReadModelTemplatesDir()
if err != nil {
Error.Printf("error reding model templates: %s", err)
// disable function in UI
data.AllowFromTemplate = false
}
}
appCreateThingServePage(w, *data)
}
func AppCreateThingFromTemplateHandlePost(w http.ResponseWriter, req *http.Request) {
if ServerConfig.Features.App == false {
http.Redirect(w, req, "/", 302)
return
}
// create new one
data := &appEntryData{
AppPageData: AppPageData{
PageData: PageData{
Title: "Create new Thing Description",
InApp: true,
},
},
}
data.SetFeaturesFromConfig()
data.UpdateFeaturesFromContext(req.Context())
err := req.ParseForm()
if err != nil {
Debug.Printf("Error parsing create thing form: %s\n", err)
appCreateThingServePage(w, appEntryData{
AppPageData: AppPageData{
Message: "There was an error processing your data.",
},
})
return
}
ctft := req.PostForm
var id = ctft.Get("ctftid")
Debug.Printf("%#v", ctft)
if id != "" {
id, err := appEntryCreateThingFromTemplate(data, id)
Debug.Printf("new id=%s", id)
if err != nil {
Error.Printf("error creating from template: %s", err)
data.AppPageData.Message = "There was an error creating your Thing Description. Please try again."
appCreateThingServePage(w, *data)
} else {
// redirect to next steps
http.Redirect(w, req, "/app/"+id+"/framework", http.StatusFound)
}
return
} else {
data.AppPageData.Message = "There was an error creating your Thing Description from a template. Please try again."
appCreateThingServePage(w, *data)
}
}
func AppCreateThingHandlePost(w http.ResponseWriter, req *http.Request) {
if ServerConfig.Features.App == false {
http.Redirect(w, req, "/", 302)
return
}
err := req.ParseForm()
if err != nil {
Debug.Printf("Error parsing create thing form: %s\n", err)
appCreateThingServePage(w, appEntryData{
AppPageData: AppPageData{
Message: "There was an error processing your data.",
},
})
return
}
ctf := req.PostForm
// check if id is valid
vars := mux.Vars(req)
id := vars["id"]
if id != "" {
// this is an edit of an existing ThingId
data := &appManageActionsData{
AppPageData: AppPageData{
PageData: PageData{
InApp: true,
},
ThingId: id,
},
}
data.UpdateFeaturesFromContext(req.Context())
if !data.IsIdValid() {
appCreateThingServePage(w, appEntryData{
AppPageData: AppPageData{
Message: "There was an error locating WoT data by ID.",
},
})
return
}
if err := data.Deserialize(); err != nil {
Error.Println(err)
appCreateThingServePage(w, appEntryData{
AppPageData: AppPageData{
Message: "There was an error locating WoT data by ID.",
},
})
}
data.wtd.Name = ctf.Get("ctf_name")
data.wtd.Type = ctf.Get("ctf_type")
data.wtd.Description = new(string)
*data.wtd.Description = ctf.Get("ctf_desc")
Debug.Printf("id=%s, wtd=%#v\n", id, data.wtd)
// save..
if data.Serialize() != nil {
Error.Println(err)
appCreateThingServePage(w, appEntryData{
AppPageData: AppPageData{
Message: "There was an error writing session data.",
},
})
return
}
// redirect to next steps
http.Redirect(w, req, "/app/"+id+"/framework", http.StatusFound)
} else {
// create new one
data := &appEntryData{
AppPageData: AppPageData{
PageData: PageData{
Title: "Create new Thing Description",
InApp: true,
},
},
CtfName: ctf.Get("ctf_name"),
CtfDesc: strings.TrimSpace(ctf.Get("ctf_desc")),
CtfType: ctf.Get("ctf_type"),
}
data.SetFeaturesFromConfig()
data.UpdateFeaturesFromContext(req.Context())
id, err := appEntryCreateThing(data)
if err != nil {
data.AppPageData.Message = "There was an error creating your Thing Description. Please try again."
appCreateThingServePage(w, *data)
} else {
// redirect to next steps
http.Redirect(w, req, "/app/"+id+"/framework", http.StatusFound)
}
}
}
func AppCreateThingHandleDelete(w http.ResponseWriter, req *http.Request) {
if ServerConfig.Features.App == false {
w.WriteHeader(501)
return
}
// check if id is valid
vars := mux.Vars(req)
id := vars["id"]
if id != "" {
// this is an edit of an existing ThingId
data := &appManageActionsData{
AppPageData: AppPageData{
PageData: PageData{
InApp: true,
},
ThingId: id,
},
}
// delete
if err := data.Delete(); err != nil {
w.WriteHeader(500)
return
}
w.WriteHeader(205)
return
}
w.WriteHeader(500)
}
// reads all templates from model template dir
func appReadModelTemplatesDir() (map[string]string, error) {
res := make(map[string]string)
fileInfos, err := ioutil.ReadDir(ServerConfig.Paths.ModelTemplatesPath)
if err != nil {
return res, err
}
for _, fileInfo := range fileInfos {
if !fileInfo.IsDir() {
continue
}
wtd := &WebThingDescription{}
path := filepath.Join(ServerConfig.Paths.ModelTemplatesPath, fileInfo.Name(), "data.json")
err := wtd.Deserialize("0", path)
if err != nil {
continue
}
var s string
if wtd.Description != nil {
s = *wtd.Description
} else {
s = wtd.Name
}
res[fileInfo.Name()] = s
}
return res, nil
}
func appEntryCreateThingFromTemplate(data *appEntryData, templateId string) (string, error) {
data.AppPageData.ThingId = uuid.Must(uuid.NewV4()).String()
data.AppPageData.wtd = &WebThingDescription{}
path := filepath.Join(ServerConfig.Paths.ModelTemplatesPath, templateId, "data.json")
err := data.AppPageData.wtd.Deserialize(data.AppPageData.ThingId, path)
if err != nil {
return "", err
}
err = data.AppPageData.Serialize()
if err != nil {
return "", err
}
return data.AppPageData.ThingId, nil
}
// creates a new Thing Description json, puts basic data in it,
// returns unique thing id
func appEntryCreateThing(data *appEntryData) (string, error) {
data.AppPageData.ThingId = uuid.Must(uuid.NewV4()).String()
data.AppPageData.wtd = &WebThingDescription{
Name: data.CtfName,
Description: new(string),
Type: data.CtfType,
}
*data.AppPageData.wtd.Description = data.CtfDesc
// According to Thing Type selected, prefill with properties/actions
var wtd = data.AppPageData.wtd
for key, tp := range TypePresets {
if wtd.Type == key {
if len(tp.properties) > 0 {
wtd.NewProperties()
for _, o := range tp.properties {
wtd.AppendProperty(o)
}
}
if len(tp.actions) > 0 {
wtd.NewActions()
for _, o := range tp.actions {
wtd.AppendAction(o)
}
}
if len(tp.events) > 0 {
wtd.NewEvents()
for _, o := range tp.events {
wtd.AppendEvent(o)
}
}
}
}
err := data.AppPageData.Serialize()
if err != nil {
return "", err
}
return data.AppPageData.ThingId, nil
}
func appCreateThingServePage(w http.ResponseWriter, data appEntryData) {
templates, err := NewBasicHtmlTemplateSet("app_ct.html.tpl", "app_ct_script.html.tpl")
if err != nil {
Error.Fatalf("Fatal error creating template set: %s\n", err)
panic(err)
}
Verbose.Printf("appCreateThingServePage: %#v\n", data)
err = templates.ExecuteTemplate(w, "root", data)
if err != nil {
Error.Printf("Error executing template: %s\n", err)
w.WriteHeader(500)
fmt.Fprint(w, "There was an internal error.")
}
}