From 5b9535e9964816eb228d3797f4c8a3e7676d1f53 Mon Sep 17 00:00:00 2001 From: Robert Jaros Date: Wed, 25 Apr 2018 08:12:25 +0200 Subject: Multiplatform kvision-common and kvision-server modules. Support for automatic remote bindings (work in progress). --- src/main/kotlin/pl/treksoft/kvision/form/Form.kt | 111 ++++-- .../kotlin/pl/treksoft/kvision/form/FormControl.kt | 18 +- .../kotlin/pl/treksoft/kvision/form/FormPanel.kt | 58 ++- .../pl/treksoft/kvision/form/time/DateTime.kt | 10 +- .../pl/treksoft/kvision/form/time/DateTimeInput.kt | 15 +- .../pl/treksoft/kvision/form/upload/Upload.kt | 15 +- .../pl/treksoft/kvision/form/upload/UploadInput.kt | 25 +- .../kotlin/pl/treksoft/kvision/remote/Jooby.kt | 34 ++ .../pl/treksoft/kvision/remote/RemoteAgent.kt | 417 +++++++++++++++++++++ .../pl/treksoft/kvision/remote/ServiceManager.kt | 117 ++++++ src/main/kotlin/pl/treksoft/kvision/types/KDate.kt | 39 ++ 11 files changed, 780 insertions(+), 79 deletions(-) create mode 100644 src/main/kotlin/pl/treksoft/kvision/remote/Jooby.kt create mode 100644 src/main/kotlin/pl/treksoft/kvision/remote/RemoteAgent.kt create mode 100644 src/main/kotlin/pl/treksoft/kvision/remote/ServiceManager.kt create mode 100644 src/main/kotlin/pl/treksoft/kvision/types/KDate.kt (limited to 'src/main/kotlin/pl/treksoft') diff --git a/src/main/kotlin/pl/treksoft/kvision/form/Form.kt b/src/main/kotlin/pl/treksoft/kvision/form/Form.kt index 65161303..18acdf9f 100644 --- a/src/main/kotlin/pl/treksoft/kvision/form/Form.kt +++ b/src/main/kotlin/pl/treksoft/kvision/form/Form.kt @@ -21,8 +21,14 @@ */ package pl.treksoft.kvision.form -import org.w3c.files.File -import kotlin.js.Date +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Mapper +import kotlinx.serialization.json.JSON +import kotlinx.serialization.serializer +import pl.treksoft.kvision.form.upload.Upload +import pl.treksoft.kvision.types.KDate +import pl.treksoft.kvision.types.KFile +import pl.treksoft.kvision.utils.getContent import kotlin.js.Json import kotlin.reflect.KProperty1 @@ -41,16 +47,45 @@ internal data class FieldParams( * @constructor Creates a form with a given modelFactory function * @param K model class type * @param panel optional instance of [FormPanel] - * @param modelFactory function transforming a Map to a data model of class K + * @param serializer a serializer for model type */ @Suppress("TooManyFunctions") -class Form(private val panel: FormPanel? = null, private val modelFactory: (Map) -> K) { +class Form(private val panel: FormPanel? = null, private val serializer: KSerializer) { + internal val modelFactory: (Map) -> K internal val fields: MutableMap = mutableMapOf() internal val fieldsParams: MutableMap = mutableMapOf() internal var validatorMessage: ((Form) -> String?)? = null internal var validator: ((Form) -> Boolean?)? = null + init { + modelFactory = { + val map = it.flatMap { entry -> + when (entry.value) { + is KDate -> { + listOf(entry.key to entry.value, "${entry.key}.time" to (entry.value as KDate).time) + } + is List<*> -> { + @Suppress("UNCHECKED_CAST") + (entry.value as? List)?.let { + listOf(entry.key to entry.value, "${entry.key}.size" to it.size) + + it.mapIndexed { index, kFile -> + listOf( + "${entry.key}.${index + 1}.name" to kFile.name, + "${entry.key}.${index + 1}.size" to kFile.size, + "${entry.key}.${index + 1}.content" to kFile.content + ) + }.flatten() + } ?: listOf() + } + else -> listOf(entry.key to entry.value) + } + }.toMap().withDefault { null } + val mapper = Mapper.InNullableMapper(map) + mapper.read(serializer) + } + } + internal fun addInternal( key: KProperty1, control: C, required: Boolean = false, validatorMessage: ((C) -> String?)? = null, @@ -121,8 +156,8 @@ class Form(private val panel: FormPanel? = null, private val modelFactory: * @param validator optional validation function * @return current form */ - fun add( - key: KProperty1, control: C, required: Boolean = false, + fun add( + key: KProperty1, control: C, required: Boolean = false, validatorMessage: ((C) -> String?)? = null, validator: ((C) -> Boolean?)? = null ): Form { @@ -138,8 +173,8 @@ class Form(private val panel: FormPanel? = null, private val modelFactory: * @param validator optional validation function * @return current form */ - fun add( - key: KProperty1?>, control: C, required: Boolean = false, + fun add( + key: KProperty1?>, control: C, required: Boolean = false, validatorMessage: ((C) -> String?)? = null, validator: ((C) -> Boolean?)? = null ): Form { @@ -189,16 +224,9 @@ class Form(private val panel: FormPanel? = null, private val modelFactory: */ fun setData(model: K) { fields.forEach { it.value.setValue(null) } - val map = model.asDynamic().map as? Map - if (map != null) { - map.forEach { - fields[it.key]?.setValue(it.value) - } - } else { - for (key in js("Object").keys(model)) { - @Suppress("UnsafeCastFromDynamic") - fields[key]?.setValue(model.asDynamic()[key]) - } + for (key in js("Object").keys(model)) { + @Suppress("UnsafeCastFromDynamic") + fields[key]?.setValue(model.asDynamic()[key]) } } @@ -218,12 +246,28 @@ class Form(private val panel: FormPanel? = null, private val modelFactory: return modelFactory(map.withDefault { null }) } + /** + * Returns file with the content read. + * @param key key identifier of the control + * @param kFile object identifying the file + * @return KFile object + */ + @Suppress("EXPERIMENTAL_FEATURE_WARNING") + suspend fun getContent( + key: KProperty1?>, + kFile: KFile + ): KFile { + val control = getControl(key) as Upload + val content = control.getNativeFile(kFile)?.getContent() + return kFile.copy(content = content) + } + /** * Returns current data model as JSON. * @return data model as JSON */ fun getDataJson(): Json { - return fields.entries.associateBy({ it.key }, { it.value.getValue() }).asJson() + return kotlin.js.JSON.parse(JSON.stringify(serializer, getData())) } /** @@ -259,27 +303,20 @@ class Form(private val panel: FormPanel? = null, private val modelFactory: } return fieldWithError == null && validatorPassed } -} -/** - * Returns given value from the map as a String. - */ -fun Map.string(key: String): String? = this[key] as? String + companion object { + inline fun create( + panel: FormPanel? = null, + noinline init: (Form.() -> Unit)? = null + ): Form { + val form = Form(panel, K::class.serializer()) + init?.invoke(form) + return form + } -/** - * Returns given value from the map as a Number. - */ -fun Map.number(key: String): Number? = this[key] as? Number -/** - * Returns given value from the map as a Boolean. - */ -fun Map.bool(key: String): Boolean? = this[key] as? Boolean - -/** - * Returns given value from the map as a Date. - */ -fun Map.date(key: String): Date? = this[key] as? Date + } +} /** * Extension function to convert Map to JSON. diff --git a/src/main/kotlin/pl/treksoft/kvision/form/FormControl.kt b/src/main/kotlin/pl/treksoft/kvision/form/FormControl.kt index be27ac7a..6aff842a 100644 --- a/src/main/kotlin/pl/treksoft/kvision/form/FormControl.kt +++ b/src/main/kotlin/pl/treksoft/kvision/form/FormControl.kt @@ -21,9 +21,9 @@ */ package pl.treksoft.kvision.form -import org.w3c.files.File import pl.treksoft.kvision.core.Component -import kotlin.js.Date +import pl.treksoft.kvision.types.KDate +import pl.treksoft.kvision.types.KFile /** * Input controls sizes. @@ -190,15 +190,15 @@ interface BoolFormControl : FormControl { /** * Base interface of a form control with a date value. */ -interface DateFormControl : FormControl { +interface KDateFormControl : FormControl { /** * Date value. */ - var value: Date? + var value: KDate? - override fun getValue(): Date? = value + override fun getValue(): KDate? = value override fun setValue(v: Any?) { - value = v as? Date + value = v as? KDate } override fun getValueAsString(): String? = value?.toString() @@ -207,13 +207,13 @@ interface DateFormControl : FormControl { /** * Base interface of a form control with a list of files value. */ -interface FilesFormControl : FormControl { +interface KFilesFormControl : FormControl { /** * List of files value. */ - var value: List? + var value: List? - override fun getValue(): List? = value + override fun getValue(): List? = value override fun setValue(v: Any?) { if (v == null) value = null } diff --git a/src/main/kotlin/pl/treksoft/kvision/form/FormPanel.kt b/src/main/kotlin/pl/treksoft/kvision/form/FormPanel.kt index 3eb2a0ca..88aed36b 100644 --- a/src/main/kotlin/pl/treksoft/kvision/form/FormPanel.kt +++ b/src/main/kotlin/pl/treksoft/kvision/form/FormPanel.kt @@ -22,7 +22,8 @@ package pl.treksoft.kvision.form import com.github.snabbdom.VNode -import org.w3c.files.File +import kotlinx.serialization.KSerializer +import kotlinx.serialization.serializer import pl.treksoft.kvision.core.Container import pl.treksoft.kvision.core.StringBoolPair import pl.treksoft.kvision.core.StringPair @@ -31,7 +32,8 @@ import pl.treksoft.kvision.form.check.Radio import pl.treksoft.kvision.html.TAG import pl.treksoft.kvision.html.Tag import pl.treksoft.kvision.panel.SimplePanel -import kotlin.js.Date +import pl.treksoft.kvision.types.KDate +import pl.treksoft.kvision.types.KFile import kotlin.js.Json import kotlin.reflect.KProperty1 @@ -80,13 +82,13 @@ enum class FormTarget(internal val target: String) { * @param enctype form encoding type * @param type form layout * @param classes set of CSS class names - * @param modelFactory function transforming a Map to a data model of class K + * @param serializer a serializer for model type */ @Suppress("TooManyFunctions") -open class FormPanel( +open class FormPanel( method: FormMethod? = null, action: String? = null, enctype: FormEnctype? = null, private val type: FormType? = null, classes: Set = setOf(), - modelFactory: (Map) -> K + serializer: KSerializer ) : SimplePanel(classes) { /** @@ -148,7 +150,7 @@ open class FormPanel( * Internal property. */ @Suppress("LeakingThis") - protected val form = Form(this, modelFactory) + protected val form = Form(this, serializer) /** * @suppress * Internal property. @@ -281,8 +283,8 @@ open class FormPanel( * @param validator optional validation function * @return current form panel */ - open fun add( - key: KProperty1, control: C, required: Boolean = false, + open fun add( + key: KProperty1, control: C, required: Boolean = false, validatorMessage: ((C) -> String?)? = null, validator: ((C) -> Boolean?)? = null ): FormPanel { @@ -298,8 +300,8 @@ open class FormPanel( * @param validator optional validation function * @return current form panel */ - open fun add( - key: KProperty1?>, control: C, required: Boolean = false, + open fun add( + key: KProperty1?>, control: C, required: Boolean = false, validatorMessage: ((C) -> String?)? = null, validator: ((C) -> Boolean?)? = null ): FormPanel { @@ -367,6 +369,20 @@ open class FormPanel( return form.getData() } + /** + * Returns an object with the content of the file. + * @param key key identifier of the control + * @param kFile object identifying the file + * @return KFile object + */ + @Suppress("EXPERIMENTAL_FEATURE_WARNING") + suspend fun getContent( + key: KProperty1?>, + kFile: KFile + ): KFile { + return form.getContent(key, kFile) + } + /** * Returns current data model as JSON. * @return data model as JSON @@ -389,14 +405,26 @@ open class FormPanel( * * It takes the same parameters as the constructor of the built component. */ - fun Container.formPanel( + inline fun Container.formPanel( method: FormMethod? = null, action: String? = null, enctype: FormEnctype? = null, type: FormType? = null, classes: Set = setOf(), - modelFactory: (Map) -> K + noinline init: (FormPanel.() -> Unit)? = null ): FormPanel { - val panel = FormPanel(method, action, enctype, type, classes, modelFactory) - this.add(panel) - return panel + val formPanel = FormPanel.create(method, action, enctype, type, classes) + init?.invoke(formPanel) + this.add(formPanel) + return formPanel } + + inline fun create( + method: FormMethod? = null, action: String? = null, enctype: FormEnctype? = null, + type: FormType? = null, classes: Set = setOf(), + noinline init: (FormPanel.() -> Unit)? = null + ): FormPanel { + val formPanel = FormPanel(method, action, enctype, type, classes, K::class.serializer()) + init?.invoke(formPanel) + return formPanel + } + } } diff --git a/src/main/kotlin/pl/treksoft/kvision/form/time/DateTime.kt b/src/main/kotlin/pl/treksoft/kvision/form/time/DateTime.kt index 3d32fd8c..9cdd0369 100644 --- a/src/main/kotlin/pl/treksoft/kvision/form/time/DateTime.kt +++ b/src/main/kotlin/pl/treksoft/kvision/form/time/DateTime.kt @@ -24,12 +24,12 @@ package pl.treksoft.kvision.form.time import pl.treksoft.kvision.core.Container import pl.treksoft.kvision.core.StringBoolPair import pl.treksoft.kvision.core.Widget -import pl.treksoft.kvision.form.DateFormControl import pl.treksoft.kvision.form.FieldLabel import pl.treksoft.kvision.form.HelpBlock +import pl.treksoft.kvision.form.KDateFormControl import pl.treksoft.kvision.panel.SimplePanel +import pl.treksoft.kvision.types.KDate import pl.treksoft.kvision.utils.SnOn -import kotlin.js.Date /** * Form field date/time chooser component. @@ -42,9 +42,9 @@ import kotlin.js.Date * @param rich determines if [label] can contain HTML code */ open class DateTime( - value: Date? = null, name: String? = null, format: String = "YYYY-MM-DD HH:mm", label: String? = null, + value: KDate? = null, name: String? = null, format: String = "YYYY-MM-DD HH:mm", label: String? = null, rich: Boolean = false -) : SimplePanel(setOf("form-group")), DateFormControl { +) : SimplePanel(setOf("form-group")), KDateFormControl { /** * Date/time input value. @@ -235,7 +235,7 @@ open class DateTime( * It takes the same parameters as the constructor of the built component. */ fun Container.dateTime( - value: Date? = null, name: String? = null, format: String = "YYYY-MM-DD HH:mm", label: String? = null, + value: KDate? = null, name: String? = null, format: String = "YYYY-MM-DD HH:mm", label: String? = null, rich: Boolean = false, init: (DateTime.() -> Unit)? = null ): DateTime { val dateTime = DateTime(value, name, format, label, rich).apply { init?.invoke(this) } diff --git a/src/main/kotlin/pl/treksoft/kvision/form/time/DateTimeInput.kt b/src/main/kotlin/pl/treksoft/kvision/form/time/DateTimeInput.kt index 86e9c7ba..3a40d1af 100644 --- a/src/main/kotlin/pl/treksoft/kvision/form/time/DateTimeInput.kt +++ b/src/main/kotlin/pl/treksoft/kvision/form/time/DateTimeInput.kt @@ -28,10 +28,11 @@ import pl.treksoft.kvision.core.StringPair import pl.treksoft.kvision.core.Widget import pl.treksoft.kvision.form.FormInput import pl.treksoft.kvision.form.InputSize +import pl.treksoft.kvision.types.KDate +import pl.treksoft.kvision.types.toJS +import pl.treksoft.kvision.types.toKDateF +import pl.treksoft.kvision.types.toStringF import pl.treksoft.kvision.utils.obj -import pl.treksoft.kvision.utils.toDateF -import pl.treksoft.kvision.utils.toStringF -import kotlin.js.Date internal const val DEFAULT_MINUTE_STEP = 5 internal const val MAX_VIEW = 4 @@ -46,7 +47,7 @@ internal const val MAX_VIEW = 4 */ @Suppress("TooManyFunctions") open class DateTimeInput( - value: Date? = null, format: String = "YYYY-MM-DD HH:mm", + value: KDate? = null, format: String = "YYYY-MM-DD HH:mm", classes: Set = setOf() ) : Widget(classes + "form-control"), FormInput { @@ -162,7 +163,7 @@ open class DateTimeInput( @Suppress("UnsafeCastFromDynamic") protected open fun refreshState() { value?.let { - getElementJQueryD()?.datetimepicker("update", it) + getElementJQueryD()?.datetimepicker("update", it.toJS()) } ?: run { getElementJQueryD()?.`val`(null) getElementJQueryD()?.datetimepicker("update", null) @@ -179,7 +180,7 @@ open class DateTimeInput( protected open fun changeValue() { val v = getElementJQuery()?.`val`() as String? if (v != null && v.isNotEmpty()) { - this.value = v.toDateF(format) + this.value = v.toKDateF(format) } else { this.value = null } @@ -276,7 +277,7 @@ open class DateTimeInput( * It takes the same parameters as the constructor of the built component. */ fun Container.dateTimeInput( - value: Date? = null, format: String = "YYYY-MM-DD HH:mm", classes: Set = setOf(), + value: KDate? = null, format: String = "YYYY-MM-DD HH:mm", classes: Set = setOf(), init: (DateTimeInput.() -> Unit)? = null ): DateTimeInput { val dateTimeInput = DateTimeInput(value, format, classes).apply { init?.invoke(this) } diff --git a/src/main/kotlin/pl/treksoft/kvision/form/upload/Upload.kt b/src/main/kotlin/pl/treksoft/kvision/form/upload/Upload.kt index e6b397eb..5e3ac0df 100644 --- a/src/main/kotlin/pl/treksoft/kvision/form/upload/Upload.kt +++ b/src/main/kotlin/pl/treksoft/kvision/form/upload/Upload.kt @@ -3,13 +3,15 @@ */ package pl.treksoft.kvision.form.upload +import org.w3c.files.File import pl.treksoft.kvision.core.Container import pl.treksoft.kvision.core.StringBoolPair import pl.treksoft.kvision.core.Widget import pl.treksoft.kvision.form.FieldLabel -import pl.treksoft.kvision.form.FilesFormControl import pl.treksoft.kvision.form.HelpBlock +import pl.treksoft.kvision.form.KFilesFormControl import pl.treksoft.kvision.panel.SimplePanel +import pl.treksoft.kvision.types.KFile import pl.treksoft.kvision.utils.SnOn /** @@ -25,7 +27,7 @@ import pl.treksoft.kvision.utils.SnOn open class Upload( uploadUrl: String? = null, multiple: Boolean = false, label: String? = null, rich: Boolean = false -) : SimplePanel(setOf("form-group")), FilesFormControl { +) : SimplePanel(setOf("form-group")), KFilesFormControl { /** * File input value. @@ -227,6 +229,15 @@ open class Upload( return input.getValueAsString() } + /** + * Returns the native JavaScript File object. + * @param kFile KFile object + * @return File object + */ + fun getNativeFile(kFile: KFile): File? { + return input.getNativeFile(kFile) + } + /** * Resets the file input control. */ diff --git a/src/main/kotlin/pl/treksoft/kvision/form/upload/UploadInput.kt b/src/main/kotlin/pl/treksoft/kvision/form/upload/UploadInput.kt index d77a9b9b..645cc69b 100644 --- a/src/main/kotlin/pl/treksoft/kvision/form/upload/UploadInput.kt +++ b/src/main/kotlin/pl/treksoft/kvision/form/upload/UploadInput.kt @@ -11,6 +11,7 @@ import pl.treksoft.kvision.core.StringPair import pl.treksoft.kvision.core.Widget import pl.treksoft.kvision.form.FormInput import pl.treksoft.kvision.form.InputSize +import pl.treksoft.kvision.types.KFile import pl.treksoft.kvision.utils.obj /** @@ -28,7 +29,7 @@ open class UploadInput(uploadUrl: String? = null, multiple: Boolean = false, cla /** * File input value. */ - var value: List? + var value: List? get() = getValue() set(value) { if (value == null) resetInput() @@ -112,6 +113,8 @@ open class UploadInput(uploadUrl: String? = null, multiple: Boolean = false, cla */ override var size: InputSize? by refreshOnUpdate() + private val nativeFiles: MutableMap = mutableMapOf() + override fun render(): VNode { return render("input") } @@ -139,7 +142,7 @@ open class UploadInput(uploadUrl: String? = null, multiple: Boolean = false, cla return sn } - private fun getValue(): List? { + private fun getValue(): List? { val v = getFiles() return if (v.isNotEmpty()) v else null } @@ -217,8 +220,22 @@ open class UploadInput(uploadUrl: String? = null, multiple: Boolean = false, cla getElementJQueryD()?.fileinput("unlock") } - private fun getFiles(): List { - return (getElementJQueryD()?.fileinput("getFileStack") as Array).toList() + /** + * Returns the native JavaScript File object. + * @param kFile KFile object + * @return File object + */ + fun getNativeFile(kFile: KFile): File? { + return nativeFiles[kFile] + } + + private fun getFiles(): List { + nativeFiles.clear() + return (getElementJQueryD()?.fileinput("getFileStack") as Array).toList().map { + val kFile = KFile(it.name, it.size, null) + nativeFiles[kFile] = it + kFile + } } /** diff --git a/src/main/kotlin/pl/treksoft/kvision/remote/Jooby.kt b/src/main/kotlin/pl/treksoft/kvision/remote/Jooby.kt new file mode 100644 index 00000000..a5c580d6 --- /dev/null +++ b/src/main/kotlin/pl/treksoft/kvision/remote/Jooby.kt @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2017-present Robert Jaros + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package pl.treksoft.kvision.remote + +/** + * A Jooby based server. + * Not used on the js platform. + */ +actual open class JoobyServer + +/** + * A server request. + * Not used on the js platform. + */ +actual interface Request diff --git a/src/main/kotlin/pl/treksoft/kvision/remote/RemoteAgent.kt b/src/main/kotlin/pl/treksoft/kvision/remote/RemoteAgent.kt new file mode 100644 index 00000000..3f7276f0 --- /dev/null +++ b/src/main/kotlin/pl/treksoft/kvision/remote/RemoteAgent.kt @@ -0,0 +1,417 @@ +/* + * Copyright (c) 2017-present Robert Jaros + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package pl.treksoft.kvision.remote + +import kotlinx.coroutines.experimental.Deferred +import kotlinx.serialization.KSerializer +import kotlinx.serialization.internal.ArrayListSerializer +import kotlinx.serialization.internal.BooleanSerializer +import kotlinx.serialization.internal.CharSerializer +import kotlinx.serialization.internal.DoubleSerializer +import kotlinx.serialization.internal.LongSerializer +import kotlinx.serialization.internal.StringSerializer +import kotlinx.serialization.json.JSON +import kotlinx.serialization.list +import kotlinx.serialization.serializer +import pl.treksoft.jquery.JQueryXHR +import pl.treksoft.jquery.jQuery +import pl.treksoft.kvision.utils.obj +import kotlin.js.Promise +import kotlin.js.js +import kotlin.js.undefined +import kotlin.reflect.KClass +import kotlin.js.JSON as NativeJSON + +internal class NonStandardTypeException(type: String) : Exception("Non standard type: $type!") + +/** + * Client side agent for remote calls. + */ +@Suppress("EXPERIMENTAL_FEATURE_WARNING", "LargeClass", "TooManyFunctions") +open class RemoteAgent(val serviceManager: ServiceManager) { + + /** + * Executes defined call to a remote web service. + */ + inline fun call(noinline function: T.(Request?) -> Deferred): Promise { + val url = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return ajaxCall(url, null).then { + try { + deserialize(it, RET::class.js.name) + } catch (t: NonStandardTypeException) { + JSON.parse(RET::class.serializer(), it) + } + } + } + + /** + * Executes defined call to a remote web service. + */ + inline fun call(noinline function: T.(Request?) -> Deferred>): Promise> { + val url = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return ajaxCall(url, null).then { + try { + deserializeLists(it, RET::class.js.name) + } catch (t: NonStandardTypeException) { + JSON.parse(RET::class.serializer().list, it) + } + } + } + + /** + * Executes defined call to a remote web service. + */ + inline fun call( + noinline function: T.(PAR, Request?) -> Deferred, + p: PAR, serializer: KSerializer? = null + ): Promise { + val data = serialize(p, serializer) + val url = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return ajaxCall(url, data).then { + try { + @Suppress("UNCHECKED_CAST") + deserialize(it, (RET::class as KClass).js.name) + } catch (t: NonStandardTypeException) { + JSON.parse(RET::class.serializer(), it) + } + } + } + + /** + * Executes defined call to a remote web service. + */ + inline fun call( + noinline function: T.(PAR, Request?) -> Deferred>, + p: PAR, serializer: KSerializer? = null + ): Promise> { + val data = serialize(p, serializer) + val url = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return ajaxCall(url, data).then { + try { + deserializeLists(it, RET::class.js.name) + } catch (t: NonStandardTypeException) { + JSON.parse(RET::class.serializer().list, it) + } + } + } + + /** + * Executes defined call to a remote web service. + */ + inline fun call( + noinline function: T.(PAR1, PAR2, Request?) -> Deferred, + p1: PAR1, p2: PAR2, serializer1: KSerializer? = null, serializer2: KSerializer? = null + ): Promise { + val data1 = serialize(p1, serializer1) + val data2 = serialize(p2, serializer2) + val data = "[ $data1 , $data2 ]" + val url = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return ajaxCall(url, data).then { + try { + deserialize(it, RET::class.js.name) + } catch (t: NonStandardTypeException) { + JSON.parse(RET::class.serializer(), it) + } + } + } + + /** + * Executes defined call to a remote web service. + */ + inline fun call( + noinline function: T.(PAR1, PAR2, Request?) -> Deferred>, + p1: PAR1, p2: PAR2, serializer1: KSerializer? = null, serializer2: KSerializer? = null + ): Promise> { + val data1 = serialize(p1, serializer1) + val data2 = serialize(p2, serializer2) + val data = "[ $data1 , $data2 ]" + val url = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return ajaxCall(url, data).then { + try { + deserializeLists(it, RET::class.js.name) + } catch (t: NonStandardTypeException) { + JSON.parse(RET::class.serializer().list, it) + } + } + } + + /** + * Executes defined call to a remote web service. + */ + inline fun call( + noinline function: T.(PAR1, PAR2, PAR3, Request?) -> Deferred, + p1: PAR1, p2: PAR2, p3: PAR3, serializer1: KSerializer? = null, serializer2: KSerializer? = null, + serializer3: KSerializer? = null + ): Promise { + val data1 = serialize(p1, serializer1) + val data2 = serialize(p2, serializer2) + val data3 = serialize(p3, serializer3) + val data = "[ $data1 , $data2 , $data3 ]" + val url = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return ajaxCall(url, data).then { + try { + deserialize(it, RET::class.js.name) + } catch (t: NonStandardTypeException) { + JSON.parse(RET::class.serializer(), it) + } + } + } + + /** + * Executes defined call to a remote web service. + */ + inline fun call( + noinline function: T.(PAR1, PAR2, PAR3, Request?) -> Deferred>, + p1: PAR1, p2: PAR2, p3: PAR3, serializer1: KSerializer? = null, serializer2: KSerializer? = null, + serializer3: KSerializer? = null + ): Promise> { + val data1 = serialize(p1, serializer1) + val data2 = serialize(p2, serializer2) + val data3 = serialize(p3, serializer3) + val data = "[ $data1 , $data2 , $data3 ]" + val url = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return ajaxCall(url, data).then { + try { + deserializeLists(it, RET::class.js.name) + } catch (t: NonStandardTypeException) { + JSON.parse(RET::class.serializer().list, it) + } + } + } + + /** + * Executes defined call to a remote web service. + */ + inline fun call( + noinline function: T.(PAR1, PAR2, PAR3, PAR4, Request?) -> Deferred, + p1: PAR1, + p2: PAR2, + p3: PAR3, + p4: PAR4, + serializer1: KSerializer? = null, + serializer2: KSerializer? = null, + serializer3: KSerializer? = null, + serializer4: KSerializer? = null + ): Promise { + val data1 = serialize(p1, serializer1) + val data2 = serialize(p2, serializer2) + val data3 = serialize(p3, serializer3) + val data4 = serialize(p4, serializer4) + val data = "[ $data1 , $data2 , $data3 , $data4 ]" + val url = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return ajaxCall(url, data).then { + try { + deserialize(it, RET::class.js.name) + } catch (t: NonStandardTypeException) { + JSON.parse(RET::class.serializer(), it) + } + } + } + + /** + * Executes defined call to a remote web service. + */ + inline fun call( + noinline function: T.(PAR1, PAR2, PAR3, PAR4, Request?) -> Deferred>, + p1: PAR1, + p2: PAR2, + p3: PAR3, + p4: PAR4, + serializer1: KSerializer? = null, + serializer2: KSerializer? = null, + serializer3: KSerializer? = null, + serializer4: KSerializer? = null + ): Promise> { + val data1 = serialize(p1, serializer1) + val data2 = serialize(p2, serializer2) + val data3 = serialize(p3, serializer3) + val data4 = serialize(p4, serializer4) + val data = "[ $data1 , $data2 , $data3 , $data4 ]" + val url = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return ajaxCall(url, data).then { + try { + deserializeLists(it, RET::class.js.name) + } catch (t: NonStandardTypeException) { + JSON.parse(RET::class.serializer().list, it) + } + } + } + + /** + * Executes defined call to a remote web service. + */ + @Suppress("LongParameterList") + inline fun call( + noinline function: T.(PAR1, PAR2, PAR3, PAR4, PAR5, Request?) -> Deferred, + p1: PAR1, + p2: PAR2, + p3: PAR3, + p4: PAR4, + p5: PAR5, + serializer1: KSerializer? = null, + serializer2: KSerializer? = null, + serializer3: KSerializer? = null, + serializer4: KSerializer? = null, + serializer5: KSerializer? = null + ): Promise { + val data1 = serialize(p1, serializer1) + val data2 = serialize(p2, serializer2) + val data3 = serialize(p3, serializer3) + val data4 = serialize(p4, serializer4) + val data5 = serialize(p5, serializer5) + val data = "[ $data1 , $data2 , $data3 , $data4 , $data5 ]" + val url = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return ajaxCall(url, data).then { + try { + deserialize(it, RET::class.js.name) + } catch (t: NonStandardTypeException) { + JSON.parse(RET::class.serializer(), it) + } + } + } + + /** + * Executes defined call to a remote web service. + */ + @Suppress("LongParameterList") + inline fun call( + noinline function: T.(PAR1, PAR2, PAR3, PAR4, PAR5, Request?) -> Deferred>, + p1: PAR1, + p2: PAR2, + p3: PAR3, + p4: PAR4, + p5: PAR5, + serializer1: KSerializer? = null, + serializer2: KSerializer? = null, + serializer3: KSerializer? = null, + serializer4: KSerializer? = null, + serializer5: KSerializer? = null + ): Promise> { + val data1 = serialize(p1, serializer1) + val data2 = serialize(p2, serializer2) + val data3 = serialize(p3, serializer3) + val data4 = serialize(p4, serializer4) + val data5 = serialize(p5, serializer5) + val data = "[ $data1 , $data2 , $data3 , $data4 , $data5 ]" + val url = + serviceManager.getCalls()[function.toString()] ?: throw IllegalStateException("Function not specified!") + return ajaxCall(url, data).then { + try { + deserializeLists(it, RET::class.js.name) + } catch (t: NonStandardTypeException) { + JSON.parse(RET::class.serializer().list, it) + } + } + } + + /** + * @suppress + * Internal function + */ + @Suppress("UnsafeCastFromDynamic") + fun ajaxCall(url: String, data: Any?): Promise = + Promise({ resolve, reject -> + jQuery.ajax(url, obj { + this.contentType = "application/json" + this.data = data + this.method = "POST" + this.success = + { data: Any, _: Any, _: Any -> + resolve(NativeJSON.stringify(data)) + } + this.error = + { xhr: JQueryXHR, _: String, errorText: String -> + val message = if (xhr.responseJSON != null && xhr.responseJSON != undefined) { + xhr.responseJSON.toString() + } else { + errorText + } + reject(Exception(message)) + } + }) + }) + + /** + * @suppress + * Internal function + */ + @Suppress("TooGenericExceptionCaught") + inline fun serialize(value: PAR, serializer: KSerializer?): String? { + return value?.let { + if (serializer != null) { + JSON.stringify(serializer, it) + } else { + try { + @Suppress("UNCHECKED_CAST") + JSON.stringify((PAR::class as KClass).serializer(), it as Any) + } catch (e: Throwable) { + it.toString() + } + } + } + } + + /** + * @suppress + * Internal function + */ + @Suppress("UNCHECKED_CAST") + fun deserialize(value: String, type: String): RET { + return when (type) { + "String" -> JSON.parse(StringSerializer, value) as RET + "Number" -> JSON.parse(DoubleSerializer, value) as RET + "Long" -> JSON.parse(LongSerializer, value) as RET + "Boolean" -> JSON.parse(BooleanSerializer, value) as RET + "Char" -> JSON.parse(CharSerializer, value) as RET + else -> throw NonStandardTypeException(type) + } + } + + /** + * @suppress + * Internal function + */ + @Suppress("UNCHECKED_CAST") + fun deserializeLists(value: String, type: String): List { + return when (type) { + "String" -> JSON.parse(ArrayListSerializer(StringSerializer), value) as List + "Number" -> JSON.parse(ArrayListSerializer(DoubleSerializer), value) as List + "Long" -> JSON.parse(ArrayListSerializer(LongSerializer), value) as List + "Boolean" -> JSON.parse(ArrayListSerializer(BooleanSerializer), value) as List + "Char" -> JSON.parse(ArrayListSerializer(CharSerializer), value) as List + else -> throw NonStandardTypeException(type) + } + } +} diff --git a/src/main/kotlin/pl/treksoft/kvision/remote/ServiceManager.kt b/src/main/kotlin/pl/treksoft/kvision/remote/ServiceManager.kt new file mode 100644 index 00000000..cd42f038 --- /dev/null +++ b/src/main/kotlin/pl/treksoft/kvision/remote/ServiceManager.kt @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2017-present Robert Jaros + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package pl.treksoft.kvision.remote + +import kotlinx.coroutines.experimental.Deferred + +/** + * Multiplatform service manager. + */ +actual open class ServiceManager actual constructor(service: T?) { + protected val calls: MutableMap = mutableMapOf() + + /** + * Binds a given route with a function of the receiver. + * @param route a route + * @param function a function of the receiver + */ + protected actual inline fun bind( + route: String, + noinline function: T.(Request?) -> Deferred + ) { + calls[function.toString()] = "$SERVICE_PREFIX/$route" + } + + /** + * Binds a given route with a function of the receiver. + * @param route a route + * @param function a function of the receiver + */ + protected actual inline fun bind( + route: String, + noinline function: T.(PAR, Request?) -> Deferred + ) { + calls[function.toString()] = "$SERVICE_PREFIX/$route" + } + + /** + * Binds a given route with a function of the receiver. + * @param route a route + * @param function a function of the receiver + */ + protected actual inline fun bind( + route: String, + noinline function: T.(PAR1, PAR2, Request?) -> Deferred + ) { + calls[function.toString()] = "$SERVICE_PREFIX/$route" + } + + /** + * Binds a given route with a function of the receiver. + * @param route a route + * @param function a function of the receiver + */ + protected actual inline fun bind( + route: String, + noinline function: T.(PAR1, PAR2, PAR3, Request?) -> Deferred + ) { + calls[function.toString()] = "$SERVICE_PREFIX/$route" + } + + /** + * Binds a given route with a function of the receiver. + * @param route a route + * @param function a function of the receiver + */ + protected actual inline fun bind( + route: String, + noinline function: T.(PAR1, PAR2, PAR3, PAR4, Request?) -> Deferred + ) { + calls[function.toString()] = "$SERVICE_PREFIX/$route" + } + + /** + * Binds a given route with a function of the receiver. + * @param route a route + * @param function a function of the receiver + */ + protected actual inline fun bind( + route: String, + noinline function: T.(PAR1, PAR2, PAR3, PAR4, PAR5, Request?) -> Deferred + ) { + calls[function.toString()] = "$SERVICE_PREFIX/$route" + } + + /** + * Applies all defined routes to the given server. + * Not used on the js platform. + */ + actual fun applyRoutes(k: JoobyServer) { + } + + /** + * Returns the list of defined bindings. + * Not used on the jvm platform. + */ + actual fun getCalls(): Map = calls +} diff --git a/src/main/kotlin/pl/treksoft/kvision/types/KDate.kt b/src/main/kotlin/pl/treksoft/kvision/types/KDate.kt new file mode 100644 index 00000000..798a02be --- /dev/null +++ b/src/main/kotlin/pl/treksoft/kvision/types/KDate.kt @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2017-present Robert Jaros + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package pl.treksoft.kvision.types + +import pl.treksoft.kvision.utils.toDateF +import pl.treksoft.kvision.utils.toStringF +import kotlin.js.Date + +@Suppress("MayBeConstant", "TopLevelPropertyNaming") +actual val KDATE_FORMAT = "YYYY-MM-DD HH:mm:ss" + +internal actual fun nowDate(): KDate = + KDate(Date().getTime().toLong()) + +internal actual fun String.toKDateF(format: String): KDate = + KDate(this.toDateF(format).getTime().toLong()) + +internal actual fun KDate.toStringF(format: String) = this.toJS().toStringF(format) + +fun KDate.toJS(): kotlin.js.Date = kotlin.js.Date(this.time) -- cgit