-
Notifications
You must be signed in to change notification settings - Fork 4
/
WOContext.swift
711 lines (580 loc) · 21 KB
/
WOContext.swift
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
//
// WOContext.swift
// SwiftObjects
//
// Created by Helge Hess on 11.05.18.
// Copyright © 2018-2019 ZeeZide. All rights reserved.
//
import Runtime
/**
* The WOContext is the context for one HTTP transaction, that is, one
* request/response cycle. It provides access to all objects required for
* handling the requests, this includes request, response, the session,
* the current page and so on.
*
* THREAD: WOContext is not threadsafe, its supposed to be used from one thread
* only (the one processing the HTTP request).
*/
public protocol WOContext : WOCoreContext, WOLifecycle,
KeyValueCodingType, MutableKeyValueCodingType
{
init(application: WOApplication, request: WORequest)
var session : WOSession { get set }
var hasNewSession : Bool { get }
var languages : [ String ] { get }
var savePageRequired : Bool { get set } // set is kinda internal
var isRenderingDisabled : Bool { get }
var fragmentID : String? { get set }
@discardableResult func disableRendering() -> Bool
@discardableResult func enableRendering() -> Bool
var hasSession : Bool { get }
/**
* Returns the element-id of the currently active element. The element-id can
* be assigned manually, or it is an automatically generated path. The id is
* calculated by the path the elements flow and repeat through the template
* tree.
* Careful: this is *not* just the node positions, element ids are also
* added/removed by elements like repetitions or conditions! (the contents of
* a repetition need own IDs, not their index in the tree)
*
* Unlike SOPE the Go/So element id does NOT include the context-id.
*
* @return a unique identifier for the current element (in page scope)
*/
var elementID : String { get set }
var senderID : String? { get }
func setRequestSenderID(_ id: String)
func setNewSession(_ sn: WOSession)
/**
* Returns the WOQuerySession attached to the context. This calls the
* WOApplication's restoreQuerySessionInContext() on demand to set up
* the query session.
*/
var querySession : WOQuerySession { get }
/**
* This method uses the query session to determine which query parameters
* should be included in a URL. The method is called by URL generating dynamic
* elements (eg WOHyperlink).
*/
var allQuerySessionValues : [ String : Any ] { get }
// TODO: languages, locale, timezone
var page : WOComponent? { get set }
var cursor : Any? { get }
var component : WOComponent? { get }
var parentComponent : WOComponent? { get }
var componentContent : WOElement? { get }
/**
* If a WOForm is entered, it calls this method to remember the fact. Remember
* that forms must not be nested.
*/
var isInForm : Bool { get set }
/**
* This method is called during the takeValues() phase by WOInput elements to
* register an element as the active one. Eg if a WOSubmitButton encounters
* that its value is set during takeValues() it will set itself as the active
* form element (since only the values of the pressed submit button are
* transmitted, hence can be used to detect the action).
*
* This basically moves the invoke step to the take values process for form
* values. Actually this should not be strictly necessary?
*
* @param _element - the WOElement for the action (usually an WOInput object)
*/
func addActiveFormElement(_ element: WOElement)
/**
* Returns the element (usually an WOInput) which registered itself as the
* active one during the takeValues() phase.
*/
var activeFormElement : WOElement? { get }
/**
* Returns the currently active WOErrorReport. This method is called by
* dynamic elements (eg WOInput) which want to attach errors.
* The value can be null (in this case the elements usually throw an
* exception).
*
* Error reports are pushed to the WOContext using the pushErrorReport()
* method. For example this is called by WOForm if the errorReport binding
* is set.
*
* @return the active WOErrorReport object
*/
var errorReport : WOErrorReport? { get }
/**
* This method is used to push a new WOErrorReport object to the stack of
* error reports. New error reports will be attached to their parent report,
* so that a hierarchy of reports can be built.
* E.g. it is called by WOForm if the 'errorReport' binding is set.
*
* @param _report - the new WOErrorReport object
*/
func pushErrorReport(_ report : WOErrorReport)
func popErrorReport () -> WOErrorReport?
/**
* An internal method which is called from various places. It registers a
* component as awake (it does NOT trigger the awake() method).
*/
func _addAwakeComponent(_ component: WOComponent)
func enterComponent(_ component: WOComponent, content: WOElement?)
func leaveComponent(_ component: WOComponent)
var rootResourceManager : WOResourceManager? { get }
}
public extension WOContext {
func enterComponent(_ component: WOComponent) {
enterComponent(component, content: nil)
}
var cursor : Any? { return component }
}
// MARK: - URL generation
public extension WOContext {
var hasErrorReport : Bool { return errorReport != nil }
/**
* Composes a URL suitable for use with the given request handler.
*
* Important: this does *not* add any query parameters (like wosid).
*/
func urlWithRequestHandlerKey(_ key : String,
path : String? = nil,
query : String? = nil) -> String
{
var sb = ""
if let v = request.adaptorPrefix, !v.isEmpty {
sb += v
}
let appName = request.applicationName ?? application.name
if sb.isEmpty || !sb.hasSuffix("/") { sb += "/" }
sb += appName
sb += "/"
sb += key
if let v = path, !v.isEmpty {
if !v.hasPrefix("/") { sb += "/" }
sb += v
}
if let v = query, !v.isEmpty {
sb += "?"
sb += v
}
return sb
}
/**
* Constructs a component action URL for the currently active element. This
* URL includes the sessionID as well as the currently active elementID.
*
* This method calls urlWithRequestHandlerKey to perform the final assembly.
*/
func componentActionURL() -> String? {
/*
* This makes the request handler save the page in the session at the
* end of the request (only necessary if the page generates URLs which
* refer the context).
*/
savePageRequired = true
return urlWithRequestHandlerKey(
application.componentRequestHandlerKey,
path: session.sessionID + "/" + contextID + "/" + elementID
)
}
/**
* Generates a URL for the given direct action.
*
* Important: this does *not* embed a session id! Session ids or query
* session parameters are added to the queryDict by the respective
* WODynamicElement class (usually WOLinkGenerator).
*
* @param _name - a direct action name, eg "Main/default"
* @param _queryDict - set of query parameters to be included in the URL
* @return a URL
*/
func directActionURLForActionNamed(_ name: String,
with queryDictionary: [ String : Any? ]?)
-> String
{
let qs = queryDictionary?.stringForQueryDictionary()
return urlWithRequestHandlerKey(application.directActionRequestHandlerKey,
path: name, query: qs)
}
/**
* Generates a URL for the given direct action.
*
* Important: this does *not* embed a session id! Session ids or query
* session parameters are added to the queryDict by the respective
* WODynamicElement class (usually WOLinkGenerator).
*
* @param _name - a direct action name, eg "Main/default"
* @return a URL
*/
func directActionURLForActionNamed(_ name: String) -> String {
return urlWithRequestHandlerKey(application.directActionRequestHandlerKey,
path: name, query: nil)
}
/**
* Same like directActionURLForActionNamed(name,dict), but this prepares the
* query dictionary with the query session parameters and the session-id (if
* one is active).
*
* @param _name - name of the direct action (eg Main/default)
* @param _queryDict - query parameters
* @param _addSnId - whether to include the session id (?wosid)
* @param _incQuerySession - whether to include the query session
* @return a URL pointing to the direct action
*/
func directActionURLForActionNamed(_ name: String,
with queryDictionary : [ String : Any? ]?,
addSessionID : Bool = false,
includeQuerySession : Bool = false)
-> String
{
if !addSessionID && !includeQuerySession {
return directActionURLForActionNamed(name, with: queryDictionary)
}
let querySession : WOQuerySession? = {
guard includeQuerySession else { return nil }
guard self.querySession.hasActiveQuerySessionValues else { return nil }
return self.querySession
}()
let sessionID = addSessionID && hasSession ? (session.sessionID) : nil
if querySession == nil && sessionID == nil {
return directActionURLForActionNamed(name, with: queryDictionary)
}
var qd = queryDictionary ?? [:]
querySession?.add(to: &qd)
if let sessionID = sessionID {
qd[WORequest.SessionIDKey] = sessionID
}
return directActionURLForActionNamed(name, with: qd)
}
}
// MARK: - Element IDs
public extension WOContext {
func appendElementIDComponent(_ id: String) {
if !elementID.isEmpty { elementID += "." }
elementID += id
}
func appendElementIDComponent(_ id: Int) {
if !elementID.isEmpty { elementID += "." }
elementID += String(id)
}
/**
* Adds a zero to the element ID. Example:
*
* "2.3.4.5" => "2.3.4.5.0"
* "" => "0"
*
*/
func appendZeroElementIDComponent() {
if elementID.isEmpty { elementID += "0" }
else { elementID += ".0" }
}
/**
* Increments the last part of the element-id. Example
*
* "2.3.4.5" => "2.3.4.6"
* "2" => "3"
*
*/
func incrementLastElementIDComponent(by value: Int = 1) {
if let r = elementID.range(of: ".", options: .backwards) {
let prefix = elementID[elementID.startIndex..<r.upperBound]
let num = elementID[r.upperBound..<elementID.endIndex]
let v = (Int(num) ?? 0) + value
elementID = prefix + String(v)
}
else {
let v = (Int(elementID) ?? 0) + value
elementID = String(v)
}
}
/**
* Deletes the last part of the element-id. Example
*
* "2.3.4.5" => "2.3.4"
* "2" => ""
*
*/
func deleteLastElementIDComponent() {
if let r = elementID.range(of: ".", options: .backwards) {
elementID = String(elementID[elementID.startIndex..<r.lowerBound])
}
else {
elementID.removeAll()
}
}
/**
* Completely clears the element-id (to the empty string "").
*/
func deleteAllElementIDComponents() {
elementID.removeAll()
}
}
// MARK: - Concrete Object
open class WOAppContext : WOCoreContextBase, WOContext, ExtraVariables {
open var hasNewSession = false
open var savePageRequired = false
open var isRenderingDisabled = false
open var fragmentID : String? = nil
open var elementID = ""
open var senderID : String? = nil
open var isInForm : Bool = false
open var activeFormElement : WOElement? = nil
open var errorReports = [ WOErrorReport ]()
public var variableDictionary = [ String : Any ]()
var _languages : [ String ]?
var _session : WOSession?
var _querySession : WOQuerySession?
var awakeComponents = [ WOComponent ]()
var componentStack = [ WOComponent ]()
var contentStack = [ WOElement? ]()
override
required public init(application: WOApplication, request: WORequest) {
super.init(application: application, request: request)
}
// MARK: - Lifecycle
open func awake() {
}
open func sleep() {
sleepComponents()
if hasSession { session.sleep(in: self) }
}
// MARK: - Languages
open var languages : [ String ] {
set { _languages = newValue }
/**
* Returns the List of languages associated with this request. This method is
* checked for localization.
*
* @return a List of language codes (eg ['en', 'de'])
*/
get {
if let langs = _languages { return langs }
if hasSession, let langs = session.languages { return langs }
return request.browserLanguages ?? []
}
}
// MARK: - Session
open var session : WOSession {
set {
_session = newValue
}
get { // FIXME: clumsy
if let sn = _session { return sn }
guard let sn = application.initializeSession(in: self) else {
_session = WOSession() // weird, fix me
return _session!
}
return sn
}
}
open var hasSession : Bool { return _session != nil }
open func setNewSession(_ sn: WOSession) {
session = sn
hasNewSession = true
}
// MARK: - Query Session
open var querySession : WOQuerySession {
if let qs = _querySession { return qs }
let qs = application.restoreQuerySession(in: self)
_querySession = qs
return _querySession!
}
open var allQuerySessionValues : [ String : Any ] {
return querySession.allQuerySessionValues
}
open func setRequestSenderID(_ id: String) {
senderID = id
}
// MARK: - Components
open var page : WOComponent? {
didSet { page?.ensureAwake(in: self) }
}
open var componentContent : WOElement? {
guard let last = contentStack.last else { return nil }
return last
}
open var component : WOComponent? {
return componentStack.last ?? page
}
open var parentComponent : WOComponent? {
guard componentStack.count > 1 else { return nil }
let idx = componentStack.index(componentStack.endIndex, offsetBy: -2)
return componentStack[idx]
}
open func enterComponent(_ component: WOComponent, content: WOElement?) {
componentStack.append(component)
contentStack .append(content)
_awakeComponent(component)
if componentStack.count > 1 {
component.pullValuesFromParent()
}
}
open func leaveComponent(_ component: WOComponent) {
guard component === self.component else {
// TODO: scan stack for _component to see whether the _component is
// upcoming, do something useful
return
}
if componentStack.count > 1 {
component.pushValuesToParent()
}
componentStack.removeLast()
contentStack .removeLast()
}
open func _addAwakeComponent(_ component: WOComponent) {
awakeComponents.append(component)
}
open func _awakeComponent(_ component: WOComponent) {
guard !awakeComponents.contains(where: { $0 === component }) else { return }
component._awakeWithContext(self)
_addAwakeComponent(component)
}
/**
* Calls the sleep() method on all components which got an awake() call with
* this context.
* This is called in WOApp.handleRequest() before a session is saved to ensure
* that just the necessary state is preserved.
*/
open func sleepComponents() {
var sendSleepToPage = true
for component in awakeComponents {
component._sleepWithContext(self)
if component === page { sendSleepToPage = false }
}
awakeComponents.removeAll()
if sendSleepToPage, let page = page {
page._sleepWithContext(self)
}
}
// MARK: - Forms
open func addActiveFormElement(_ element: WOElement) {
guard activeFormElement == nil else {
log.error("active form element already set:", element, self);
return
}
activeFormElement = element
// TBD: is this really necessary? The element-id has no relevance?
setRequestSenderID(elementID)
}
open var errorReport : WOErrorReport? { return errorReports.last }
open func pushErrorReport(_ report : WOErrorReport) {
errorReports.append(report)
}
open func popErrorReport() -> WOErrorReport? {
return errorReports.popLast()
}
// MARK: - Resource Manager
open var rootResourceManager : WOResourceManager? {
return application.resourceManager
}
// MARK: - Rendering
@discardableResult
open func disableRendering() -> Bool {
let old = isRenderingDisabled
isRenderingDisabled = true
return old
}
@discardableResult
open func enableRendering() -> Bool {
let old = isRenderingDisabled
isRenderingDisabled = false
return old
}
// MARK: - KVC
lazy var typeInfo = try? Runtime.typeInfo(of: type(of: self))
open func takeValue(_ value : Any?, forKey k: String) throws {
if variableDictionary[k] != nil {
if let value = value { variableDictionary[k] = value }
else { variableDictionary.removeValue(forKey: k) }
}
switch k {
case "elementID", "senderID", "savePageRequired", "isRenderingDisabled",
"variableDictionary",
"isInForm",
"session", "hasSession", "hasNewSession", "querySession",
"errorReports", "hasErrorReport", "errorReport",
"awakeComponents", "componentStack", "contentStack",
"allQuerySessionValues", "componentActionURL",
"page", "cursor", "component", "parentComponent",
"rootResourceManager":
return try handleTakeValue(value, forUnboundKey: k)
case "fragmentID":
fragmentID = value as? String
return
case "languages":
// TODO
return try handleTakeValue(value, forUnboundKey: k)
default: break
}
if let ti = typeInfo, let prop = try? ti.property(named: k) {
var me = self // TBD
if let value = value { try prop.zset(value: value, on: &me) }
else { try prop.zset(value: value as Any, on: &me) }
return
}
variableDictionary[k] = value
}
open func value(forKey k: String) -> Any? {
if let v = variableDictionary[k] { return v }
switch k {
case "application": return application
case "elementID": return elementID
case "senderID": return senderID
case "savePageRequired": return savePageRequired
case "isRenderingDisabled": return isRenderingDisabled
case "fragmentID": return fragmentID
case "session": return session
case "hasSession": return hasSession
case "hasNewSession": return hasNewSession
case "querySession": return querySession
case "errorReports": return errorReports
case "languages": return languages
case "allQuerySessionValues": return allQuerySessionValues
case "page": return page
case "cursor": return cursor
case "component": return component
case "parentComponent": return parentComponent
case "rootResourceManager": return rootResourceManager
case "componentActionURL": return componentActionURL
case "hasErrorReport": return hasErrorReport
case "errorReport": return errorReport
default: break
}
guard let ti = typeInfo, let prop = try? ti.property(named: k) else {
return handleQueryWithUnboundKey(k)
}
do {
// if this is an optional, we wrap it again
let v = try prop.zget(from: self)
return v
}
catch {
log.error("Failed to get KVC property:", k, error)
return nil
}
}
// MARK: - Description
override open func appendToDescription(_ ms: inout String) {
super.appendToDescription(&ms)
if !elementID.isEmpty { ms += " eid=\(elementID)" }
if let sid = senderID { ms += " sender=\(sid)" }
if let fid = fragmentID { ms += " fragment=\(fid)" }
if savePageRequired { ms += " needs-save" }
if isRenderingDisabled { ms += " render-off" }
if isInForm { ms += " in-form" }
if let sn = _session { ms += " sid=\(sn.sessionID)" }
if let qs = _querySession { ms += " qs=\(qs)" }
if let _ = activeFormElement {
ms += " has-active-form-element"
}
if !variableDictionary.isEmpty {
ms += " #vars=\(variableDictionary.keys)"
}
if let l = _languages, !l.isEmpty {
ms += " langs="
ms += l.joined(separator: ",")
}
if !errorReports.isEmpty {
ms += " errors=\(errorReports)"
}
if awakeComponents.count > 1 { ms += " #awake=\(awakeComponents.count)" }
if componentStack.count > 1 { ms += " #stack=\(componentStack.count)" }
if contentStack.count > 1 { ms += " #content=\(contentStack.count)" }
}
}