From 913105c5f33528b64b34ad4273050d149c750234 Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Mon, 26 Nov 2018 12:50:29 +0100 Subject: [PATCH 01/58] Update to SDK level 28 and AndroidX --- build.gradle | 10 +++++----- gradle.properties | 1 + .../at/bitfire/ical4android/AndroidCalendarTest.kt | 8 ++++---- .../java/at/bitfire/ical4android/AndroidEventTest.kt | 8 ++++---- .../at/bitfire/ical4android/AndroidTaskListTest.kt | 4 ++-- .../java/at/bitfire/ical4android/AndroidTaskTest.kt | 4 ++-- .../java/at/bitfire/ical4android/MiscUtilsTest.kt | 3 ++- .../java/at/bitfire/ical4android/TestUtils.kt | 2 +- .../java/at/bitfire/ical4android/AndroidCalendar.kt | 3 ++- src/test/java/at/bitfire/ical4android/EventTest.kt | 5 ++--- 10 files changed, 25 insertions(+), 23 deletions(-) diff --git a/build.gradle b/build.gradle index ff7a090..7abf287 100644 --- a/build.gradle +++ b/build.gradle @@ -1,6 +1,6 @@ buildscript { - ext.kotlin_version = '1.2.71' + ext.kotlin_version = '1.3.10' ext.dokka_version = '0.9.17' repositories { @@ -9,7 +9,7 @@ buildscript { } dependencies { - classpath 'com.android.tools.build:gradle:3.2.0' + classpath 'com.android.tools.build:gradle:3.2.1' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath "org.jetbrains.dokka:dokka-android-gradle-plugin:${dokka_version}" } @@ -36,7 +36,7 @@ android { minSdkVersion 19 targetSdkVersion 28 - testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" buildConfigField "String", "version_ical4j", "\"$ical4j_version\"" } @@ -66,8 +66,8 @@ dependencies { api "org.mnode.ical4j:ical4j:$ical4j_version" implementation 'org.slf4j:slf4j-jdk14:1.7.25' - androidTestImplementation 'com.android.support.test:runner:1.0.2' - androidTestImplementation 'com.android.support.test:rules:1.0.2' + androidTestImplementation 'androidx.test:runner:1.1.0' + androidTestImplementation 'androidx.test:rules:1.1.0' testImplementation 'junit:junit:4.12' } diff --git a/gradle.properties b/gradle.properties index 8bd86f6..d9cf55d 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1 +1,2 @@ org.gradle.jvmargs=-Xmx1536M +android.useAndroidX=true diff --git a/src/androidTest/java/at/bitfire/ical4android/AndroidCalendarTest.kt b/src/androidTest/java/at/bitfire/ical4android/AndroidCalendarTest.kt index f0be1b6..d7d86eb 100644 --- a/src/androidTest/java/at/bitfire/ical4android/AndroidCalendarTest.kt +++ b/src/androidTest/java/at/bitfire/ical4android/AndroidCalendarTest.kt @@ -15,9 +15,9 @@ import android.content.ContentUris import android.content.ContentValues import android.os.Build import android.provider.CalendarContract -import android.support.test.InstrumentationRegistry -import android.support.test.filters.MediumTest -import android.support.test.rule.GrantPermissionRule +import androidx.test.filters.MediumTest +import androidx.test.platform.app.InstrumentationRegistry +import androidx.test.rule.GrantPermissionRule import at.bitfire.ical4android.impl.TestCalendar import org.junit.After import org.junit.Assert.assertEquals @@ -41,7 +41,7 @@ class AndroidCalendarTest { @Before fun prepare() { - provider = InstrumentationRegistry.getInstrumentation().targetContext.contentResolver.acquireContentProviderClient(CalendarContract.AUTHORITY) + provider = InstrumentationRegistry.getInstrumentation().targetContext.contentResolver.acquireContentProviderClient(CalendarContract.AUTHORITY)!! } @After diff --git a/src/androidTest/java/at/bitfire/ical4android/AndroidEventTest.kt b/src/androidTest/java/at/bitfire/ical4android/AndroidEventTest.kt index 83f0787..3200a56 100644 --- a/src/androidTest/java/at/bitfire/ical4android/AndroidEventTest.kt +++ b/src/androidTest/java/at/bitfire/ical4android/AndroidEventTest.kt @@ -15,9 +15,9 @@ import android.content.ContentValues import android.net.Uri import android.os.Build import android.provider.CalendarContract -import android.support.test.InstrumentationRegistry.getInstrumentation -import android.support.test.filters.MediumTest -import android.support.test.rule.GrantPermissionRule +import androidx.test.filters.MediumTest +import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation +import androidx.test.rule.GrantPermissionRule import at.bitfire.ical4android.AndroidCalendar.Companion.syncAdapterURI import at.bitfire.ical4android.impl.TestCalendar import at.bitfire.ical4android.impl.TestEvent @@ -53,7 +53,7 @@ class AndroidEventTest { @Before fun prepare() { - provider = getInstrumentation().targetContext.contentResolver.acquireContentProviderClient(CalendarContract.AUTHORITY) + provider = getInstrumentation().targetContext.contentResolver.acquireContentProviderClient(CalendarContract.AUTHORITY)!! AndroidCalendar.insertColors(provider, testAccount) diff --git a/src/androidTest/java/at/bitfire/ical4android/AndroidTaskListTest.kt b/src/androidTest/java/at/bitfire/ical4android/AndroidTaskListTest.kt index 9da780b..ce04501 100644 --- a/src/androidTest/java/at/bitfire/ical4android/AndroidTaskListTest.kt +++ b/src/androidTest/java/at/bitfire/ical4android/AndroidTaskListTest.kt @@ -11,8 +11,8 @@ package at.bitfire.ical4android import android.accounts.Account import android.content.ContentUris import android.content.ContentValues -import android.support.test.InstrumentationRegistry.getInstrumentation -import android.support.test.filters.MediumTest +import androidx.test.filters.MediumTest +import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation import at.bitfire.ical4android.impl.TestTaskList import org.dmfs.tasks.contract.TaskContract import org.junit.After diff --git a/src/androidTest/java/at/bitfire/ical4android/AndroidTaskTest.kt b/src/androidTest/java/at/bitfire/ical4android/AndroidTaskTest.kt index f2210b8..37d8b53 100644 --- a/src/androidTest/java/at/bitfire/ical4android/AndroidTaskTest.kt +++ b/src/androidTest/java/at/bitfire/ical4android/AndroidTaskTest.kt @@ -11,8 +11,8 @@ package at.bitfire.ical4android import android.accounts.Account import android.content.ContentUris import android.net.Uri -import android.support.test.InstrumentationRegistry.getInstrumentation -import android.support.test.filters.MediumTest +import androidx.test.filters.MediumTest +import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation import at.bitfire.ical4android.impl.TestTask import at.bitfire.ical4android.impl.TestTaskList import net.fortuna.ical4j.model.Date diff --git a/src/androidTest/java/at/bitfire/ical4android/MiscUtilsTest.kt b/src/androidTest/java/at/bitfire/ical4android/MiscUtilsTest.kt index 8a0cfa7..f5c8183 100644 --- a/src/androidTest/java/at/bitfire/ical4android/MiscUtilsTest.kt +++ b/src/androidTest/java/at/bitfire/ical4android/MiscUtilsTest.kt @@ -9,7 +9,7 @@ package at.bitfire.ical4android import android.content.ContentValues -import android.support.test.filters.SmallTest +import androidx.test.filters.SmallTest import net.fortuna.ical4j.data.CalendarBuilder import net.fortuna.ical4j.model.Date import net.fortuna.ical4j.model.DateTime @@ -98,6 +98,7 @@ class MiscUtilsTest { } + @Suppress("unused") private class TestClass { private val s = "test" val i = 2 diff --git a/src/androidTest/java/at/bitfire/ical4android/TestUtils.kt b/src/androidTest/java/at/bitfire/ical4android/TestUtils.kt index e7a3c96..1125a04 100644 --- a/src/androidTest/java/at/bitfire/ical4android/TestUtils.kt +++ b/src/androidTest/java/at/bitfire/ical4android/TestUtils.kt @@ -8,7 +8,7 @@ package at.bitfire.ical4android -import android.support.test.runner.permission.PermissionRequester +import androidx.test.runner.permission.PermissionRequester import junit.framework.AssertionFailedError object TestUtils { diff --git a/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt b/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt index e934f06..9fb330f 100644 --- a/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt +++ b/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt @@ -44,7 +44,8 @@ abstract class AndroidCalendar( info.put(Calendars.ALLOWED_ATTENDEE_TYPES, "${Attendees.TYPE_NONE},${Attendees.TYPE_OPTIONAL},${Attendees.TYPE_REQUIRED},${Attendees.TYPE_RESOURCE}") Constants.log.info("Creating local calendar: " + info.toString()) - return provider.insert(syncAdapterURI(Calendars.CONTENT_URI, account), info) + return provider.insert(syncAdapterURI(Calendars.CONTENT_URI, account), info) ?: + throw Exception("Couldn't create calendar: provider returned null") } fun insertColors(provider: ContentProviderClient, account: Account) { diff --git a/src/test/java/at/bitfire/ical4android/EventTest.kt b/src/test/java/at/bitfire/ical4android/EventTest.kt index f427103..c3e7959 100644 --- a/src/test/java/at/bitfire/ical4android/EventTest.kt +++ b/src/test/java/at/bitfire/ical4android/EventTest.kt @@ -11,7 +11,6 @@ import org.junit.Assert.* import org.junit.Test import java.io.FileNotFoundException import java.io.InputStreamReader -import java.lang.AssertionError import java.nio.charset.Charset class EventTest { @@ -20,7 +19,7 @@ class EventTest { @Test fun testCalendarProperties() { - javaClass.classLoader.getResourceAsStream("events/multiple.ics").use { stream -> + javaClass.classLoader!!.getResourceAsStream("events/multiple.ics").use { stream -> val properties = mutableMapOf() Event.fromReader(InputStreamReader(stream, Charsets.UTF_8), properties) assertEquals(1, properties.size) @@ -201,7 +200,7 @@ class EventTest { } private fun parseCalendar(fname: String, charset: Charset = Charsets.UTF_8): List = - javaClass.classLoader.getResourceAsStream("events/$fname").use { stream -> + javaClass.classLoader!!.getResourceAsStream("events/$fname").use { stream -> return Event.fromReader(InputStreamReader(stream, charset)) } -- GitLab From 3450b0d40ce2abb2ab6303571ec96bec750750ce Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Fri, 30 Nov 2018 13:08:24 +0100 Subject: [PATCH 02/58] Don't do emulator checks (because we can only use shared runners at the moment); minor lint --- .gitlab-ci.yml | 7 ++++--- build.gradle | 6 ------ .../at/bitfire/ical4android/AndroidCalendarTest.kt | 1 + .../at/bitfire/ical4android/AndroidEventTest.kt | 1 + .../java/at/bitfire/ical4android/AndroidCalendar.kt | 10 +++++----- .../java/at/bitfire/ical4android/AndroidTaskList.kt | 13 +++++++------ .../java/at/bitfire/ical4android/TaskProvider.kt | 2 +- src/test/java/at/bitfire/ical4android/TaskTest.kt | 2 +- 8 files changed, 20 insertions(+), 22 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index ca8e81f..b8a390c 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -9,9 +9,10 @@ cache: test: script: - - (cd /sdk/emulator; ./emulator @test -no-audio -no-window & wait-for-emulator.sh) - - adb install src/androidTest/resources/org.dmfs.tasks_6880.apk - - ./gradlew check connectedCheck +# - (cd /sdk/emulator; ./emulator @test -no-audio -no-window & wait-for-emulator.sh) +# - adb install src/androidTest/resources/org.dmfs.tasks_6880.apk +# - ./gradlew check connectedCheck + - ./gradlew check artifacts: paths: - build/outputs/lint-results-debug.html diff --git a/build.gradle b/build.gradle index 7abf287..656f2ef 100644 --- a/build.gradle +++ b/build.gradle @@ -40,12 +40,6 @@ android { buildConfigField "String", "version_ical4j", "\"$ical4j_version\"" } - buildTypes { - release { - minifyEnabled false - proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' - } - } lintOptions { disable 'AllowBackup' disable 'InvalidPackage' diff --git a/src/androidTest/java/at/bitfire/ical4android/AndroidCalendarTest.kt b/src/androidTest/java/at/bitfire/ical4android/AndroidCalendarTest.kt index d7d86eb..aed63af 100644 --- a/src/androidTest/java/at/bitfire/ical4android/AndroidCalendarTest.kt +++ b/src/androidTest/java/at/bitfire/ical4android/AndroidCalendarTest.kt @@ -46,6 +46,7 @@ class AndroidCalendarTest { @After fun shutdown() { + @Suppress("DEPRECATION") if (Build.VERSION.SDK_INT >= 24) provider.close() else diff --git a/src/androidTest/java/at/bitfire/ical4android/AndroidEventTest.kt b/src/androidTest/java/at/bitfire/ical4android/AndroidEventTest.kt index 3200a56..7321e69 100644 --- a/src/androidTest/java/at/bitfire/ical4android/AndroidEventTest.kt +++ b/src/androidTest/java/at/bitfire/ical4android/AndroidEventTest.kt @@ -67,6 +67,7 @@ class AndroidEventTest { fun shutdown() { calendar.delete() + @Suppress("DEPRECATION") if (Build.VERSION.SDK_INT >= 24) provider.close() else diff --git a/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt b/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt index 9fb330f..165d1db 100644 --- a/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt +++ b/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt @@ -151,13 +151,13 @@ abstract class AndroidCalendar( /** * Queries events from this calendar. Adds a WHERE clause that restricts the * query to [Events.CALENDAR_ID] = [id]. - * @param where selection - * @param whereArgs arguments for selection + * @param _where selection + * @param _whereArgs arguments for selection * @return events from this calendar which match the selection */ - fun queryEvents(where: String? = null, whereArgs: Array? = null): List { - val where = "(${where ?: "1"}) AND " + Events.CALENDAR_ID + "=?" - val whereArgs = (whereArgs ?: arrayOf()) + id.toString() + fun queryEvents(_where: String? = null, _whereArgs: Array? = null): List { + val where = "(${_where ?: "1"}) AND " + Events.CALENDAR_ID + "=?" + val whereArgs = (_whereArgs ?: arrayOf()) + id.toString() val events = LinkedList() provider.query(eventsSyncURI(), null, where, whereArgs, null)?.use { cursor -> diff --git a/src/main/java/at/bitfire/ical4android/AndroidTaskList.kt b/src/main/java/at/bitfire/ical4android/AndroidTaskList.kt index b8daad8..49a08ba 100644 --- a/src/main/java/at/bitfire/ical4android/AndroidTaskList.kt +++ b/src/main/java/at/bitfire/ical4android/AndroidTaskList.kt @@ -59,7 +59,8 @@ abstract class AndroidTaskList( info.put(TaskLists.ACCESS_LEVEL, 0) Constants.log.info("Creating local task list: " + info.toString()) - return provider.client.insert(TaskProvider.syncAdapterUri(provider.taskListsUri(), account), info) + return provider.client.insert(TaskProvider.syncAdapterUri(provider.taskListsUri(), account), info) ?: + throw CalendarStorageException("Couldn't create task list (empty result from provider)") } fun> findByID(account: Account, provider: TaskProvider, factory: AndroidTaskListFactory, id: Long): T { @@ -113,13 +114,13 @@ abstract class AndroidTaskList( /** * Queries tasks from this task list. Adds a WHERE clause that restricts the * query to [Tasks.LIST_ID] = [id]. - * @param where selection - * @param whereArgs arguments for selection + * @param _where selection + * @param _whereArgs arguments for selection * @return events from this task list which match the selection */ - fun queryTasks(where: String? = null, whereArgs: Array? = null): List { - val where = "(${where ?: "1"}) AND ${Tasks.LIST_ID}=?" - val whereArgs = (whereArgs ?: arrayOf()) + id.toString() + fun queryTasks(_where: String? = null, _whereArgs: Array? = null): List { + val where = "(${_where ?: "1"}) AND ${Tasks.LIST_ID}=?" + val whereArgs = (_whereArgs ?: arrayOf()) + id.toString() val tasks = LinkedList() provider.client.query( diff --git a/src/main/java/at/bitfire/ical4android/TaskProvider.kt b/src/main/java/at/bitfire/ical4android/TaskProvider.kt index 78680fb..3bf92b5 100644 --- a/src/main/java/at/bitfire/ical4android/TaskProvider.kt +++ b/src/main/java/at/bitfire/ical4android/TaskProvider.kt @@ -113,7 +113,7 @@ class TaskProvider private constructor( class ProviderTooOldException( val provider: ProviderName, - val installedVersionCode: Int, + installedVersionCode: Int, val installedVersionName: String ): Exception("Package ${provider.packageName} has version $installedVersionName ($installedVersionCode), " + "required: ${provider.minVersionName} (${provider.minVersionCode})") diff --git a/src/test/java/at/bitfire/ical4android/TaskTest.kt b/src/test/java/at/bitfire/ical4android/TaskTest.kt index d60602e..b72b9bc 100644 --- a/src/test/java/at/bitfire/ical4android/TaskTest.kt +++ b/src/test/java/at/bitfire/ical4android/TaskTest.kt @@ -98,7 +98,7 @@ class TaskTest { /* helpers */ private fun parseCalendar(fname: String, charset: Charset = Charsets.UTF_8): Task { - javaClass.classLoader.getResourceAsStream("tasks/$fname").use { stream -> + javaClass.classLoader!!.getResourceAsStream("tasks/$fname").use { stream -> return Task.fromReader(InputStreamReader(stream, charset)).first() } } -- GitLab From 3149daac068661f3f8cfeaa6e601235fe42cc25e Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Sat, 1 Dec 2018 22:11:44 +0100 Subject: [PATCH 03/58] Save/restore unknown properties of tasks --- .../java/at/bitfire/ical4android/Event.kt | 2 +- src/main/java/at/bitfire/ical4android/Task.kt | 45 ++++++++++--------- 2 files changed, 26 insertions(+), 21 deletions(-) diff --git a/src/main/java/at/bitfire/ical4android/Event.kt b/src/main/java/at/bitfire/ical4android/Event.kt index 8c258ed..ab2b2c1 100644 --- a/src/main/java/at/bitfire/ical4android/Event.kt +++ b/src/main/java/at/bitfire/ical4android/Event.kt @@ -176,7 +176,7 @@ class Event: ICalendar() { is Organizer -> e.organizer = prop is Attendee -> e.attendees += prop is LastModified -> e.lastModified = prop - is ProdId, is DtStamp -> { /* don't save those as unknown properties */ } + is ProdId, is DtStamp -> { /* don't save these as unknown properties */ } else -> e.unknownProperties += prop } diff --git a/src/main/java/at/bitfire/ical4android/Task.kt b/src/main/java/at/bitfire/ical4android/Task.kt index 6d88fac..664a7ee 100644 --- a/src/main/java/at/bitfire/ical4android/Task.kt +++ b/src/main/java/at/bitfire/ical4android/Task.kt @@ -10,9 +10,8 @@ package at.bitfire.ical4android import net.fortuna.ical4j.data.CalendarOutputter import net.fortuna.ical4j.data.ParserException +import net.fortuna.ical4j.model.* import net.fortuna.ical4j.model.Calendar -import net.fortuna.ical4j.model.Component -import net.fortuna.ical4j.model.DateTime import net.fortuna.ical4j.model.TimeZone import net.fortuna.ical4j.model.component.VToDo import net.fortuna.ical4j.model.property.* @@ -26,7 +25,7 @@ import java.util.logging.Level class Task: ICalendar() { - var createdAt: Long? = null + var createdAt: Long? = null var lastModified: Long? = null var summary: String? = null @@ -50,6 +49,8 @@ class Task: ICalendar() { val rDates = LinkedList() val exDates = LinkedList() + val unknownProperties = LinkedList() + companion object { /** @@ -108,6 +109,8 @@ class Task: ICalendar() { is RRule -> t.rRule = prop is RDate -> t.rDates += prop is ExDate -> t.exDates += prop + is ProdId, is DtStamp -> { /* don't save these as unknown properties */ } + else -> t.unknownProperties += prop } // there seem to be many invalid tasks out there because of some defect clients, @@ -125,19 +128,19 @@ class Task: ICalendar() { } - fun write(os: OutputStream) { - val ical = Calendar() - ical.properties += Version.VERSION_2_0 - ical.properties += prodId + fun write(os: OutputStream) { + val ical = Calendar() + ical.properties += Version.VERSION_2_0 + ical.properties += prodId - val todo = VToDo() - ical.components += todo - val props = todo.properties + val todo = VToDo() + ical.components += todo + val props = todo.properties uid?.let { props += Uid(it) } sequence?.let { if (it != 0) props += Sequence(sequence as Int) } - createdAt?.let { props += Created(DateTime(it)) } + createdAt?.let { props += Created(DateTime(it)) } lastModified?.let { props += LastModified(DateTime(it)) } summary?.let { props += Summary(it) } @@ -145,7 +148,7 @@ class Task: ICalendar() { geoPosition?.let { props += it } description?.let { props += Description(it) } color?.let { props += Color(EventColor.nearestMatch(it)) } - url?.let { + url?.let { try { props += Url(URI(it)) } catch (e: URISyntaxException) { @@ -155,7 +158,7 @@ class Task: ICalendar() { organizer?.let { props += it } if (priority != Priority.UNDEFINED.level) - props += Priority(priority) + props += Priority(priority) classification?.let { props += it } status?.let { props += it } @@ -163,12 +166,12 @@ class Task: ICalendar() { rDates.forEach { props += it } exDates.forEach { props += it } - // remember used time zones - val usedTimeZones = HashSet() - due?.let { + // remember used time zones + val usedTimeZones = HashSet() + due?.let { props += it it.timeZone?.let(usedTimeZones::add) - } + } duration?.let(props::add) dtStart?.let { props += it @@ -178,13 +181,15 @@ class Task: ICalendar() { props += it it.timeZone?.let(usedTimeZones::add) } - percentComplete?.let { props += PercentComplete(it) } + percentComplete?.let { props += PercentComplete(it) } - // add VTIMEZONE components + props.addAll(unknownProperties) + + // add VTIMEZONE components usedTimeZones.forEach { ical.components += it.vTimeZone } CalendarOutputter(false).output(ical, os) - } + } fun isAllDay(): Boolean { -- GitLab From 5b0cad59f2231b98185643e90edfa9af7ade53b4 Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Sat, 1 Dec 2018 22:26:16 +0100 Subject: [PATCH 04/58] Update OpenTasks contract --- .../org/dmfs/tasks/contract/TaskContract.java | 73 ++++++++++++++++--- .../org/dmfs/tasks/contract/UriFactory.java | 2 +- 2 files changed, 64 insertions(+), 11 deletions(-) diff --git a/opentasks-contract/src/main/java/org/dmfs/tasks/contract/TaskContract.java b/opentasks-contract/src/main/java/org/dmfs/tasks/contract/TaskContract.java index bcbaeec..d8363dd 100644 --- a/opentasks-contract/src/main/java/org/dmfs/tasks/contract/TaskContract.java +++ b/opentasks-contract/src/main/java/org/dmfs/tasks/contract/TaskContract.java @@ -512,7 +512,7 @@ public final class TaskContract String DESCRIPTION = "description"; /** - * An URL for this task. Must be a valid URL if not null- + * The URL iCalendar field for this task. Must be a valid URI if not null- *

* Value: String *

@@ -1036,27 +1036,80 @@ public final class TaskContract String INSTANCE_DURATION = "instance_duration"; /** - * The start of the original instance as specified in the master task. For non-recurring task instances this equals the value of {@link - * #INSTANCE_START}, except that `null` values are represented as `0`. + * The start of the original instance as specified in the master task. For non-recurring task instances this is {@code null}. *

* For recurring tasks, these are the timestamps which have been derived from the recurrence rule or dates, except those specified as exdates. */ String INSTANCE_ORIGINAL_TIME = "instance_original_time"; + /** + * The distance of the instance from the current one. For closed instances this is always {@code -1}, for the current instance this is {@code 0}. For + * the instance after the current one this is {@code 1}, for the instance after that one it's {@code 2}, etc.. + *

+ * Value: Integer + *

+ * read-only + */ + String DISTANCE_FROM_CURRENT = "distance_from_current"; } /** - * Instances of a task. At present this table is read only. Currently it contains exactly one entry per task (and task exception), so it's merely a copy of - * {@link Tasks}. + * A table containing one entry per task instance. This table is writable in order to allow modification of single instances of a task. Write operations to + * this table will be converted into operations on overrides and forwarded to the task table. + *

+ * Note: The {@link #DTSTART}, {@link #DUE} values of instances of recurring tasks represent the actual instance values, i.e. they are different for each + * instance ({@link #DURATION} is always {@code null}). + *

+ * Also, none of the instances are recurring themselves, so {@link #RRULE}, {@link #RDATE} and {@link #EXDATE} are always {@code null}. + *

+ * TODO: Insert all instances of recurring tasks. + *

+ * The following operations are supported: *

- * TODO: Insert all instances of recurring the tasks. - *

+ *

Insert

*

- * TODO: In later releases it's planned to provide a convenient interface to add, change or delete task instances via this URI. - *

+ * Note, the data of an insert must not contain the fields {@link #RRULE}, {@link #RDATE} or {@link #EXDATE}. If the new instance belongs to an existing + * task the data must contain the fields {@link #ORIGINAL_INSTANCE_ID} and {@link #ORIGINAL_INSTANCE_TIME}. Also note, this table supports writing {@link + * #DURATION} (if the instance has a {@link #DTSTART}), but reading it back will always return a {@code null} {@link #DURATION} and a non-{@code null} + * {@link #DUE} date. Reading the task in the tasks table will, however, return the original {@link #DURATION}. + *

+ * If there already is an instance (with or without override) for the given {@link #ORIGINAL_INSTANCE_ID} and {@link #ORIGINAL_INSTANCE_TIME} an exception + * is thrown. + *

+ *
ORIGINAL_INSTANCE_ID valueResult
absent or emptyA new non-recurring task is created with the given + * values.
a valid {@link Tasks} row {@code _ID}An {@link #RDATE} for the given {@link #ORIGINAL_INSTANCE_TIME} time is added to + * the given master task, any {@link #EXDATE} for this time is removed. The task is inserted as an override to the given master. No fields are inherited + * though. {@link #ORIGINAL_INSTANCE_ALLDAY} will be set to {@link #IS_ALLDAY} of the master. + *

+ * Note, if the given master is non-recurring, this operation will turn it into a recurring task.

invalid {@link Tasks} row {@code + * _ID}An exception is thrown.
+ *

+ *

Update

+ *

+ * Note, the data of an update must not contain any fields related to recurrence ({@link #RRULE}, {@link #RDATE}, {@link #EXDATE}, {@link + * #ORIGINAL_INSTANCE_ID}, {@link #ORIGINAL_INSTANCE_TIME} and {@link #ORIGINAL_INSTANCE_ALLDAY}). Also note, this table supports writing {@link #DURATION} + * (if the instance has a {@link #DTSTART}), but reading it back will always return a {@code null} {@link #DURATION} and a non-{@code null} {@link #DUE} + * date. Reading the task in the tasks table will, however, return the original {@link #DURATION}. + *

+ * + *
Target task typeResult
Recurring master taskA new override is created with the given data.

Note, + * any fields which are not provided are inherited from the master, except for {@link #DTSTART} and {@link #DUE} which will be inherited from the instance + * and {@link #DURATION}, {@link #RRULE}, {@link #RDATE} and {@link #EXDATE} which are set to {@code null}. {@link #ORIGINAL_INSTANCE_ID}, {@link + * #ORIGINAL_INSTANCE_TIME} and {@link #ORIGINAL_INSTANCE_ALLDAY} will be set accordingly.

Single instance taskThe task is + * updated with the given values.
Recurrence override with existing masterThe task is updated with the given values.
Recurrence override without existing masterThe task is updated with the given values.
+ *

+ *

Delete

+ *

+ * + * + *
Target task typeResult
Recurring master taskAn {@link #EXDATE} for this instance is added, any {@link + * #RDATE} for this instance is removed. The instance row is removed.

TODO: mark the task deleted if the remaining recurrence set is empty

Single instance taskThe {@link Tasks#_DELETED} flag of the task is set.
Recurrence override with existing + * masterThe {@link Tasks#_DELETED} flag of the override is set, an {@link #EXDATE} for this instance is added to the master, any {@link #RDATE} + * for this instance is removed from the master. TODO: mark the master deleted if the remaining recurrence set of the master is empty
Recurrence override without existing masterThe {@link Tasks#_DELETED} flag of the task is set.
* - * @author Yannic Ahrens + * @author Yannic Ahrens + * @author Marten Gajda */ public static final class Instances implements TaskColumns, InstanceColumns { diff --git a/opentasks-contract/src/main/java/org/dmfs/tasks/contract/UriFactory.java b/opentasks-contract/src/main/java/org/dmfs/tasks/contract/UriFactory.java index 8efbd7f..0092aca 100644 --- a/opentasks-contract/src/main/java/org/dmfs/tasks/contract/UriFactory.java +++ b/opentasks-contract/src/main/java/org/dmfs/tasks/contract/UriFactory.java @@ -34,7 +34,7 @@ public final class UriFactory UriFactory(String authority) { mAuthority = authority; - mUriMap.put((String) null, Uri.parse("content://" + authority)); + mUriMap.put(null, Uri.parse("content://" + authority)); } -- GitLab From e04df070148adaf4ddc454a97350ffe46280ee2b Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Fri, 21 Dec 2018 17:00:14 +0100 Subject: [PATCH 05/58] Update libraries --- build.gradle | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/build.gradle b/build.gradle index 656f2ef..bc14633 100644 --- a/build.gradle +++ b/build.gradle @@ -1,6 +1,6 @@ buildscript { - ext.kotlin_version = '1.3.10' + ext.kotlin_version = '1.3.11' ext.dokka_version = '0.9.17' repositories { @@ -25,7 +25,7 @@ apply plugin: 'kotlin-android' apply plugin: 'org.jetbrains.dokka-android' ext { - ical4j_version = '2.2.0' + ical4j_version = '2.2.1' } android { @@ -60,8 +60,8 @@ dependencies { api "org.mnode.ical4j:ical4j:$ical4j_version" implementation 'org.slf4j:slf4j-jdk14:1.7.25' - androidTestImplementation 'androidx.test:runner:1.1.0' - androidTestImplementation 'androidx.test:rules:1.1.0' + androidTestImplementation 'androidx.test:runner:1.1.1' + androidTestImplementation 'androidx.test:rules:1.1.1' testImplementation 'junit:junit:4.12' } -- GitLab From fef93f94bbc1265e53e55c95fe86e8c33e2e4f0f Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Fri, 4 Jan 2019 09:35:49 +0100 Subject: [PATCH 06/58] Update ical4j to 2.2.3 --- .gitlab-ci.yml | 2 +- build.gradle | 2 +- .../bitfire/ical4android/AndroidEventTest.kt | 22 +++--- .../bitfire/ical4android/AndroidCalendar.kt | 6 +- .../at/bitfire/ical4android/AndroidEvent.kt | 17 +++-- .../{EventColor.kt => Css3Color.kt} | 30 ++++++-- .../java/at/bitfire/ical4android/Event.kt | 6 +- .../java/at/bitfire/ical4android/ICalendar.kt | 73 +------------------ src/main/java/at/bitfire/ical4android/Task.kt | 4 +- .../{EventColorTest.kt => Css3ColorTest.kt} | 6 +- .../java/at/bitfire/ical4android/EventTest.kt | 3 +- src/test/resources/events/utf8.ics | 1 + 12 files changed, 62 insertions(+), 110 deletions(-) rename src/main/java/at/bitfire/ical4android/{EventColor.kt => Css3Color.kt} (87%) rename src/test/java/at/bitfire/ical4android/{EventColorTest.kt => Css3ColorTest.kt} (78%) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index b8a390c..936610a 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -1,4 +1,4 @@ -image: registry.gitlab.com/bitfireat/davdroid:latest +image: registry.gitlab.com/bitfireat/davx5-ose:latest before_script: - export GRADLE_USER_HOME=`pwd`/.gradle; chmod +x gradlew diff --git a/build.gradle b/build.gradle index bc14633..e079ab0 100644 --- a/build.gradle +++ b/build.gradle @@ -25,7 +25,7 @@ apply plugin: 'kotlin-android' apply plugin: 'org.jetbrains.dokka-android' ext { - ical4j_version = '2.2.1' + ical4j_version = '2.2.3' } android { diff --git a/src/androidTest/java/at/bitfire/ical4android/AndroidEventTest.kt b/src/androidTest/java/at/bitfire/ical4android/AndroidEventTest.kt index 7321e69..80bf296 100644 --- a/src/androidTest/java/at/bitfire/ical4android/AndroidEventTest.kt +++ b/src/androidTest/java/at/bitfire/ical4android/AndroidEventTest.kt @@ -80,17 +80,17 @@ class AndroidEventTest { fun testAddEvent() { // build and write recurring event to calendar provider val event = Event() - event.uid = ("sample1@testAddEvent") - event.summary = ("Sample event") - event.description = ("Sample event with date/time") - event.location = ("Sample location") - event.dtStart = (DtStart("20150501T120000", tzVienna)) - event.dtEnd = (DtEnd("20150501T130000", tzVienna)) - event.organizer = (Organizer(URI("mailto:organizer@example.com"))) - event.rRule = (RRule("FREQ=DAILY;COUNT=10")) - event.classification = (Clazz.PRIVATE) - event.status = (Status.VEVENT_CONFIRMED) - event.color = (EventColor.aliceblue) + event.uid = "sample1@testAddEvent" + event.summary = "Sample event" + event.description = "Sample event with date/time" + event.location = "Sample location" + event.dtStart = DtStart("20150501T120000", tzVienna) + event.dtEnd = DtEnd("20150501T130000", tzVienna) + event.organizer = Organizer(URI("mailto:organizer@example.com")) + event.rRule = RRule("FREQ=DAILY;COUNT=10") + event.classification = Clazz.PRIVATE + event.status = Status.VEVENT_CONFIRMED + event.color = Css3Color.aliceblue assertFalse(event.isAllDay()) // TODO test rDates, exDate, duration diff --git a/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt b/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt index 165d1db..71594e9 100644 --- a/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt +++ b/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt @@ -50,7 +50,7 @@ abstract class AndroidCalendar( fun insertColors(provider: ContentProviderClient, account: Account) { provider.query(syncAdapterURI(Colors.CONTENT_URI, account), arrayOf(Colors.COLOR_KEY), null, null, null)?.use { cursor -> - if (cursor.count == EventColor.values().size) + if (cursor.count == Css3Color.values().size) // colors already inserted and up to date return } @@ -60,9 +60,9 @@ abstract class AndroidCalendar( values.put(CalendarContract.Colors.ACCOUNT_NAME, account.name) values.put(CalendarContract.Colors.ACCOUNT_TYPE, account.type) values.put(Colors.COLOR_TYPE, Colors.TYPE_EVENT) - for (color in EventColor.values()) { + for (color in Css3Color.values()) { values.put(Colors.COLOR_KEY, color.name) - values.put(Colors.COLOR, color.rgba) + values.put(Colors.COLOR, color.argb) provider.insert(syncAdapterURI(Colors.CONTENT_URI, account), values) } } diff --git a/src/main/java/at/bitfire/ical4android/AndroidEvent.kt b/src/main/java/at/bitfire/ical4android/AndroidEvent.kt index 878a270..23df741 100644 --- a/src/main/java/at/bitfire/ical4android/AndroidEvent.kt +++ b/src/main/java/at/bitfire/ical4android/AndroidEvent.kt @@ -53,6 +53,9 @@ abstract class AndroidEvent( const val EXT_UNKNOWN_PROPERTY = "unknown-property" const val MAX_UNKNOWN_PROPERTY_SIZE = 25000 + // not declared in ical4j Parameters class yet + private const val PARAMETER_EMAIL = "EMAIL" + } var id: Long? = null @@ -144,7 +147,7 @@ abstract class AndroidEvent( row.getAsString(Events.EVENT_COLOR_KEY)?.let { name -> try { - event.color = EventColor.valueOf(name) + event.color = Css3Color.valueOf(name) } catch(e: IllegalArgumentException) { Constants.log.warning("Ignoring unknown color $name from Calendar Provider") } @@ -258,7 +261,7 @@ abstract class AndroidEvent( if (idNS != null || id != null) { // attendee identified by namespace and ID attendee = Attendee(URI(idNS, id, null)) - email?.let { attendee.parameters.add(ICalendar.Email(it)) } + email?.let { attendee.parameters.add(Email(it)) } } else // attendee identified by email address attendee = Attendee(URI("mailto", email, null)) @@ -581,7 +584,7 @@ abstract class AndroidEvent( email = if (uri.scheme.equals("mailto", true)) uri.schemeSpecificPart else { - val emailParam = organizer.getParameter(ICalendar.Email.PARAMETER_NAME) as ICalendar.Email? + val emailParam = organizer.getParameter(PARAMETER_EMAIL) as? Email emailParam?.value } if (email != null) @@ -639,7 +642,7 @@ abstract class AndroidEvent( // attendee identified by other URI builder .withValue(Attendees.ATTENDEE_ID_NAMESPACE, member.scheme) .withValue(Attendees.ATTENDEE_IDENTITY, member.schemeSpecificPart) - (attendee.getParameter(ICalendar.Email.PARAMETER_NAME) as ICalendar.Email?)?.let { email -> + (attendee.getParameter(PARAMETER_EMAIL) as? Email)?.let { email -> builder.withValue(Attendees.ATTENDEE_EMAIL, email.value) } } @@ -649,13 +652,13 @@ abstract class AndroidEvent( } var type = Attendees.TYPE_NONE - val cutype = attendee.getParameter(Parameter.CUTYPE) as CuType? + val cutype = attendee.getParameter(Parameter.CUTYPE) as? CuType if (cutype in arrayOf(CuType.RESOURCE, CuType.ROOM)) // "attendee" is a (physical) resource type = Attendees.TYPE_RESOURCE else { // attendee is not a (physical) resource - val role = attendee.getParameter(Parameter.ROLE) as Role? + val role = attendee.getParameter(Parameter.ROLE) as? Role val relationship: Int if (role == Role.CHAIR) relationship = Attendees.RELATIONSHIP_ORGANIZER @@ -669,7 +672,7 @@ abstract class AndroidEvent( builder.withValue(Attendees.ATTENDEE_RELATIONSHIP, relationship) } - val partStat = attendee.getParameter(Parameter.PARTSTAT) as PartStat? + val partStat = attendee.getParameter(Parameter.PARTSTAT) as? PartStat val status = when(partStat) { null, PartStat.NEEDS_ACTION -> Attendees.ATTENDEE_STATUS_INVITED diff --git a/src/main/java/at/bitfire/ical4android/EventColor.kt b/src/main/java/at/bitfire/ical4android/Css3Color.kt similarity index 87% rename from src/main/java/at/bitfire/ical4android/EventColor.kt rename to src/main/java/at/bitfire/ical4android/Css3Color.kt index 0705970..8433227 100644 --- a/src/main/java/at/bitfire/ical4android/EventColor.kt +++ b/src/main/java/at/bitfire/ical4android/Css3Color.kt @@ -10,9 +10,11 @@ package at.bitfire.ical4android /** * Represents an RGBA COLOR value, as specified in https://tools.ietf.org/html/rfc7986#section-5.9 + * + * @property argb ARGB color value (0xAARRGGBB), alpha is 0xFF for all values */ @Suppress("EnumEntryName") -enum class EventColor(val rgba: Int) { +enum class Css3Color(val argb: Int) { // values taken from https://www.w3.org/TR/2011/REC-css3-color-20110607/#svg-color aliceblue(0xfff0f8ff.toInt()), antiquewhite(0xfffaebd7.toInt()), @@ -166,13 +168,29 @@ enum class EventColor(val rgba: Int) { companion object { /** - * Finds the best matching [EventColor] for a given RGBA value using a weighted Euclidian - * distance formula for RGB (A is being ignored). + * Returns the CSS3 color property of the given name. + * + * @param name color name + * @return [Css3Color] object or null if no match was found */ - fun nearestMatch(rgba: Int): EventColor { - val rgb = rgba and 0xFFFFFF + fun fromString(name: String) = + try { + Css3Color.valueOf(name) + } catch (e: IllegalArgumentException) { + Constants.log.warning("Unknown color: $name") + null + } + + /** + * Finds the best matching [Css3Color] for a given RGBA value using a weighted Euclidian + * distance formula for RGB. + * + * @param argb (A)RGB color (A will be ignored) + */ + fun nearestMatch(argb: Int): Css3Color { + val rgb = argb and 0xFFFFFF val distance = values().map { - val cssColor = it.rgba and 0xFFFFFF + val cssColor = it.argb and 0xFFFFFF val r1 = rgb shr 16 val r2 = cssColor shr 16 val r = (r1 + r2)/2.0 diff --git a/src/main/java/at/bitfire/ical4android/Event.kt b/src/main/java/at/bitfire/ical4android/Event.kt index ab2b2c1..1791414 100644 --- a/src/main/java/at/bitfire/ical4android/Event.kt +++ b/src/main/java/at/bitfire/ical4android/Event.kt @@ -30,7 +30,7 @@ class Event: ICalendar() { var summary: String? = null var location: String? = null var description: String? = null - var color: EventColor? = null + var color: Css3Color? = null var dtStart: DtStart? = null var dtEnd: DtEnd? = null @@ -162,7 +162,7 @@ class Event: ICalendar() { is Summary -> e.summary = prop.value is Location -> e.location = prop.value is Description -> e.description = prop.value - is Color -> e.color = prop.value + is Color -> e.color = Css3Color.fromString(prop.value) is DtStart -> e.dtStart = prop is DtEnd -> e.dtEnd = prop is Duration -> e.duration = prop @@ -242,7 +242,7 @@ class Event: ICalendar() { summary?.let { props += Summary(it) } location?.let { props += Location(it) } description?.let { props += Description(it) } - color?.let { props += Color(it) } + color?.let { props += Color(null, it.name) } props += dtStart dtEnd?.let { props += it } diff --git a/src/main/java/at/bitfire/ical4android/ICalendar.kt b/src/main/java/at/bitfire/ical4android/ICalendar.kt index 0b174a8..6942b08 100644 --- a/src/main/java/at/bitfire/ical4android/ICalendar.kt +++ b/src/main/java/at/bitfire/ical4android/ICalendar.kt @@ -17,7 +17,6 @@ import net.fortuna.ical4j.model.component.* import net.fortuna.ical4j.model.property.DateProperty import net.fortuna.ical4j.model.property.ProdId import net.fortuna.ical4j.model.property.TzUrl -import net.fortuna.ical4j.util.Strings import java.io.StringReader import java.util.* import java.util.logging.Level @@ -39,16 +38,8 @@ open class ICalendar { } var prodId = ProdId("+//IDN bitfire.at//ical4android") - - private val parameterFactoryRegistry = ParameterFactoryRegistry() - init { - parameterFactoryRegistry.register(Email.PARAMETER_NAME, Email.Factory) - } - private val propertyFactoryRegistry = PropertyFactoryRegistry() - init { - propertyFactoryRegistry.register(Color.PROPERTY_NAME, Color.Factory) - } + private val parameterFactoryRegistry = ParameterFactoryRegistry() @JvmStatic protected fun calendarBuilder() = CalendarBuilder( @@ -155,66 +146,4 @@ open class ICalendar { override fun toString() = MiscUtils.reflectionToString(this) - - // ical4j helpers and extensions - - /** COLOR property for VEVENT components [RFC 7986 5.9 COLOR] */ - class Color( - var value: EventColor? = null - ): Property(PROPERTY_NAME, Factory) { - companion object { - const val PROPERTY_NAME = "COLOR" - } - - override fun getValue() = value?.name - - override fun setValue(name: String?) { - name?.let { - try { - value = EventColor.valueOf(name.toLowerCase()) - } catch(e: IllegalArgumentException) { - Constants.log.warning("Ignoring unknown COLOR $name") - } - } - } - - override fun validate() { - } - - object Factory: PropertyFactory { - override fun createProperty() = Color() - - override fun createProperty(params: ParameterList?, value: String?): Color { - val c = Color() - c.setValue(value) - return c - } - - override fun supports(property: String?) = property == PROPERTY_NAME - } - - } - - /** EMAIL parameter for ATTENDEE properties, as used by iCloud: - ATTENDEE;EMAIL=bla@domain.tld;/path/to/principal - */ - class Email(): Parameter(PARAMETER_NAME, Factory) { - companion object { - const val PARAMETER_NAME = "EMAIL" - } - - var email: String? = null - override fun getValue() = email - - constructor(aValue: String): this() - { - email = Strings.unquote(aValue) - } - - object Factory: ParameterFactory { - override fun createParameter(value: String) = Email(value) - override fun supports(name: String) = name == PARAMETER_NAME - } - } - } \ No newline at end of file diff --git a/src/main/java/at/bitfire/ical4android/Task.kt b/src/main/java/at/bitfire/ical4android/Task.kt index 664a7ee..3ac1a80 100644 --- a/src/main/java/at/bitfire/ical4android/Task.kt +++ b/src/main/java/at/bitfire/ical4android/Task.kt @@ -95,7 +95,7 @@ class Task: ICalendar() { is Location -> t.location = prop.value is Geo -> t.geoPosition = prop is Description -> t.description = prop.value - is Color -> t.color = prop.value?.rgba + is Color -> t.color = Css3Color.fromString(prop.value)?.argb is Url -> t.url = prop.value is Organizer -> t.organizer = prop is Priority -> t.priority = prop.level @@ -147,7 +147,7 @@ class Task: ICalendar() { location?.let { props += Location(it) } geoPosition?.let { props += it } description?.let { props += Description(it) } - color?.let { props += Color(EventColor.nearestMatch(it)) } + color?.let { props += Color(null, Css3Color.nearestMatch(it).name) } url?.let { try { props += Url(URI(it)) diff --git a/src/test/java/at/bitfire/ical4android/EventColorTest.kt b/src/test/java/at/bitfire/ical4android/Css3ColorTest.kt similarity index 78% rename from src/test/java/at/bitfire/ical4android/EventColorTest.kt rename to src/test/java/at/bitfire/ical4android/Css3ColorTest.kt index 6ad1c3c..a4bd6c0 100644 --- a/src/test/java/at/bitfire/ical4android/EventColorTest.kt +++ b/src/test/java/at/bitfire/ical4android/Css3ColorTest.kt @@ -11,13 +11,13 @@ package at.bitfire.ical4android import org.junit.Assert.assertEquals import org.junit.Test -class EventColorTest { +class Css3ColorTest { @Test fun testNearestMatch() { // every color is its own nearest match - EventColor.values().forEach { - assertEquals(it.rgba, EventColor.nearestMatch(it.rgba).rgba) + Css3Color.values().forEach { + assertEquals(it.argb, Css3Color.nearestMatch(it.argb).argb) } } diff --git a/src/test/java/at/bitfire/ical4android/EventTest.kt b/src/test/java/at/bitfire/ical4android/EventTest.kt index c3e7959..5e4f834 100644 --- a/src/test/java/at/bitfire/ical4android/EventTest.kt +++ b/src/test/java/at/bitfire/ical4android/EventTest.kt @@ -81,7 +81,8 @@ class EventTest { assertEquals("© äö — üß", event.summary) assertEquals("Test Description", event.description) assertEquals("中华人民共和国", event.location) - assertEquals(EventColor.aliceblue, event.color) + assertEquals(Css3Color.aliceblue, event.color) + assertEquals("cyrus@example.com", event.attendees.first.parameters.getParameter("EMAIL").value) } @Test diff --git a/src/test/resources/events/utf8.ics b/src/test/resources/events/utf8.ics index 43fbdba..11644b6 100644 --- a/src/test/resources/events/utf8.ics +++ b/src/test/resources/events/utf8.ics @@ -7,6 +7,7 @@ SUMMARY:© äö — üß DESCRIPTION:Test Description LOCATION:中华人民共和国 COLOR:aliceblue +ATTENDEE;CN=Cyrus Daboo;EMAIL=cyrus@example.com:mailto:opaque-token-1234@example.com DTSTART:20131009T170000T DTEND:20131009T180000T END:VEVENT -- GitLab From 7c49ba213d823fcb3b06c567227d53e723864043 Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Sun, 6 Jan 2019 18:13:25 +0100 Subject: [PATCH 07/58] Update gradle --- gradle/wrapper/gradle-wrapper.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 5801d8e..a547d65 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-4.8-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-5.1-all.zip -- GitLab From d36b93cc80a93d62c126091aebaad702b049f3d2 Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Fri, 11 Jan 2019 16:26:20 +0100 Subject: [PATCH 08/58] Some documentation --- .../java/at/bitfire/ical4android/AndroidCalendar.kt | 11 +++++++++++ src/main/java/at/bitfire/ical4android/Css3Color.kt | 2 +- src/main/java/at/bitfire/ical4android/MiscUtils.kt | 6 ++++++ src/test/java/at/bitfire/ical4android/EventTest.kt | 2 +- src/test/java/at/bitfire/ical4android/TaskTest.kt | 2 +- 5 files changed, 20 insertions(+), 3 deletions(-) diff --git a/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt b/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt index 71594e9..106df95 100644 --- a/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt +++ b/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt @@ -35,6 +35,17 @@ abstract class AndroidCalendar( companion object { + /** + * Creates a local (Android calendar provider) calendar. + * + * @param account account which the calendar should be assigned to + * @param provider client for Android calendar provider + * @param info initial calendar properties ([Calendars.CALENDAR_DISPLAY_NAME] etc.) + * + * @return [Uri] of the created calendar + * + * @throws Exception if the calendar couldn't be created + */ fun create(account: Account, provider: ContentProviderClient, info: ContentValues): Uri { info.put(Calendars.ACCOUNT_NAME, account.name) info.put(Calendars.ACCOUNT_TYPE, account.type) diff --git a/src/main/java/at/bitfire/ical4android/Css3Color.kt b/src/main/java/at/bitfire/ical4android/Css3Color.kt index 8433227..5fb2672 100644 --- a/src/main/java/at/bitfire/ical4android/Css3Color.kt +++ b/src/main/java/at/bitfire/ical4android/Css3Color.kt @@ -13,7 +13,7 @@ package at.bitfire.ical4android * * @property argb ARGB color value (0xAARRGGBB), alpha is 0xFF for all values */ -@Suppress("EnumEntryName") +@Suppress("EnumEntryName", "SpellCheckingInspection") enum class Css3Color(val argb: Int) { // values taken from https://www.w3.org/TR/2011/REC-css3-color-20110607/#svg-color aliceblue(0xfff0f8ff.toInt()), diff --git a/src/main/java/at/bitfire/ical4android/MiscUtils.kt b/src/main/java/at/bitfire/ical4android/MiscUtils.kt index 07212f8..29a2849 100644 --- a/src/main/java/at/bitfire/ical4android/MiscUtils.kt +++ b/src/main/java/at/bitfire/ical4android/MiscUtils.kt @@ -18,6 +18,7 @@ object MiscUtils { /** * Ensures that a given DateProperty has a time zone with an ID that is available in Android. + * * @param date DateProperty to validate. Values which are not DATE-TIME will be ignored. */ fun androidifyTimeZone(date: DateProperty?) { @@ -35,6 +36,7 @@ object MiscUtils { /** * Returns the time-zone ID for a given date-time, or TIMEZONE_UTC for dates (without time). * TIMEZONE_UTC is also returned for DATE-TIMEs in UTC representation. + * * @param date DateProperty (DATE or DATE-TIME) whose time-zone information is used */ fun getTzId(date: DateProperty?) = @@ -45,6 +47,9 @@ object MiscUtils { /** * Generates useful toString info (fields and values) from [obj] by reflection. + * + * @param obj object to inspect + * @return string containing properties and non-static declared fields */ fun reflectionToString(obj: Any): String { val s = LinkedList() @@ -61,6 +66,7 @@ object MiscUtils { /** * Removes empty [String] values from [values]. + * * @param values set of values to be processed */ fun removeEmptyStrings(values: ContentValues) { diff --git a/src/test/java/at/bitfire/ical4android/EventTest.kt b/src/test/java/at/bitfire/ical4android/EventTest.kt index 5e4f834..be683bd 100644 --- a/src/test/java/at/bitfire/ical4android/EventTest.kt +++ b/src/test/java/at/bitfire/ical4android/EventTest.kt @@ -29,7 +29,7 @@ class EventTest { @Test fun testCharsets() { - var e = parseCalendar("latin1.ics", Charset.forName("ISO-8859-1"))[0] + var e = parseCalendar("latin1.ics", Charsets.ISO_8859_1)[0] assertEquals("äöüß", e.summary) e = parseCalendar("utf8.ics").first() diff --git a/src/test/java/at/bitfire/ical4android/TaskTest.kt b/src/test/java/at/bitfire/ical4android/TaskTest.kt index b72b9bc..01475d7 100644 --- a/src/test/java/at/bitfire/ical4android/TaskTest.kt +++ b/src/test/java/at/bitfire/ical4android/TaskTest.kt @@ -27,7 +27,7 @@ class TaskTest { @Test fun testCharsets() { - var t = parseCalendar("latin1.ics", Charset.forName("ISO-8859-1")) + var t = parseCalendar("latin1.ics", Charsets.ISO_8859_1) assertEquals("äöüß", t.summary) t = parseCalendar("utf8.ics") -- GitLab From 17b0e04774fa218fd94a60e6a342a22cde6d7f5c Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Sun, 27 Jan 2019 23:16:06 +0100 Subject: [PATCH 09/58] Wrap IllegalArgumentExceptions in InvalidCalendarException; update Kotlin/gradle --- build.gradle | 4 ++-- src/main/java/at/bitfire/ical4android/Event.kt | 4 +++- src/main/java/at/bitfire/ical4android/Task.kt | 6 ++++-- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/build.gradle b/build.gradle index e079ab0..5b1a847 100644 --- a/build.gradle +++ b/build.gradle @@ -1,6 +1,6 @@ buildscript { - ext.kotlin_version = '1.3.11' + ext.kotlin_version = '1.3.20' ext.dokka_version = '0.9.17' repositories { @@ -9,7 +9,7 @@ buildscript { } dependencies { - classpath 'com.android.tools.build:gradle:3.2.1' + classpath 'com.android.tools.build:gradle:3.3.0' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath "org.jetbrains.dokka:dokka-android-gradle-plugin:${dokka_version}" } diff --git a/src/main/java/at/bitfire/ical4android/Event.kt b/src/main/java/at/bitfire/ical4android/Event.kt index 1791414..89c0c08 100644 --- a/src/main/java/at/bitfire/ical4android/Event.kt +++ b/src/main/java/at/bitfire/ical4android/Event.kt @@ -77,7 +77,9 @@ class Event: ICalendar() { try { ical = calendarBuilder().build(reader) } catch(e: ParserException) { - throw InvalidCalendarException("Couldn't parse iCalendar resource", e) + throw InvalidCalendarException("Couldn't parse iCalendar object", e) + } catch(e: IllegalArgumentException) { + throw InvalidCalendarException("iCalendar object contains invalid value", e) } // fill calendar properties diff --git a/src/main/java/at/bitfire/ical4android/Task.kt b/src/main/java/at/bitfire/ical4android/Task.kt index 3ac1a80..37239d1 100644 --- a/src/main/java/at/bitfire/ical4android/Task.kt +++ b/src/main/java/at/bitfire/ical4android/Task.kt @@ -65,8 +65,10 @@ class Task: ICalendar() { val ical: Calendar try { ical = calendarBuilder().build(reader) - } catch (e: ParserException) { - throw InvalidCalendarException("Couldn't parse iCalendar resource", e) + } catch(e: ParserException) { + throw InvalidCalendarException("Couldn't parse iCalendar object", e) + } catch(e: IllegalArgumentException) { + throw InvalidCalendarException("iCalendar object contains invalid value", e) } val vToDos = ical.getComponents(Component.VTODO) -- GitLab From d1bb15568c1894d1d9f9eb28c323e7595e60e6ed Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Tue, 29 Jan 2019 23:17:58 +0100 Subject: [PATCH 10/58] Use PackageInfoCompat to support long version codes --- build.gradle | 1 + src/main/java/at/bitfire/ical4android/TaskProvider.kt | 10 ++++++---- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/build.gradle b/build.gradle index 5b1a847..5dfdc1d 100644 --- a/build.gradle +++ b/build.gradle @@ -59,6 +59,7 @@ dependencies { api "org.mnode.ical4j:ical4j:$ical4j_version" implementation 'org.slf4j:slf4j-jdk14:1.7.25' + implementation 'androidx.core:core-ktx:1.0.1' androidTestImplementation 'androidx.test:runner:1.1.1' androidTestImplementation 'androidx.test:rules:1.1.1' diff --git a/src/main/java/at/bitfire/ical4android/TaskProvider.kt b/src/main/java/at/bitfire/ical4android/TaskProvider.kt index 3bf92b5..57ded7c 100644 --- a/src/main/java/at/bitfire/ical4android/TaskProvider.kt +++ b/src/main/java/at/bitfire/ical4android/TaskProvider.kt @@ -15,6 +15,7 @@ import android.content.Context import android.content.pm.PackageManager import android.net.Uri import android.os.Build +import androidx.core.content.pm.PackageInfoCompat import org.dmfs.tasks.contract.TaskContract import java.io.Closeable import java.util.logging.Level @@ -27,7 +28,7 @@ class TaskProvider private constructor( enum class ProviderName( val authority: String, val packageName: String, - val minVersionCode: Int, + val minVersionCode: Long, val minVersionName: String ) { //Mirakel("de.azapps.mirakel.provider"), @@ -80,8 +81,9 @@ class TaskProvider private constructor( private fun checkVersion(context: Context, name: ProviderName) { // check whether package is available with required minimum version val info = context.packageManager.getPackageInfo(name.packageName, 0) - if (info.versionCode < name.minVersionCode) { - val exception = ProviderTooOldException(name, info.versionCode, info.versionName) + val installedVersionCode = PackageInfoCompat.getLongVersionCode(info) + if (installedVersionCode < name.minVersionCode) { + val exception = ProviderTooOldException(name, installedVersionCode, info.versionName) Constants.log.log(Level.WARNING, "Task provider too old", exception) throw exception } @@ -113,7 +115,7 @@ class TaskProvider private constructor( class ProviderTooOldException( val provider: ProviderName, - installedVersionCode: Int, + installedVersionCode: Long, val installedVersionName: String ): Exception("Package ${provider.packageName} has version $installedVersionName ($installedVersionCode), " + "required: ${provider.minVersionName} (${provider.minVersionCode})") -- GitLab From c9948ade974cab4ca40ce4a18de002402602d9c3 Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Wed, 30 Jan 2019 17:43:11 +0100 Subject: [PATCH 11/58] Exceptions of recurring events: use main event's DTSTART time zone for RECURRENCE-ID --- .../java/at/bitfire/ical4android/Event.kt | 54 ++++++++++++------- 1 file changed, 36 insertions(+), 18 deletions(-) diff --git a/src/main/java/at/bitfire/ical4android/Event.kt b/src/main/java/at/bitfire/ical4android/Event.kt index 89c0c08..8d92a77 100644 --- a/src/main/java/at/bitfire/ical4android/Event.kt +++ b/src/main/java/at/bitfire/ical4android/Event.kt @@ -100,8 +100,8 @@ class Event: ICalendar() { vEvent.properties += uid } - Constants.log.fine("Assigning exceptions to master events") - val masterEvents = mutableMapOf() + Constants.log.fine("Assigning exceptions to main events") + val mainEvents = mutableMapOf() val exceptions = mutableMapOf>() for (vEvent in vEvents) { @@ -109,13 +109,13 @@ class Event: ICalendar() { val sequence = vEvent.sequence?.sequenceNo ?: 0 if (vEvent.recurrenceId == null) { - // master event (no RECURRENCE-ID) + // main event (no RECURRENCE-ID) // If there are multiple entries, compare SEQUENCE and use the one with higher SEQUENCE. // If the SEQUENCE is identical, use latest version. - val event = masterEvents[uid] + val event = mainEvents[uid] if (event == null || (event.sequence != null && sequence >= event.sequence.sequenceNo)) - masterEvents[uid] = vEvent + mainEvents[uid] = vEvent } else { // exception (RECURRENCE-ID) @@ -134,7 +134,7 @@ class Event: ICalendar() { } val events = mutableListOf() - for ((uid, vEvent) in masterEvents) { + for ((uid, vEvent) in mainEvents) { val event = fromVEvent(vEvent) exceptions[uid]?.let { eventExceptions -> event.exceptions.addAll(eventExceptions.map { (_,it) -> fromVEvent(it) }) @@ -202,25 +202,38 @@ class Event: ICalendar() { ical.properties += Version.VERSION_2_0 ical.properties += prodId - // "master event" (without exceptions) + val dtStart = dtStart ?: throw InvalidCalendarException("Won't generate event without start time") + + // "main event" (without exceptions) val components = ical.components - val master = toVEvent(Uid(uid)) - components += master + val mainEvent = toVEvent() + components += mainEvent // remember used time zones val usedTimeZones = mutableSetOf() - dtStart?.timeZone?.let(usedTimeZones::add) + dtStart.timeZone?.let(usedTimeZones::add) dtEnd?.timeZone?.let(usedTimeZones::add) // recurrence exceptions for (exception in exceptions) { - // create VEVENT for exception - val vException = exception.toVEvent(master.uid) - components += vException + // make sure that + // - exceptions have the same UID as the main event and + // - RECURRENCE-IDs have the same timezone as the main event's DTSTART + exception.uid = uid + exception.recurrenceId?.let { recurrenceId -> + if (recurrenceId.timeZone != dtStart.timeZone) { + recurrenceId.timeZone = dtStart.timeZone + exception.recurrenceId = recurrenceId + } - // remember used time zones - exception.dtStart?.timeZone?.let(usedTimeZones::add) - exception.dtEnd?.timeZone?.let(usedTimeZones::add) + // create VEVENT for exception + val vException = exception.toVEvent() + components += vException + + // remember used time zones + exception.dtStart?.timeZone?.let(usedTimeZones::add) + exception.dtEnd?.timeZone?.let(usedTimeZones::add) + } } // add VTIMEZONE components @@ -233,11 +246,16 @@ class Event: ICalendar() { CalendarOutputter(false).output(ical, os) } - private fun toVEvent(uid: Uid): VEvent { + /** + * Generates a VEvent representation of this event. + * + * @return generated VEvent + */ + private fun toVEvent(): VEvent { val event = VEvent() val props = event.properties - props += uid + props += Uid(uid) recurrenceId?.let { props += it } sequence?.let { if (it != 0) props += Sequence(it) } -- GitLab From ff2a29599a50454507d9a9d524797cff9a23e1e8 Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Wed, 6 Feb 2019 01:19:55 +0100 Subject: [PATCH 12/58] Use default time-zone to store floating DATE-TIMEs --- .../java/at/bitfire/ical4android/MiscUtils.kt | 27 ++++++++++++++----- 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/src/main/java/at/bitfire/ical4android/MiscUtils.kt b/src/main/java/at/bitfire/ical4android/MiscUtils.kt index 29a2849..ae14494 100644 --- a/src/main/java/at/bitfire/ical4android/MiscUtils.kt +++ b/src/main/java/at/bitfire/ical4android/MiscUtils.kt @@ -34,15 +34,30 @@ object MiscUtils { } /** - * Returns the time-zone ID for a given date-time, or TIMEZONE_UTC for dates (without time). - * TIMEZONE_UTC is also returned for DATE-TIMEs in UTC representation. + * Returns the time-zone ID for a given date or date-time that should be used to store it + * in the Android calendar storage. * * @param date DateProperty (DATE or DATE-TIME) whose time-zone information is used + * + * @return - UTC for dates and UTC date-times + * - the specified time zone ID for date-times with given time zone + * - the currently set default time zone ID for floating date-times */ - fun getTzId(date: DateProperty?) = - if (ICalendar.isDateTime(date!!) && !date.isUtc && date.timeZone != null) - date.timeZone.id!! - else + fun getTzId(date: DateProperty): String = + if (ICalendar.isDateTime(date)) { + when { + date.isUtc -> + // DATE-TIME in UTC format + TimeZones.UTC_ID + date.timeZone != null -> + // DATE-TIME with given time-zone + date.timeZone.id + else /* date.timeZone == null */ -> + // DATE-TIME in local format (floating) + TimeZone.getDefault().id + } + } else + // DATE TimeZones.UTC_ID /** -- GitLab From 01a09e8fd8a46947f6ebde34f9522c75a07e23b1 Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Mon, 18 Feb 2019 13:27:46 +0100 Subject: [PATCH 13/58] Serialize unknown parameters as JSON instead of a big Base64 blob which isn't human-readable --- .../ical4android/UnknownPropertyTest.kt | 60 +++++++++ .../at/bitfire/ical4android/AndroidEvent.kt | 114 +++++++++++++----- .../java/at/bitfire/ical4android/ICalendar.kt | 4 +- 3 files changed, 149 insertions(+), 29 deletions(-) create mode 100644 src/androidTest/java/at/bitfire/ical4android/UnknownPropertyTest.kt diff --git a/src/androidTest/java/at/bitfire/ical4android/UnknownPropertyTest.kt b/src/androidTest/java/at/bitfire/ical4android/UnknownPropertyTest.kt new file mode 100644 index 0000000..04772a8 --- /dev/null +++ b/src/androidTest/java/at/bitfire/ical4android/UnknownPropertyTest.kt @@ -0,0 +1,60 @@ +package at.bitfire.ical4android + +import androidx.test.filters.SmallTest +import net.fortuna.ical4j.model.parameter.Rsvp +import net.fortuna.ical4j.model.parameter.XParameter +import net.fortuna.ical4j.model.property.Attendee +import net.fortuna.ical4j.model.property.Uid +import org.json.JSONException +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class UnknownPropertyTest { + + @Test + @SmallTest + fun testFromExtendedProperty() { + val prop = AndroidEvent.UnknownProperty.fromExtendedProperty("[ \"UID\", \"PropValue\" ]") + assertTrue(prop is Uid) + assertEquals("UID", prop.name) + assertEquals("PropValue", prop.value) + } + + @Test + @SmallTest + fun testFromExtendedPropertyWithParameters() { + val prop = AndroidEvent.UnknownProperty.fromExtendedProperty("[ \"ATTENDEE\", \"PropValue\", { \"x-param1\": \"value1\", \"x-param2\": \"value2\" } ]") + assertTrue(prop is Attendee) + assertEquals("ATTENDEE", prop.name) + assertEquals("PropValue", prop.value) + assertEquals(2, prop.parameters.size()) + assertEquals("value1", prop.parameters.getParameter("x-param1").value) + assertEquals("value2", prop.parameters.getParameter("x-param2").value) + } + + @Test(expected = JSONException::class) + @SmallTest + fun testFromInvalidExtendedProperty() { + AndroidEvent.UnknownProperty.fromExtendedProperty("This isn't JSON") + } + + + @Test + @SmallTest + fun testToExtendedProperty() { + val attendee = Attendee("mailto:test@test.at") + assertEquals( + "ATTENDEE:mailto:test@test.at", + attendee.toString().trim() + ) + + attendee.parameters.add(Rsvp(true)) + attendee.parameters.add(XParameter("X-My-Param", "SomeValue")) + assertEquals( + "ATTENDEE;RSVP=TRUE;X-My-Param=SomeValue:mailto:test@test.at", + attendee.toString().trim() + ) + } + +} \ No newline at end of file diff --git a/src/main/java/at/bitfire/ical4android/AndroidEvent.kt b/src/main/java/at/bitfire/ical4android/AndroidEvent.kt index 23df741..747b626 100644 --- a/src/main/java/at/bitfire/ical4android/AndroidEvent.kt +++ b/src/main/java/at/bitfire/ical4android/AndroidEvent.kt @@ -26,7 +26,11 @@ import net.fortuna.ical4j.model.component.VAlarm import net.fortuna.ical4j.model.parameter.* import net.fortuna.ical4j.model.property.* import net.fortuna.ical4j.util.TimeZones -import java.io.* +import org.json.JSONArray +import org.json.JSONObject +import java.io.ByteArrayInputStream +import java.io.FileNotFoundException +import java.io.ObjectInputStream import java.net.URI import java.net.URISyntaxException import java.text.ParseException @@ -50,7 +54,9 @@ abstract class AndroidEvent( companion object { /** [ExtendedProperties.NAME] for unknown iCal properties */ + @Deprecated("New serialization format", ReplaceWith("EXT_UNKNOWN_PROPERTY2")) const val EXT_UNKNOWN_PROPERTY = "unknown-property" + const val EXT_UNKNOWN_PROPERTY2 = "unknown-property.v2" const val MAX_UNKNOWN_PROPERTY_SIZE = 25000 // not declared in ical4j Parameters class yet @@ -325,17 +331,25 @@ abstract class AndroidEvent( protected open fun populateExtended(row: ContentValues) { Constants.log.log(Level.FINE, "Read extended property from calender provider", row.getAsString(ExtendedProperties.NAME)) + val event = requireNotNull(event) - if (row.getAsString(ExtendedProperties.NAME) == EXT_UNKNOWN_PROPERTY) { - // de-serialize unknown property - val stream = ByteArrayInputStream(Base64.decode(row.getAsString(ExtendedProperties.VALUE), Base64.NO_WRAP)) - try { - ObjectInputStream(stream).use { - event!!.unknownProperties += it.readObject() as Property + try { + when (row.getAsString(ExtendedProperties.NAME)) { + EXT_UNKNOWN_PROPERTY -> { + // deserialize unknown property v1 (deprecated) + val stream = ByteArrayInputStream(Base64.decode(row.getAsString(ExtendedProperties.VALUE), Base64.NO_WRAP)) + ObjectInputStream(stream).use { + event.unknownProperties += it.readObject() as Property + } + } + + EXT_UNKNOWN_PROPERTY2 -> { + // deserialize unknown property v2 + event.unknownProperties += UnknownProperty.fromExtendedProperty(row.getAsString(ExtendedProperties.VALUE)) } - } catch(e: Exception) { - Constants.log.log(Level.WARNING, "Couldn't de-serialize unknown property", e) } + } catch(e: Exception) { + Constants.log.log(Level.WARNING, "Couldn't parse extended property", e) } } @@ -690,25 +704,16 @@ abstract class AndroidEvent( } protected open fun insertUnknownProperty(batch: BatchOperation, idxEvent: Int, property: Property) { - val baos = ByteArrayOutputStream() - try { - ObjectOutputStream(baos).use { oos -> - oos.writeObject(property) - - if (baos.size() > MAX_UNKNOWN_PROPERTY_SIZE) { - Constants.log.warning("Ignoring unknown property with ${baos.size()} octets") - return - } + if (property.value.length > MAX_UNKNOWN_PROPERTY_SIZE) { + Constants.log.warning("Ignoring unknown property with ${property.value.length} octets (too long)") + return + } - val builder = ContentProviderOperation.newInsert(calendar.syncAdapterURI(ExtendedProperties.CONTENT_URI)) - builder .withValue(ExtendedProperties.NAME, EXT_UNKNOWN_PROPERTY) - .withValue(ExtendedProperties.VALUE, Base64.encodeToString(baos.toByteArray(), Base64.NO_WRAP)) + val builder = ContentProviderOperation.newInsert(calendar.syncAdapterURI(ExtendedProperties.CONTENT_URI)) + builder .withValue(ExtendedProperties.NAME, EXT_UNKNOWN_PROPERTY2) + .withValue(ExtendedProperties.VALUE, UnknownProperty.toExtendedProperty(property)) - batch.enqueue(BatchOperation.Operation(builder, ExtendedProperties.EVENT_ID, idxEvent)) - } - } catch(e: IOException) { - Constants.log.log(Level.WARNING, "Couldn't serialize unknown property", e) - } + batch.enqueue(BatchOperation.Operation(builder, ExtendedProperties.EVENT_ID, idxEvent)) } private fun useRetainedClassification() { @@ -737,7 +742,62 @@ abstract class AndroidEvent( return calendar.syncAdapterURI(ContentUris.withAppendedId(Events.CONTENT_URI, id)) } - override fun toString() = MiscUtils.reflectionToString(this) + + /** + * Helpers to (de)serialize unknown properties as JSON to store it in an Android ExtendedProperty row. + * + * Format: `{ propertyName, propertyValue, { param1Name: param1Value, ... } }`, with the third + * array (parameters) being optional. + */ + object UnknownProperty { + + /** + * Deserializes a JSON string from an ExtendedProperty value to an ical4j property. + * + * @param jsonString JSON representation of an ical4j property + * @return ical4j property, generated from [jsonString] + * @throws org.json.JSONException when the input value can't be parsed + */ + fun fromExtendedProperty(jsonString: String): Property { + val json = JSONArray(jsonString) + val name = json.getString(0) + val value = json.getString(1) + + val params = ParameterList() + json.optJSONObject(2)?.let { jsonParams -> + for (paramName in jsonParams.keys()) + params.add(ICalendar.parameterFactoryRegistry.createParameter( + paramName, + jsonParams.getString(paramName) + )) + } + + return ICalendar.propertyFactoryRegistry.createProperty(name, params, value) + } + + /** + * Serializes an ical4j property to a JSON string that can be stored in an ExtendedProperty. + * + * @param prop property to serialize as JSON + * @return JSON representation of [prop] + */ + fun toExtendedProperty(prop: Property): String { + val json = JSONArray() + json.put(prop.name) + json.put(prop.value) + + if (!prop.parameters.isEmpty) { + val jsonParams = JSONObject() + for (param in prop.parameters) + jsonParams.put(param.name, param.value) + json.put(jsonParams) + } + + return json.toString() + } + + } + } diff --git a/src/main/java/at/bitfire/ical4android/ICalendar.kt b/src/main/java/at/bitfire/ical4android/ICalendar.kt index 6942b08..345ed7b 100644 --- a/src/main/java/at/bitfire/ical4android/ICalendar.kt +++ b/src/main/java/at/bitfire/ical4android/ICalendar.kt @@ -38,8 +38,8 @@ open class ICalendar { } var prodId = ProdId("+//IDN bitfire.at//ical4android") - private val propertyFactoryRegistry = PropertyFactoryRegistry() - private val parameterFactoryRegistry = ParameterFactoryRegistry() + val propertyFactoryRegistry = PropertyFactoryRegistry() + val parameterFactoryRegistry = ParameterFactoryRegistry() @JvmStatic protected fun calendarBuilder() = CalendarBuilder( -- GitLab From 03f3b94f245bb31b63b988bea728c417416ce1f3 Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Mon, 18 Feb 2019 14:07:06 +0100 Subject: [PATCH 14/58] Fix tests, update Kotlin/gradle plugin --- build.gradle | 5 +++-- .../java/at/bitfire/ical4android/MiscUtilsTest.kt | 6 +++--- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/build.gradle b/build.gradle index 5dfdc1d..953a702 100644 --- a/build.gradle +++ b/build.gradle @@ -1,6 +1,6 @@ buildscript { - ext.kotlin_version = '1.3.20' + ext.kotlin_version = '1.3.21' ext.dokka_version = '0.9.17' repositories { @@ -9,7 +9,7 @@ buildscript { } dependencies { - classpath 'com.android.tools.build:gradle:3.3.0' + classpath 'com.android.tools.build:gradle:3.3.1' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath "org.jetbrains.dokka:dokka-android-gradle-plugin:${dokka_version}" } @@ -61,6 +61,7 @@ dependencies { implementation 'org.slf4j:slf4j-jdk14:1.7.25' implementation 'androidx.core:core-ktx:1.0.1' + androidTestImplementation 'androidx.test:core:1.1.0' androidTestImplementation 'androidx.test:runner:1.1.1' androidTestImplementation 'androidx.test:rules:1.1.1' diff --git a/src/androidTest/java/at/bitfire/ical4android/MiscUtilsTest.kt b/src/androidTest/java/at/bitfire/ical4android/MiscUtilsTest.kt index f5c8183..c9a54f5 100644 --- a/src/androidTest/java/at/bitfire/ical4android/MiscUtilsTest.kt +++ b/src/androidTest/java/at/bitfire/ical4android/MiscUtilsTest.kt @@ -65,11 +65,11 @@ class MiscUtilsTest { // DATE (without time) assertEquals(TimeZones.UTC_ID, MiscUtils.getTzId(DtStart(Date("20150101")))) - // DATE-TIME without time zone (floating time): should be UTC (because net.fortuna.ical4j.timezone.date.floating=false) - assertEquals(TimeZones.UTC_ID, MiscUtils.getTzId(DtStart(DateTime("20150101T000000")))) + // DATE-TIME without time zone (floating time): should be local time zone (because Android doesn't support floating times) + assertEquals(java.util.TimeZone.getDefault().id, MiscUtils.getTzId(DtStart(DateTime("20150101T000000")))) // DATE-TIME without time zone (UTC) - assertEquals(TimeZones.UTC_ID, MiscUtils.getTzId(DtStart(DateTime(1438607288000L)))) + assertEquals(TimeZones.UTC_ID, MiscUtils.getTzId(DtStart(DateTime(1438607288000L), true))) // DATE-TIME with time zone assertEquals(tzVienna.id, MiscUtils.getTzId(DtStart(DateTime("20150101T000000", tzVienna)))) -- GitLab From 9c8b971961bce8594e2fecd516f17d302716714d Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Mon, 18 Feb 2019 14:56:55 +0100 Subject: [PATCH 15/58] Don't crash when color can't be inserted --- src/main/java/at/bitfire/ical4android/AndroidCalendar.kt | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt b/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt index 106df95..59fbd36 100644 --- a/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt +++ b/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt @@ -18,6 +18,7 @@ import android.provider.CalendarContract import android.provider.CalendarContract.* import java.io.FileNotFoundException import java.util.* +import java.util.logging.Level /** * Represents a locally stored calendar, containing [AndroidEvent]s (whose data objects are [Event]s). @@ -62,7 +63,7 @@ abstract class AndroidCalendar( fun insertColors(provider: ContentProviderClient, account: Account) { provider.query(syncAdapterURI(Colors.CONTENT_URI, account), arrayOf(Colors.COLOR_KEY), null, null, null)?.use { cursor -> if (cursor.count == Css3Color.values().size) - // colors already inserted and up to date + // colors already inserted and up to date return } @@ -74,7 +75,11 @@ abstract class AndroidCalendar( for (color in Css3Color.values()) { values.put(Colors.COLOR_KEY, color.name) values.put(Colors.COLOR, color.argb) - provider.insert(syncAdapterURI(Colors.CONTENT_URI, account), values) + try { + provider.insert(syncAdapterURI(Colors.CONTENT_URI, account), values) + } catch(e: Exception) { + Constants.log.log(Level.WARNING, "Couldn't insert event color: ${color.name}", e) + } } } -- GitLab From be40a3c7201b3d21a72fd1d67387a397ece572b7 Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Sun, 17 Mar 2019 16:00:41 +0100 Subject: [PATCH 16/58] Add info for AboutLibraries --- src/main/res/values/about_strings.xml | 692 ++++++++++++++++++++++++++ 1 file changed, 692 insertions(+) create mode 100644 src/main/res/values/about_strings.xml diff --git a/src/main/res/values/about_strings.xml b/src/main/res/values/about_strings.xml new file mode 100644 index 0000000..e19f329 --- /dev/null +++ b/src/main/res/values/about_strings.xml @@ -0,0 +1,692 @@ + + + + + Ricki Hirner + https://www.bitfire.at + ical4android + Library that brings together iCalendar and Android + https://gitlab.com/bitfireAT/ical4android + gpl_3_0 + true + + + GPLv3 + http://www.gnu.org/licenses/gpl-3.0.html + + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers\' and authors\' protection, the GPL clearly explains +that there is no warranty for this free software. For both users\' and +authors\' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users\' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work\'s +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users\' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work\'s +users, your or third parties\' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program\'s source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation\'s users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party\'s predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor\'s "contributor version". + + A contributor\'s "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor\'s essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient\'s use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others\' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy\'s +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w\'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c\' for details. + +The hypothetical commands `show w\' and `show c\' should show the appropriate +parts of the General Public License. Of course, your program\'s commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +.]]> + + \ No newline at end of file -- GitLab From 1eb42e9f8036355232221bdb1339a5e942f38d8e Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Sat, 23 Mar 2019 22:44:06 +0100 Subject: [PATCH 17/58] Enable Gitlab CI tests again --- .gitlab-ci.yml | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 936610a..27e2949 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -9,10 +9,9 @@ cache: test: script: -# - (cd /sdk/emulator; ./emulator @test -no-audio -no-window & wait-for-emulator.sh) -# - adb install src/androidTest/resources/org.dmfs.tasks_6880.apk -# - ./gradlew check connectedCheck - - ./gradlew check + - (cd /sdk/emulator; ./emulator @test -no-audio -no-window & wait-for-emulator.sh) + - adb install src/androidTest/resources/org.dmfs.tasks_6880.apk + - ./gradlew check connectedCheck artifacts: paths: - build/outputs/lint-results-debug.html -- GitLab From d9f8a0376667ae3ff620bf6fcfd80d5218c9fe45 Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Tue, 26 Mar 2019 12:01:13 +0100 Subject: [PATCH 18/58] Update gradle, remove gpl_3_0 for AboutLibraries 6.2.3+ --- build.gradle | 2 +- src/main/res/values/about_strings.xml | 679 -------------------------- 2 files changed, 1 insertion(+), 680 deletions(-) diff --git a/build.gradle b/build.gradle index 953a702..af4246c 100644 --- a/build.gradle +++ b/build.gradle @@ -9,7 +9,7 @@ buildscript { } dependencies { - classpath 'com.android.tools.build:gradle:3.3.1' + classpath 'com.android.tools.build:gradle:3.3.2' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath "org.jetbrains.dokka:dokka-android-gradle-plugin:${dokka_version}" } diff --git a/src/main/res/values/about_strings.xml b/src/main/res/values/about_strings.xml index e19f329..2d00528 100644 --- a/src/main/res/values/about_strings.xml +++ b/src/main/res/values/about_strings.xml @@ -10,683 +10,4 @@ gpl_3_0 true - - GPLv3 - http://www.gnu.org/licenses/gpl-3.0.html - - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers\' and authors\' protection, the GPL clearly explains -that there is no warranty for this free software. For both users\' and -authors\' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users\' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work\'s -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users\' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work\'s -users, your or third parties\' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program\'s source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation\'s users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party\'s predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor\'s "contributor version". - - A contributor\'s "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor\'s essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient\'s use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others\' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy\'s -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w\'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c\' for details. - -The hypothetical commands `show w\' and `show c\' should show the appropriate -parts of the General Public License. Of course, your program\'s commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -.]]> - \ No newline at end of file -- GitLab From 94feded02e00b3b58645cf1b7af187ade718bf9e Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Tue, 2 Apr 2019 23:59:13 +0200 Subject: [PATCH 19/58] AndroidTask: compare ORGANIZER URI scheme without case sensitivity --- src/main/java/at/bitfire/ical4android/AndroidTask.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/at/bitfire/ical4android/AndroidTask.kt b/src/main/java/at/bitfire/ical4android/AndroidTask.kt index f7556ab..a9e5a17 100644 --- a/src/main/java/at/bitfire/ical4android/AndroidTask.kt +++ b/src/main/java/at/bitfire/ical4android/AndroidTask.kt @@ -216,7 +216,7 @@ abstract class AndroidTask( task.organizer?.let { try { val uri = URI(it.value) - if (uri.scheme == "mailto") + if (uri.scheme.equals("mailto", true)) organizer = uri.schemeSpecificPart else Constants.log.log(Level.WARNING, "Found non-mailto ORGANIZER URI, ignoring", uri) -- GitLab From 8f201fbfb05d26d4180365dc493ee53c436291da Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Wed, 17 Apr 2019 22:46:50 +0200 Subject: [PATCH 20/58] Update Kotlin, gradle, gradle plugin --- build.gradle | 23 +++++++++++------------ gradle/wrapper/gradle-wrapper.properties | 4 ++-- 2 files changed, 13 insertions(+), 14 deletions(-) diff --git a/build.gradle b/build.gradle index af4246c..0226d06 100644 --- a/build.gradle +++ b/build.gradle @@ -1,7 +1,10 @@ buildscript { - ext.kotlin_version = '1.3.21' - ext.dokka_version = '0.9.17' + ext.versions = [ + kotlin: '1.3.30', + dokka: '0.9.17', + ical4j: '2.2.3' + ] repositories { jcenter() @@ -9,9 +12,9 @@ buildscript { } dependencies { - classpath 'com.android.tools.build:gradle:3.3.2' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" - classpath "org.jetbrains.dokka:dokka-android-gradle-plugin:${dokka_version}" + classpath 'com.android.tools.build:gradle:3.4.0' + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${versions.kotlin}" + classpath "org.jetbrains.dokka:dokka-android-gradle-plugin:${versions.dokka}" } } @@ -24,10 +27,6 @@ apply plugin: 'com.android.library' apply plugin: 'kotlin-android' apply plugin: 'org.jetbrains.dokka-android' -ext { - ical4j_version = '2.2.3' -} - android { compileSdkVersion 28 buildToolsVersion '28.0.3' @@ -38,7 +37,7 @@ android { testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" - buildConfigField "String", "version_ical4j", "\"$ical4j_version\"" + buildConfigField "String", "version_ical4j", "\"${versions.ical4j}\"" } lintOptions { disable 'AllowBackup' @@ -55,9 +54,9 @@ android { } dependencies { - implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:${versions.kotlin}" - api "org.mnode.ical4j:ical4j:$ical4j_version" + api "org.mnode.ical4j:ical4j:${versions.ical4j}" implementation 'org.slf4j:slf4j-jdk14:1.7.25' implementation 'androidx.core:core-ktx:1.0.1' diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index a547d65..bf1e464 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Tue Aug 23 16:42:17 CEST 2016 +#Wed Apr 17 22:31:47 CEST 2019 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-5.1-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-all.zip -- GitLab From a8d3eb8ae8aa12044944cd13b393458f7dbe0ed1 Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Tue, 30 Apr 2019 23:36:59 +0200 Subject: [PATCH 21/58] Update ical4j: now allows UTC properties to have non-UTC values for compatibility --- build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index 0226d06..f529483 100644 --- a/build.gradle +++ b/build.gradle @@ -1,9 +1,9 @@ buildscript { ext.versions = [ - kotlin: '1.3.30', + kotlin: '1.3.31', dokka: '0.9.17', - ical4j: '2.2.3' + ical4j: '2.2.4' ] repositories { -- GitLab From 13e85f0be57b3ffa68bb2ea9c6c30589c536454c Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Fri, 17 May 2019 12:03:18 +0200 Subject: [PATCH 22/58] Update gradle plugin, AndroidX core --- build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index f529483..a28b0d8 100644 --- a/build.gradle +++ b/build.gradle @@ -12,7 +12,7 @@ buildscript { } dependencies { - classpath 'com.android.tools.build:gradle:3.4.0' + classpath 'com.android.tools.build:gradle:3.4.1' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${versions.kotlin}" classpath "org.jetbrains.dokka:dokka-android-gradle-plugin:${versions.dokka}" } @@ -58,7 +58,7 @@ dependencies { api "org.mnode.ical4j:ical4j:${versions.ical4j}" implementation 'org.slf4j:slf4j-jdk14:1.7.25' - implementation 'androidx.core:core-ktx:1.0.1' + implementation 'androidx.core:core-ktx:1.0.2' androidTestImplementation 'androidx.test:core:1.1.0' androidTestImplementation 'androidx.test:runner:1.1.1' -- GitLab From b89c0573e8d4328f67ea7bced940ccde64158fa9 Mon Sep 17 00:00:00 2001 From: Nihar Thakkar Date: Sun, 23 Jun 2019 00:06:24 +0530 Subject: [PATCH 23/58] Remove unused file --- src/main/java/foundation/e/ical4android/EventColor.kt | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 src/main/java/foundation/e/ical4android/EventColor.kt diff --git a/src/main/java/foundation/e/ical4android/EventColor.kt b/src/main/java/foundation/e/ical4android/EventColor.kt deleted file mode 100644 index e69de29..0000000 -- GitLab From ce388590034d86397619c27b7f19bc1b86c501c9 Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Sun, 23 Jun 2019 15:42:07 +0200 Subject: [PATCH 24/58] Don't reuse ical4j parameter/property factories in possibly different threads; update Android dependencies --- build.gradle | 10 +++++----- src/main/java/at/bitfire/ical4android/AndroidEvent.kt | 7 +++++-- src/main/java/at/bitfire/ical4android/Event.kt | 3 ++- src/main/java/at/bitfire/ical4android/ICalendar.kt | 8 -------- src/main/java/at/bitfire/ical4android/Task.kt | 3 ++- 5 files changed, 14 insertions(+), 17 deletions(-) diff --git a/build.gradle b/build.gradle index a28b0d8..704f3f4 100644 --- a/build.gradle +++ b/build.gradle @@ -1,8 +1,8 @@ buildscript { ext.versions = [ - kotlin: '1.3.31', - dokka: '0.9.17', + kotlin: '1.3.40', + dokka: '0.9.18', ical4j: '2.2.4' ] @@ -60,9 +60,9 @@ dependencies { implementation 'org.slf4j:slf4j-jdk14:1.7.25' implementation 'androidx.core:core-ktx:1.0.2' - androidTestImplementation 'androidx.test:core:1.1.0' - androidTestImplementation 'androidx.test:runner:1.1.1' - androidTestImplementation 'androidx.test:rules:1.1.1' + androidTestImplementation 'androidx.test:core:1.2.0' + androidTestImplementation 'androidx.test:runner:1.2.0' + androidTestImplementation 'androidx.test:rules:1.2.0' testImplementation 'junit:junit:4.12' } diff --git a/src/main/java/at/bitfire/ical4android/AndroidEvent.kt b/src/main/java/at/bitfire/ical4android/AndroidEvent.kt index 747b626..c5f826a 100644 --- a/src/main/java/at/bitfire/ical4android/AndroidEvent.kt +++ b/src/main/java/at/bitfire/ical4android/AndroidEvent.kt @@ -753,6 +753,9 @@ abstract class AndroidEvent( */ object UnknownProperty { + private val parameterFactory = ParameterFactoryRegistry() + private val propertyFactory = PropertyFactoryRegistry() + /** * Deserializes a JSON string from an ExtendedProperty value to an ical4j property. * @@ -768,13 +771,13 @@ abstract class AndroidEvent( val params = ParameterList() json.optJSONObject(2)?.let { jsonParams -> for (paramName in jsonParams.keys()) - params.add(ICalendar.parameterFactoryRegistry.createParameter( + params.add(parameterFactory.createParameter( paramName, jsonParams.getString(paramName) )) } - return ICalendar.propertyFactoryRegistry.createProperty(name, params, value) + return propertyFactory.createProperty(name, params, value) } /** diff --git a/src/main/java/at/bitfire/ical4android/Event.kt b/src/main/java/at/bitfire/ical4android/Event.kt index 8d92a77..4a7ab9d 100644 --- a/src/main/java/at/bitfire/ical4android/Event.kt +++ b/src/main/java/at/bitfire/ical4android/Event.kt @@ -8,6 +8,7 @@ package at.bitfire.ical4android +import net.fortuna.ical4j.data.CalendarBuilder import net.fortuna.ical4j.data.CalendarOutputter import net.fortuna.ical4j.data.ParserException import net.fortuna.ical4j.model.Calendar @@ -75,7 +76,7 @@ class Event: ICalendar() { // parse stream val ical: Calendar try { - ical = calendarBuilder().build(reader) + ical = CalendarBuilder().build(reader) } catch(e: ParserException) { throw InvalidCalendarException("Couldn't parse iCalendar object", e) } catch(e: IllegalArgumentException) { diff --git a/src/main/java/at/bitfire/ical4android/ICalendar.kt b/src/main/java/at/bitfire/ical4android/ICalendar.kt index 345ed7b..d3bb3bd 100644 --- a/src/main/java/at/bitfire/ical4android/ICalendar.kt +++ b/src/main/java/at/bitfire/ical4android/ICalendar.kt @@ -38,14 +38,6 @@ open class ICalendar { } var prodId = ProdId("+//IDN bitfire.at//ical4android") - val propertyFactoryRegistry = PropertyFactoryRegistry() - val parameterFactoryRegistry = ParameterFactoryRegistry() - - @JvmStatic - protected fun calendarBuilder() = CalendarBuilder( - CalendarParserFactory.getInstance().createParser(), - propertyFactoryRegistry, parameterFactoryRegistry, - TimeZoneRegistryFactory.getInstance().createRegistry()) // time zone helpers diff --git a/src/main/java/at/bitfire/ical4android/Task.kt b/src/main/java/at/bitfire/ical4android/Task.kt index 37239d1..22e8c3c 100644 --- a/src/main/java/at/bitfire/ical4android/Task.kt +++ b/src/main/java/at/bitfire/ical4android/Task.kt @@ -8,6 +8,7 @@ package at.bitfire.ical4android +import net.fortuna.ical4j.data.CalendarBuilder import net.fortuna.ical4j.data.CalendarOutputter import net.fortuna.ical4j.data.ParserException import net.fortuna.ical4j.model.* @@ -64,7 +65,7 @@ class Task: ICalendar() { fun fromReader(reader: Reader): List { val ical: Calendar try { - ical = calendarBuilder().build(reader) + ical = CalendarBuilder().build(reader) } catch(e: ParserException) { throw InvalidCalendarException("Couldn't parse iCalendar object", e) } catch(e: IllegalArgumentException) { -- GitLab From c6e4f19ee284e0636a8fbac08523b3937441971a Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Mon, 8 Jul 2019 15:30:32 +0200 Subject: [PATCH 25/58] Update to ical4j/2.2.5 to fix problem with VTIMEZONEs with only DAYLIGHT --- build.gradle | 4 ++-- src/test/java/at/bitfire/ical4android/EventTest.kt | 8 ++------ 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/build.gradle b/build.gradle index 704f3f4..5ad383a 100644 --- a/build.gradle +++ b/build.gradle @@ -1,9 +1,9 @@ buildscript { ext.versions = [ - kotlin: '1.3.40', + kotlin: '1.3.41', dokka: '0.9.18', - ical4j: '2.2.4' + ical4j: '2.2.5' ] repositories { diff --git a/src/test/java/at/bitfire/ical4android/EventTest.kt b/src/test/java/at/bitfire/ical4android/EventTest.kt index be683bd..8d147f6 100644 --- a/src/test/java/at/bitfire/ical4android/EventTest.kt +++ b/src/test/java/at/bitfire/ical4android/EventTest.kt @@ -37,19 +37,15 @@ class EventTest { assertEquals("中华人民共和国", e.location) } - @Test(expected = AssertionError::class) + @Test fun testDstOnlyVtimezone() { - // Google Calendar (and maybe others) generate iCalendars which contain VTIMEZONE definitions - // with only a DAYLIGHT component (and no STANDARD component). This is technically valid, - // but results in wrong dates in ical4j: - // https://github.com/ical4j/ical4j/issues/230 + // see https://github.com/ical4j/ical4j/issues/230 val events = parseCalendar("dst-only-vtimezone.ics") assertEquals(1, events.size) val e = events.first() assertEquals("only-dst@example.com", e.uid) val dtStart = e.dtStart!! assertEquals("Europe/Berlin", dtStart.timeZone.id) - // FIXME this should not fail, but it does: assertEquals(1522738800000L, dtStart.date.time) } -- GitLab From 559727c53746478cb4c5ecceddee926095e1ac0f Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Fri, 12 Jul 2019 22:45:07 +0200 Subject: [PATCH 26/58] Update gradle plugin --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 5ad383a..b54a313 100644 --- a/build.gradle +++ b/build.gradle @@ -12,7 +12,7 @@ buildscript { } dependencies { - classpath 'com.android.tools.build:gradle:3.4.1' + classpath 'com.android.tools.build:gradle:3.4.2' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${versions.kotlin}" classpath "org.jetbrains.dokka:dokka-android-gradle-plugin:${versions.dokka}" } -- GitLab From 0d21cca34cc6a7098d860acf77955de99a518c4b Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Wed, 17 Jul 2019 17:01:44 +0200 Subject: [PATCH 27/58] Update dependencies --- build.gradle | 5 +++-- gradle/wrapper/gradle-wrapper.properties | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/build.gradle b/build.gradle index b54a313..23757bc 100644 --- a/build.gradle +++ b/build.gradle @@ -29,7 +29,7 @@ apply plugin: 'org.jetbrains.dokka-android' android { compileSdkVersion 28 - buildToolsVersion '28.0.3' + buildToolsVersion '29.0.1' defaultConfig { minSdkVersion 19 @@ -39,6 +39,7 @@ android { buildConfigField "String", "version_ical4j", "\"${versions.ical4j}\"" } + lintOptions { disable 'AllowBackup' disable 'InvalidPackage' @@ -57,7 +58,7 @@ dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:${versions.kotlin}" api "org.mnode.ical4j:ical4j:${versions.ical4j}" - implementation 'org.slf4j:slf4j-jdk14:1.7.25' + implementation 'org.slf4j:slf4j-jdk14:1.7.26' implementation 'androidx.core:core-ktx:1.0.2' androidTestImplementation 'androidx.test:core:1.2.0' diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index bf1e464..dcc7728 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-5.5.1-all.zip -- GitLab From a59848577e065ed92890d94f1ff24c764ebbb5e4 Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Sat, 20 Jul 2019 22:01:00 +0200 Subject: [PATCH 28/58] Update README --- README.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index a26788b..9022621 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ # ical4android -ical4android is an Android library that brings together iCalendar and Android. +ical4android is a library for Android that brings together iCalendar and Android. It's a framework for * parsing and generating iCalendar resources (using [ical4j](https://github.com/ical4j/ical4j)) @@ -14,11 +14,16 @@ It's a framework for It has been primarily developed for: -* [DAVdroid](https://www.davdroid.com) -* [ICSdroid](https://icsdroid.bitfire.at) +* [DAVx⁵](https://www.davx5.com) +* [ICSx⁵](https://icsx5.bitfire.at) + +_This software is not affiliated to, nor has it been authorized, sponsored or otherwise approved +by Google LLC. Android is a trademark of Google LLC._ Generated KDoc: https://bitfireAT.gitlab.io/ical4android/dokka/ical4android/ +Discussion: https://forums.bitfire.at/category/18/libraries + ## Contact @@ -30,9 +35,6 @@ Florastraße 27 Email: [play@bitfire.at](mailto:play@bitfire.at) (do not use this) -For questions, suggestions etc. please use the DAVdroid forum: -https://www.davdroid.com/forums/ - ## License -- GitLab From 18585c9db4cc6d62ec9f26b189c4efd9c30ad67c Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Thu, 12 Sep 2019 14:23:38 +0200 Subject: [PATCH 29/58] Tasks: support CATEGORIES --- .../at/bitfire/ical4android/MiscUtilsTest.kt | 24 +++++++ .../bitfire/ical4android/AndroidCalendar.kt | 9 +-- .../at/bitfire/ical4android/AndroidEvent.kt | 5 +- .../at/bitfire/ical4android/AndroidTask.kt | 68 +++++++++++++++++-- .../bitfire/ical4android/AndroidTaskList.kt | 18 ++--- .../java/at/bitfire/ical4android/ICalendar.kt | 3 +- .../java/at/bitfire/ical4android/MiscUtils.kt | 31 +++++++++ src/main/java/at/bitfire/ical4android/Task.kt | 6 ++ .../at/bitfire/ical4android/TaskProvider.kt | 7 +- 9 files changed, 140 insertions(+), 31 deletions(-) diff --git a/src/androidTest/java/at/bitfire/ical4android/MiscUtilsTest.kt b/src/androidTest/java/at/bitfire/ical4android/MiscUtilsTest.kt index c9a54f5..c00cb41 100644 --- a/src/androidTest/java/at/bitfire/ical4android/MiscUtilsTest.kt +++ b/src/androidTest/java/at/bitfire/ical4android/MiscUtilsTest.kt @@ -9,10 +9,14 @@ package at.bitfire.ical4android import android.content.ContentValues +import android.database.MatrixCursor import androidx.test.filters.SmallTest +import at.bitfire.ical4android.MiscUtils.CursorHelper.toValues +import at.bitfire.ical4android.MiscUtils.TextListHelper.toList import net.fortuna.ical4j.data.CalendarBuilder import net.fortuna.ical4j.model.Date import net.fortuna.ical4j.model.DateTime +import net.fortuna.ical4j.model.TextList import net.fortuna.ical4j.model.TimeZone import net.fortuna.ical4j.model.component.VTimeZone import net.fortuna.ical4j.model.property.DtStart @@ -98,6 +102,26 @@ class MiscUtilsTest { } + @Test + @SmallTest + fun testCursorToValues() { + val columns = arrayOf("col1", "col2") + val c = MatrixCursor(columns) + c.addRow(arrayOf("row1_val1", "row1_val2")) + c.moveToFirst() + val values = c.toValues() + assertEquals("row1_val1", values.getAsString("col1")) + assertEquals("row1_val2", values.getAsString("col2")) + } + + @Test + @SmallTest + fun testTextListToList() { + assertEquals(listOf("str1", "str2"), TextList(arrayOf("str1", "str2")).toList()) + assertEquals(emptyList(), TextList(arrayOf()).toList()) + } + + @Suppress("unused") private class TestClass { private val s = "test" diff --git a/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt b/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt index 59fbd36..67f1637 100644 --- a/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt +++ b/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt @@ -12,10 +12,10 @@ import android.accounts.Account import android.content.ContentProviderClient import android.content.ContentUris import android.content.ContentValues -import android.database.DatabaseUtils import android.net.Uri import android.provider.CalendarContract import android.provider.CalendarContract.* +import at.bitfire.ical4android.MiscUtils.CursorHelper.toValues import java.io.FileNotFoundException import java.util.* import java.util.logging.Level @@ -177,11 +177,8 @@ abstract class AndroidCalendar( val events = LinkedList() provider.query(eventsSyncURI(), null, where, whereArgs, null)?.use { cursor -> - while (cursor.moveToNext()) { - val values = ContentValues(cursor.columnCount) - DatabaseUtils.cursorRowToContentValues(cursor, values) - events += eventFactory.fromProvider(this, values) - } + while (cursor.moveToNext()) + events += eventFactory.fromProvider(this, cursor.toValues()) } return events } diff --git a/src/main/java/at/bitfire/ical4android/AndroidEvent.kt b/src/main/java/at/bitfire/ical4android/AndroidEvent.kt index c5f826a..513c5cc 100644 --- a/src/main/java/at/bitfire/ical4android/AndroidEvent.kt +++ b/src/main/java/at/bitfire/ical4android/AndroidEvent.kt @@ -13,12 +13,12 @@ import android.content.ContentProviderOperation.Builder import android.content.ContentUris import android.content.ContentValues import android.content.EntityIterator -import android.database.DatabaseUtils import android.net.Uri import android.os.RemoteException import android.provider.CalendarContract import android.provider.CalendarContract.* import android.util.Base64 +import at.bitfire.ical4android.MiscUtils.CursorHelper.toValues import net.fortuna.ical4j.model.* import net.fortuna.ical4j.model.Date import net.fortuna.ical4j.model.TimeZone @@ -361,8 +361,7 @@ abstract class AndroidEvent( null, Events.ORIGINAL_ID + "=?", arrayOf(id.toString()), null)?.use { c -> while (c.moveToNext()) { - val values = ContentValues(c.columnCount) - DatabaseUtils.cursorRowToContentValues(c, values) + val values = c.toValues() try { val exception = calendar.eventFactory.fromProvider(calendar, values) diff --git a/src/main/java/at/bitfire/ical4android/AndroidTask.kt b/src/main/java/at/bitfire/ical4android/AndroidTask.kt index a9e5a17..1597996 100644 --- a/src/main/java/at/bitfire/ical4android/AndroidTask.kt +++ b/src/main/java/at/bitfire/ical4android/AndroidTask.kt @@ -12,14 +12,16 @@ import android.content.ContentProviderOperation import android.content.ContentProviderOperation.Builder import android.content.ContentUris import android.content.ContentValues -import android.database.DatabaseUtils import android.net.Uri import android.os.RemoteException +import at.bitfire.ical4android.MiscUtils.CursorHelper.toValues import net.fortuna.ical4j.model.Date import net.fortuna.ical4j.model.DateTime import net.fortuna.ical4j.model.Dur import net.fortuna.ical4j.model.property.* -import org.dmfs.tasks.contract.TaskContract.Tasks +import org.dmfs.tasks.contract.TaskContract.* +import org.dmfs.tasks.contract.TaskContract.Properties +import org.dmfs.tasks.contract.TaskContract.Property.Category import java.io.FileNotFoundException import java.net.URI import java.net.URISyntaxException @@ -66,11 +68,25 @@ abstract class AndroidTask( val id = requireNotNull(id) task = Task() - taskList.provider.client.query(taskSyncURI(), null, null, null, null)?.use { cursor -> + val client = taskList.provider.client + client.query(taskSyncURI(), null, null, null, null)?.use { cursor -> if (cursor.moveToFirst()) { - val values = ContentValues(cursor.columnCount) - DatabaseUtils.cursorRowToContentValues(cursor, values) + val values = cursor.toValues() + Constants.log.log(Level.FINER, "Found task", values) populateTask(values) + + if (values.getAsInteger(Tasks.HAS_PROPERTIES) != 0) + // fetch properties + client.query(taskList.tasksPropertiesSyncUri(), null, + "${Properties.TASK_ID}=?", arrayOf(id.toString()), + null)?.use { propCursor -> + while (propCursor.moveToNext()) { + val propValues = propCursor.toValues() + Constants.log.log(Level.FINER, "Found property", propValues) + populateProperty(propValues) + } + } + return task } } @@ -161,6 +177,17 @@ abstract class AndroidTask( values.getAsString(Tasks.RRULE)?.let { task.rRule = RRule(it) } } + protected open fun populateProperty(values: ContentValues) { + val task = requireNotNull(task) + val type = values.getAsString(Properties.MIMETYPE) + when (type) { + Category.CONTENT_ITEM_TYPE -> + task.categories += values.getAsString(Category.CATEGORY_NAME) + else -> + Constants.log.warning("Found unknown property of type $type") + } + } + fun add(): Uri { val batch = BatchOperation(taskList.provider.client) @@ -169,8 +196,13 @@ abstract class AndroidTask( batch.enqueue(BatchOperation.Operation(builder)) batch.commit() + // TODO use backref mechanism so that only one commit is required for the whole task val result = batch.getResult(0) ?: throw CalendarStorageException("Empty result from provider when adding a task") id = ContentUris.parseId(result.uri) + + insertProperties(batch) + batch.commit() + return result.uri } @@ -182,10 +214,30 @@ abstract class AndroidTask( val builder = ContentProviderOperation.newUpdate(uri) buildTask(builder, true) batch.enqueue(BatchOperation.Operation(builder)) + + val deleteProperties = ContentProviderOperation.newDelete(taskList.tasksPropertiesSyncUri()) + .withSelection("${Properties.TASK_ID}=?", arrayOf(id.toString())) + batch.enqueue(BatchOperation.Operation(deleteProperties)) + insertProperties(batch) + batch.commit() return uri } + private fun insertProperties(batch: BatchOperation) { + val task = requireNotNull(task) + + // insert categories + for (category in task.categories) { + val builder = ContentProviderOperation.newInsert(taskList.tasksPropertiesSyncUri()) + builder .withValue(Category.TASK_ID, id) + .withValue(Category.MIMETYPE, Category.CONTENT_ITEM_TYPE) + .withValue(Category.CATEGORY_NAME, category) + Constants.log.log(Level.FINE, "Inserting category", builder.build()) + batch.enqueue(BatchOperation.Operation(builder)) + } + } + fun delete(): Int { try { return taskList.provider.client.delete(taskSyncURI(), null, null) @@ -268,7 +320,6 @@ abstract class AndroidTask( .withValue(Tasks.RRULE, task.rRule?.value) builder .withValue(Tasks.EXDATE, if (task.exDates.isEmpty()) null else DateUtils.recurrenceSetsToAndroidString(task.exDates, allDay)) - Constants.log.log(Level.FINE, "Built task object", builder.build()) } @@ -286,7 +337,10 @@ abstract class AndroidTask( protected fun taskSyncURI(): Uri { val id = requireNotNull(id) - return ContentUris.withAppendedId(taskList.tasksSyncUri(), id) + val builder = taskList.tasksSyncUri().buildUpon() + return ContentUris.appendId(builder, id) + .appendQueryParameter(LOAD_PROPERTIES, "1") + .build() } diff --git a/src/main/java/at/bitfire/ical4android/AndroidTaskList.kt b/src/main/java/at/bitfire/ical4android/AndroidTaskList.kt index 49a08ba..8655cd9 100644 --- a/src/main/java/at/bitfire/ical4android/AndroidTaskList.kt +++ b/src/main/java/at/bitfire/ical4android/AndroidTaskList.kt @@ -12,14 +12,15 @@ import android.accounts.Account import android.content.ContentUris import android.content.ContentValues import android.content.Context -import android.database.DatabaseUtils import android.net.Uri +import at.bitfire.ical4android.MiscUtils.CursorHelper.toValues import org.dmfs.tasks.contract.TaskContract import org.dmfs.tasks.contract.TaskContract.TaskLists import org.dmfs.tasks.contract.TaskContract.Tasks import java.io.FileNotFoundException import java.util.* + /** * Represents a locally stored task list, containing AndroidTasks (whose data objects are Tasks). * Communicates with third-party content providers to store the tasks. @@ -67,9 +68,7 @@ abstract class AndroidTaskList( provider.client.query(TaskProvider.syncAdapterUri(ContentUris.withAppendedId(provider.taskListsUri(), id), account), null, null, null, null)?.use { cursor -> if (cursor.moveToNext()) { val taskList = factory.newInstance(account, provider, id) - val values = ContentValues(cursor.columnCount) - DatabaseUtils.cursorRowToContentValues(cursor, values) - taskList.populate(values) + taskList.populate(cursor.toValues()) return taskList } } @@ -80,8 +79,7 @@ abstract class AndroidTaskList( val taskLists = LinkedList() provider.client.query(TaskProvider.syncAdapterUri(provider.taskListsUri(), account), null, where, whereArgs, null)?.use { cursor -> while (cursor.moveToNext()) { - val values = ContentValues(cursor.columnCount) - DatabaseUtils.cursorRowToContentValues(cursor, values) + val values = cursor.toValues() val taskList = factory.newInstance(account, provider, values.getAsLong(TaskLists._ID)) taskList.populate(values) taskLists += taskList @@ -127,11 +125,8 @@ abstract class AndroidTaskList( tasksSyncUri(), null, where, whereArgs, null)?.use { cursor -> - while (cursor.moveToNext()) { - val values = ContentValues(cursor.columnCount) - DatabaseUtils.cursorRowToContentValues(cursor, values) - tasks += taskFactory.fromProvider(this, values) - } + while (cursor.moveToNext()) + tasks += taskFactory.fromProvider(this, cursor.toValues()) } return tasks } @@ -142,5 +137,6 @@ abstract class AndroidTaskList( fun taskListSyncUri() = TaskProvider.syncAdapterUri(ContentUris.withAppendedId(provider.taskListsUri(), id), account) fun tasksSyncUri() = TaskProvider.syncAdapterUri(provider.tasksUri(), account) + fun tasksPropertiesSyncUri() = TaskProvider.syncAdapterUri(provider.propertiesUri(), account) } diff --git a/src/main/java/at/bitfire/ical4android/ICalendar.kt b/src/main/java/at/bitfire/ical4android/ICalendar.kt index d3bb3bd..ee5796c 100644 --- a/src/main/java/at/bitfire/ical4android/ICalendar.kt +++ b/src/main/java/at/bitfire/ical4android/ICalendar.kt @@ -9,10 +9,9 @@ package at.bitfire.ical4android import net.fortuna.ical4j.data.CalendarBuilder -import net.fortuna.ical4j.data.CalendarParserFactory import net.fortuna.ical4j.data.ParserException -import net.fortuna.ical4j.model.* import net.fortuna.ical4j.model.Date +import net.fortuna.ical4j.model.DateTime import net.fortuna.ical4j.model.component.* import net.fortuna.ical4j.model.property.DateProperty import net.fortuna.ical4j.model.property.ProdId diff --git a/src/main/java/at/bitfire/ical4android/MiscUtils.kt b/src/main/java/at/bitfire/ical4android/MiscUtils.kt index ae14494..d3dfce5 100644 --- a/src/main/java/at/bitfire/ical4android/MiscUtils.kt +++ b/src/main/java/at/bitfire/ical4android/MiscUtils.kt @@ -9,6 +9,9 @@ package at.bitfire.ical4android import android.content.ContentValues +import android.database.Cursor +import android.database.DatabaseUtils +import net.fortuna.ical4j.model.TextList import net.fortuna.ical4j.model.property.DateProperty import net.fortuna.ical4j.util.TimeZones import java.lang.reflect.Modifier @@ -93,4 +96,32 @@ object MiscUtils { } } + + object CursorHelper { + + /** + * Returns the entire contents of the current row as a [ContentValues] object. + * @return entire contents of the current row + */ + fun Cursor.toValues(): ContentValues { + val values = ContentValues(columnCount) + DatabaseUtils.cursorRowToContentValues(this, values) + return values + } + + } + + + object TextListHelper { + + fun TextList.toList(): List { + val list = LinkedList() + val it = iterator() + while (it.hasNext()) + list += it.next() + return list + } + + } + } \ No newline at end of file diff --git a/src/main/java/at/bitfire/ical4android/Task.kt b/src/main/java/at/bitfire/ical4android/Task.kt index 22e8c3c..1ceb39f 100644 --- a/src/main/java/at/bitfire/ical4android/Task.kt +++ b/src/main/java/at/bitfire/ical4android/Task.kt @@ -8,6 +8,7 @@ package at.bitfire.ical4android +import at.bitfire.ical4android.MiscUtils.TextListHelper.toList import net.fortuna.ical4j.data.CalendarBuilder import net.fortuna.ical4j.data.CalendarOutputter import net.fortuna.ical4j.data.ParserException @@ -50,6 +51,7 @@ class Task: ICalendar() { val rDates = LinkedList() val exDates = LinkedList() + val categories = LinkedList() val unknownProperties = LinkedList() companion object { @@ -112,6 +114,7 @@ class Task: ICalendar() { is RRule -> t.rRule = prop is RDate -> t.rDates += prop is ExDate -> t.exDates += prop + is Categories -> t.categories.addAll(prop.categories.toList()) is ProdId, is DtStamp -> { /* don't save these as unknown properties */ } else -> t.unknownProperties += prop } @@ -186,6 +189,9 @@ class Task: ICalendar() { } percentComplete?.let { props += PercentComplete(it) } + if (categories.isNotEmpty()) + props += Categories(TextList(categories.toTypedArray())) + props.addAll(unknownProperties) // add VTIMEZONE components diff --git a/src/main/java/at/bitfire/ical4android/TaskProvider.kt b/src/main/java/at/bitfire/ical4android/TaskProvider.kt index 57ded7c..0a21dcd 100644 --- a/src/main/java/at/bitfire/ical4android/TaskProvider.kt +++ b/src/main/java/at/bitfire/ical4android/TaskProvider.kt @@ -99,10 +99,13 @@ class TaskProvider private constructor( fun taskListsUri() = TaskContract.TaskLists.getContentUri(name.authority)!! - fun tasksUri() = TaskContract.Tasks.getContentUri(name.authority)!! - //fun alarmsUri() = TaskContract.Alarms.getContentUri(name.authority)!! fun syncStateUri() = TaskContract.SyncState.getContentUri(name.authority)!! + fun tasksUri() = TaskContract.Tasks.getContentUri(name.authority)!! + fun propertiesUri() = TaskContract.Properties.getContentUri(name.authority)!! + fun alarmsUri() = TaskContract.Alarms.getContentUri(name.authority)!! + fun categoriesUri() = TaskContract.Categories.getContentUri(name.authority)!! + override fun close() { if (Build.VERSION.SDK_INT >= 24) -- GitLab From 5991809cb28fb800b47278d082aa4de704a67dfb Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Mon, 30 Sep 2019 11:38:58 +0200 Subject: [PATCH 30/58] Update ical4j and other dependencies --- build.gradle | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/build.gradle b/build.gradle index 23757bc..240f80d 100644 --- a/build.gradle +++ b/build.gradle @@ -1,9 +1,9 @@ buildscript { ext.versions = [ - kotlin: '1.3.41', + kotlin: '1.3.50', dokka: '0.9.18', - ical4j: '2.2.5' + ical4j: '2.2.6' ] repositories { @@ -12,7 +12,7 @@ buildscript { } dependencies { - classpath 'com.android.tools.build:gradle:3.4.2' + classpath 'com.android.tools.build:gradle:3.5.0' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${versions.kotlin}" classpath "org.jetbrains.dokka:dokka-android-gradle-plugin:${versions.dokka}" } @@ -28,12 +28,12 @@ apply plugin: 'kotlin-android' apply plugin: 'org.jetbrains.dokka-android' android { - compileSdkVersion 28 + compileSdkVersion 29 buildToolsVersion '29.0.1' defaultConfig { minSdkVersion 19 - targetSdkVersion 28 + targetSdkVersion 29 testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" @@ -59,7 +59,7 @@ dependencies { api "org.mnode.ical4j:ical4j:${versions.ical4j}" implementation 'org.slf4j:slf4j-jdk14:1.7.26' - implementation 'androidx.core:core-ktx:1.0.2' + implementation 'androidx.core:core-ktx:1.1.0' androidTestImplementation 'androidx.test:core:1.2.0' androidTestImplementation 'androidx.test:runner:1.2.0' -- GitLab From 5ede9f9c2393508454e0fb4f9ea7b4351d7a369f Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Thu, 7 Nov 2019 18:11:15 +0100 Subject: [PATCH 31/58] Update dependencies, lint --- build.gradle | 4 ++-- .../at/bitfire/ical4android/AndroidCalendar.kt | 18 +++++++++--------- .../at/bitfire/ical4android/AndroidEvent.kt | 13 +++++-------- .../at/bitfire/ical4android/AndroidTask.kt | 5 ++--- .../at/bitfire/ical4android/AndroidTaskList.kt | 2 +- .../java/at/bitfire/ical4android/Constants.kt | 2 +- .../java/at/bitfire/ical4android/Css3Color.kt | 6 ++++-- .../java/at/bitfire/ical4android/ICalendar.kt | 2 +- .../at/bitfire/ical4android/TaskProvider.kt | 2 +- 9 files changed, 26 insertions(+), 28 deletions(-) diff --git a/build.gradle b/build.gradle index 240f80d..95f4864 100644 --- a/build.gradle +++ b/build.gradle @@ -12,7 +12,7 @@ buildscript { } dependencies { - classpath 'com.android.tools.build:gradle:3.5.0' + classpath 'com.android.tools.build:gradle:3.5.2' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${versions.kotlin}" classpath "org.jetbrains.dokka:dokka-android-gradle-plugin:${versions.dokka}" } @@ -29,7 +29,7 @@ apply plugin: 'org.jetbrains.dokka-android' android { compileSdkVersion 29 - buildToolsVersion '29.0.1' + buildToolsVersion '29.0.2' defaultConfig { minSdkVersion 19 diff --git a/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt b/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt index 67f1637..1c3e328 100644 --- a/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt +++ b/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt @@ -55,7 +55,7 @@ abstract class AndroidCalendar( info.put(Calendars.ALLOWED_AVAILABILITY, "${Events.AVAILABILITY_BUSY},${Events.AVAILABILITY_FREE},${Events.AVAILABILITY_TENTATIVE}") info.put(Calendars.ALLOWED_ATTENDEE_TYPES, "${Attendees.TYPE_NONE},${Attendees.TYPE_OPTIONAL},${Attendees.TYPE_REQUIRED},${Attendees.TYPE_RESOURCE}") - Constants.log.info("Creating local calendar: " + info.toString()) + Constants.log.info("Creating local calendar: $info") return provider.insert(syncAdapterURI(Calendars.CONTENT_URI, account), info) ?: throw Exception("Couldn't create calendar: provider returned null") } @@ -69,8 +69,8 @@ abstract class AndroidCalendar( Constants.log.info("Inserting event colors for account $account") val values = ContentValues(5) - values.put(CalendarContract.Colors.ACCOUNT_NAME, account.name) - values.put(CalendarContract.Colors.ACCOUNT_TYPE, account.type) + values.put(Colors.ACCOUNT_NAME, account.name) + values.put(Colors.ACCOUNT_TYPE, account.type) values.put(Colors.COLOR_TYPE, Colors.TYPE_EVENT) for (color in Css3Color.values()) { values.put(Colors.COLOR_KEY, color.name) @@ -100,8 +100,8 @@ abstract class AndroidCalendar( } fun> findByID(account: Account, provider: ContentProviderClient, factory: AndroidCalendarFactory, id: Long): T { - val iterCalendars = CalendarContract.CalendarEntity.newEntityIterator( - provider.query(syncAdapterURI(ContentUris.withAppendedId(CalendarContract.CalendarEntity.CONTENT_URI, id), account), null, null, null, null) + val iterCalendars = CalendarEntity.newEntityIterator( + provider.query(syncAdapterURI(ContentUris.withAppendedId(CalendarEntity.CONTENT_URI, id), account), null, null, null, null) ) try { if (iterCalendars.hasNext()) { @@ -117,8 +117,8 @@ abstract class AndroidCalendar( } fun> find(account: Account, provider: ContentProviderClient, factory: AndroidCalendarFactory, where: String?, whereArgs: Array?): List { - val iterCalendars = CalendarContract.CalendarEntity.newEntityIterator( - provider.query(syncAdapterURI(CalendarContract.CalendarEntity.CONTENT_URI, account), null, where, whereArgs, null) + val iterCalendars = CalendarEntity.newEntityIterator( + provider.query(syncAdapterURI(CalendarEntity.CONTENT_URI, account), null, where, whereArgs, null) ) try { val calendars = LinkedList() @@ -137,7 +137,7 @@ abstract class AndroidCalendar( fun syncAdapterURI(uri: Uri, account: Account) = uri.buildUpon() .appendQueryParameter(Calendars.ACCOUNT_NAME, account.name) .appendQueryParameter(Calendars.ACCOUNT_TYPE, account.type) - .appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true") + .appendQueryParameter(CALLER_IS_SYNCADAPTER, "true") .build()!! } @@ -188,7 +188,7 @@ abstract class AndroidCalendar( fun syncAdapterURI(uri: Uri) = uri.buildUpon() - .appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true") + .appendQueryParameter(CALLER_IS_SYNCADAPTER, "true") .appendQueryParameter(Calendars.ACCOUNT_NAME, account.name) .appendQueryParameter(Calendars.ACCOUNT_TYPE, account.type) .build()!! diff --git a/src/main/java/at/bitfire/ical4android/AndroidEvent.kt b/src/main/java/at/bitfire/ical4android/AndroidEvent.kt index 513c5cc..6936593 100644 --- a/src/main/java/at/bitfire/ical4android/AndroidEvent.kt +++ b/src/main/java/at/bitfire/ical4android/AndroidEvent.kt @@ -15,7 +15,6 @@ import android.content.ContentValues import android.content.EntityIterator import android.net.Uri import android.os.RemoteException -import android.provider.CalendarContract import android.provider.CalendarContract.* import android.util.Base64 import at.bitfire.ical4android.MiscUtils.CursorHelper.toValues @@ -99,9 +98,9 @@ abstract class AndroidEvent( var iterEvents: EntityIterator? = null try { - iterEvents = CalendarContract.EventsEntity.newEntityIterator( + iterEvents = EventsEntity.newEntityIterator( calendar.provider.query( - calendar.syncAdapterURI(ContentUris.withAppendedId(CalendarContract.EventsEntity.CONTENT_URI, id)), + calendar.syncAdapterURI(ContentUris.withAppendedId(EventsEntity.CONTENT_URI, id)), null, null, null, null), calendar.provider ) @@ -116,7 +115,7 @@ abstract class AndroidEvent( when (subValue.uri) { Attendees.CONTENT_URI -> populateAttendee(subValue.values) Reminders.CONTENT_URI -> populateReminder(subValue.values) - CalendarContract.ExtendedProperties.CONTENT_URI -> populateExtended(subValue.values) + ExtendedProperties.CONTENT_URI -> populateExtended(subValue.values) } populateExceptions() @@ -280,8 +279,7 @@ abstract class AndroidEvent( params.add(if (type == Attendees.TYPE_RESOURCE) CuType.RESOURCE else CuType.INDIVIDUAL) // role - val relationship = row.getAsInteger(Attendees.ATTENDEE_RELATIONSHIP) - when (relationship) { + when (row.getAsInteger(Attendees.ATTENDEE_RELATIONSHIP)) { Attendees.RELATIONSHIP_ORGANIZER, Attendees.RELATIONSHIP_ATTENDEE, Attendees.RELATIONSHIP_PERFORMER, @@ -685,8 +683,7 @@ abstract class AndroidEvent( builder.withValue(Attendees.ATTENDEE_RELATIONSHIP, relationship) } - val partStat = attendee.getParameter(Parameter.PARTSTAT) as? PartStat - val status = when(partStat) { + val status = when(attendee.getParameter(Parameter.PARTSTAT) as? PartStat) { null, PartStat.NEEDS_ACTION -> Attendees.ATTENDEE_STATUS_INVITED PartStat.ACCEPTED -> Attendees.ATTENDEE_STATUS_ACCEPTED diff --git a/src/main/java/at/bitfire/ical4android/AndroidTask.kt b/src/main/java/at/bitfire/ical4android/AndroidTask.kt index 1597996..3f102c8 100644 --- a/src/main/java/at/bitfire/ical4android/AndroidTask.kt +++ b/src/main/java/at/bitfire/ical4android/AndroidTask.kt @@ -179,8 +179,7 @@ abstract class AndroidTask( protected open fun populateProperty(values: ContentValues) { val task = requireNotNull(task) - val type = values.getAsString(Properties.MIMETYPE) - when (type) { + when (val type = values.getAsString(Properties.MIMETYPE)) { Category.CONTENT_ITEM_TYPE -> task.categories += values.getAsString(Category.CATEGORY_NAME) else -> @@ -327,7 +326,7 @@ abstract class AndroidTask( fun getTimeZone(): TimeZone { val task = requireNotNull(task) - var tz: java.util.TimeZone? = null + var tz: TimeZone? = null task.dtStart?.timeZone?.let { tz = it } tz = tz ?: task.due?.timeZone diff --git a/src/main/java/at/bitfire/ical4android/AndroidTaskList.kt b/src/main/java/at/bitfire/ical4android/AndroidTaskList.kt index 8655cd9..83a67a3 100644 --- a/src/main/java/at/bitfire/ical4android/AndroidTaskList.kt +++ b/src/main/java/at/bitfire/ical4android/AndroidTaskList.kt @@ -59,7 +59,7 @@ abstract class AndroidTaskList( info.put(TaskContract.ACCOUNT_TYPE, account.type) info.put(TaskLists.ACCESS_LEVEL, 0) - Constants.log.info("Creating local task list: " + info.toString()) + Constants.log.info("Creating local task list: $info") return provider.client.insert(TaskProvider.syncAdapterUri(provider.taskListsUri(), account), info) ?: throw CalendarStorageException("Couldn't create task list (empty result from provider)") } diff --git a/src/main/java/at/bitfire/ical4android/Constants.kt b/src/main/java/at/bitfire/ical4android/Constants.kt index 4ff863b..0163b02 100644 --- a/src/main/java/at/bitfire/ical4android/Constants.kt +++ b/src/main/java/at/bitfire/ical4android/Constants.kt @@ -12,7 +12,7 @@ import java.util.logging.Logger object Constants { - val log = Logger.getLogger("ical4android")!! + val log = Logger.getLogger("ical4android") const val ical4jVersion = BuildConfig.version_ical4j diff --git a/src/main/java/at/bitfire/ical4android/Css3Color.kt b/src/main/java/at/bitfire/ical4android/Css3Color.kt index 5fb2672..234e505 100644 --- a/src/main/java/at/bitfire/ical4android/Css3Color.kt +++ b/src/main/java/at/bitfire/ical4android/Css3Color.kt @@ -8,6 +8,8 @@ package at.bitfire.ical4android +import kotlin.math.sqrt + /** * Represents an RGBA COLOR value, as specified in https://tools.ietf.org/html/rfc7986#section-5.9 * @@ -175,7 +177,7 @@ enum class Css3Color(val argb: Int) { */ fun fromString(name: String) = try { - Css3Color.valueOf(name) + valueOf(name) } catch (e: IllegalArgumentException) { Constants.log.warning("Unknown color: $name") null @@ -199,7 +201,7 @@ enum class Css3Color(val argb: Int) { val deltaB = (rgb and 0xFF) - (cssColor and 0xFF) val deltaR2 = deltaR*deltaR val deltaG2 = deltaG*deltaG - Math.sqrt(2.0*deltaR2 + 4.0*deltaG2 + 3.0*deltaB*deltaB + (r*(deltaR2 - deltaG2))/256.0) + sqrt(2.0*deltaR2 + 4.0*deltaG2 + 3.0*deltaB*deltaB + (r*(deltaR2 - deltaG2))/256.0) } val idx = distance.withIndex().minBy { it.value }!!.index return values()[idx] diff --git a/src/main/java/at/bitfire/ical4android/ICalendar.kt b/src/main/java/at/bitfire/ical4android/ICalendar.kt index ee5796c..3169211 100644 --- a/src/main/java/at/bitfire/ical4android/ICalendar.kt +++ b/src/main/java/at/bitfire/ical4android/ICalendar.kt @@ -92,7 +92,7 @@ open class ICalendar { } // remove TZURL - tz.properties.filter { it is TzUrl }.forEach { + tz.properties.filterIsInstance().forEach { tz.properties.remove(it) } } diff --git a/src/main/java/at/bitfire/ical4android/TaskProvider.kt b/src/main/java/at/bitfire/ical4android/TaskProvider.kt index 0a21dcd..55bf980 100644 --- a/src/main/java/at/bitfire/ical4android/TaskProvider.kt +++ b/src/main/java/at/bitfire/ical4android/TaskProvider.kt @@ -49,7 +49,7 @@ class TaskProvider private constructor( * @throws [ProviderTooOldException] if the tasks provider is installed, but doesn't meet the minimum version requirement */ @SuppressLint("Recycle") - fun acquire(context: Context, name: TaskProvider.ProviderName): TaskProvider? { + fun acquire(context: Context, name: ProviderName): TaskProvider? { return try { checkVersion(context, name) -- GitLab From b1d363d30fb9521470200156ee8ca9a277e5cdfe Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Thu, 7 Nov 2019 18:52:50 +0100 Subject: [PATCH 32/58] Use headless emulator from new repo for testing --- .gitlab-ci.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 27e2949..ea47e0e 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -1,4 +1,5 @@ -image: registry.gitlab.com/bitfireat/davx5-ose:latest +# https://gitlab.com/bitfireAT/docker-android-emulator +image: registry.gitlab.com/bitfireat/docker-android-emulator:latest before_script: - export GRADLE_USER_HOME=`pwd`/.gradle; chmod +x gradlew @@ -9,7 +10,7 @@ cache: test: script: - - (cd /sdk/emulator; ./emulator @test -no-audio -no-window & wait-for-emulator.sh) + - start-emulator.sh - adb install src/androidTest/resources/org.dmfs.tasks_6880.apk - ./gradlew check connectedCheck artifacts: -- GitLab From 55d4e98f1db18872bcff1e1965deaefa3cdc6107 Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Sat, 9 Nov 2019 12:31:42 +0100 Subject: [PATCH 33/58] Make testing working again (include ancient Groovy version for testing) --- build.gradle | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/build.gradle b/build.gradle index 95f4864..39fb685 100644 --- a/build.gradle +++ b/build.gradle @@ -65,5 +65,10 @@ dependencies { androidTestImplementation 'androidx.test:runner:1.2.0' androidTestImplementation 'androidx.test:rules:1.2.0' + // This very old Groovy version is not actually used, but it's needed + // so that ical4j doesn't crash when testing: https://github.com/ical4j/ical4j/issues/315 + //noinspection GradleDependency + androidTestImplementation 'org.codehaus.groovy:groovy:2.2.2' + testImplementation 'junit:junit:4.12' } -- GitLab From fd15efa7dcf1a55af775da20611522ae72459a47 Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Sat, 9 Nov 2019 10:49:15 +0100 Subject: [PATCH 34/58] Task: handle alarms; iCalendar generation: minor refactoring --- .../java/at/bitfire/ical4android/Event.kt | 10 ++--- src/main/java/at/bitfire/ical4android/Task.kt | 37 ++++++++++++------- 2 files changed, 26 insertions(+), 21 deletions(-) diff --git a/src/main/java/at/bitfire/ical4android/Event.kt b/src/main/java/at/bitfire/ical4android/Event.kt index 4a7ab9d..b915798 100644 --- a/src/main/java/at/bitfire/ical4android/Event.kt +++ b/src/main/java/at/bitfire/ical4android/Event.kt @@ -11,9 +11,8 @@ package at.bitfire.ical4android import net.fortuna.ical4j.data.CalendarBuilder import net.fortuna.ical4j.data.CalendarOutputter import net.fortuna.ical4j.data.ParserException +import net.fortuna.ical4j.model.* import net.fortuna.ical4j.model.Calendar -import net.fortuna.ical4j.model.Component -import net.fortuna.ical4j.model.Property import net.fortuna.ical4j.model.TimeZone import net.fortuna.ical4j.model.component.VAlarm import net.fortuna.ical4j.model.component.VEvent @@ -253,9 +252,7 @@ class Event: ICalendar() { * @return generated VEvent */ private fun toVEvent(): VEvent { - val event = VEvent() - val props = event.properties - + val props = PropertyList() props += Uid(uid) recurrenceId?.let { props += it } sequence?.let { if (it != 0) props += Sequence(it) } @@ -286,8 +283,7 @@ class Event: ICalendar() { lastModified?.let { props += it } - event.alarms.addAll(alarms) - return event + return VEvent(props, ComponentList(alarms)) } diff --git a/src/main/java/at/bitfire/ical4android/Task.kt b/src/main/java/at/bitfire/ical4android/Task.kt index 1ceb39f..a3e7fd4 100644 --- a/src/main/java/at/bitfire/ical4android/Task.kt +++ b/src/main/java/at/bitfire/ical4android/Task.kt @@ -15,6 +15,8 @@ import net.fortuna.ical4j.data.ParserException import net.fortuna.ical4j.model.* import net.fortuna.ical4j.model.Calendar import net.fortuna.ical4j.model.TimeZone +import net.fortuna.ical4j.model.component.CalendarComponent +import net.fortuna.ical4j.model.component.VAlarm import net.fortuna.ical4j.model.component.VToDo import net.fortuna.ical4j.model.property.* import java.io.IOException @@ -51,6 +53,7 @@ class Task: ICalendar() { val rDates = LinkedList() val exDates = LinkedList() + val alarms = LinkedList() val categories = LinkedList() val unknownProperties = LinkedList() @@ -119,6 +122,8 @@ class Task: ICalendar() { else -> t.unknownProperties += prop } + t.alarms.addAll(todo.alarms) + // there seem to be many invalid tasks out there because of some defect clients, // do some validation val dtStart = t.dtStart @@ -135,15 +140,8 @@ class Task: ICalendar() { fun write(os: OutputStream) { - val ical = Calendar() - ical.properties += Version.VERSION_2_0 - ical.properties += prodId - - val todo = VToDo() - ical.components += todo - val props = todo.properties - - uid?.let { props += Uid(it) } + val props = PropertyList() + uid?.let { props += Uid(uid) } sequence?.let { if (it != 0) props += Sequence(sequence as Int) } createdAt?.let { props += Created(DateTime(it)) } @@ -172,6 +170,11 @@ class Task: ICalendar() { rDates.forEach { props += it } exDates.forEach { props += it } + if (categories.isNotEmpty()) + props += Categories(TextList(categories.toTypedArray())) + + props.addAll(unknownProperties) + // remember used time zones val usedTimeZones = HashSet() due?.let { @@ -189,14 +192,20 @@ class Task: ICalendar() { } percentComplete?.let { props += PercentComplete(it) } - if (categories.isNotEmpty()) - props += Categories(TextList(categories.toTypedArray())) + // generate VTODO + val iCalProps = PropertyList(2) + iCalProps += Version.VERSION_2_0 + iCalProps += prodId - props.addAll(unknownProperties) + val vTodo = VToDo(props) + if (alarms.isNotEmpty()) + vTodo.alarms.addAll(alarms) - // add VTIMEZONE components - usedTimeZones.forEach { ical.components += it.vTimeZone } + val iCalComponents = ComponentList(2) + iCalComponents.add(vTodo) + iCalComponents.addAll(usedTimeZones.map { it.vTimeZone }) + val ical = Calendar(iCalProps, iCalComponents) CalendarOutputter(false).output(ical, os) } -- GitLab From 100d49cff21363c4992de659178456481d1be95b Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Sat, 9 Nov 2019 12:38:40 +0100 Subject: [PATCH 35/58] Save/restore task alarms to/from OpenTasks provider --- .../at/bitfire/ical4android/AndroidEvent.kt | 14 +-- .../at/bitfire/ical4android/AndroidTask.kt | 92 ++++++++++++++++--- .../java/at/bitfire/ical4android/MiscUtils.kt | 8 +- 3 files changed, 91 insertions(+), 23 deletions(-) diff --git a/src/main/java/at/bitfire/ical4android/AndroidEvent.kt b/src/main/java/at/bitfire/ical4android/AndroidEvent.kt index 6936593..e7a8ef9 100644 --- a/src/main/java/at/bitfire/ical4android/AndroidEvent.kt +++ b/src/main/java/at/bitfire/ical4android/AndroidEvent.kt @@ -141,10 +141,8 @@ abstract class AndroidEvent( * @param row values of an [Events] row, as returned by the calendar provider */ protected open fun populateEvent(row: ContentValues) { - val event = requireNotNull(event) - Constants.log.log(Level.FINE, "Read event entity from calender provider", row) - MiscUtils.removeEmptyStrings(row) + val event = requireNotNull(event) event.summary = row.getAsString(Events.TITLE) event.location = row.getAsString(Events.EVENT_LOCATION) @@ -307,15 +305,12 @@ abstract class AndroidEvent( protected open fun populateReminder(row: ContentValues) { Constants.log.log(Level.FINE, "Read event reminder from calender provider", row) - val event = requireNotNull(event) + val alarm = VAlarm(Dur(0, 0, -row.getAsInteger(Reminders.MINUTES), 0)) val props = alarm.properties props += when (row.getAsInteger(Reminders.METHOD)) { - Reminders.METHOD_ALARM, - Reminders.METHOD_ALERT -> - Action.DISPLAY Reminders.METHOD_EMAIL, Reminders.METHOD_SMS -> Action.EMAIL @@ -359,7 +354,7 @@ abstract class AndroidEvent( null, Events.ORIGINAL_ID + "=?", arrayOf(id.toString()), null)?.use { c -> while (c.moveToNext()) { - val values = c.toValues() + val values = c.toValues(true) try { val exception = calendar.eventFactory.fromProvider(calendar, values) @@ -626,8 +621,7 @@ abstract class AndroidEvent( protected open fun insertReminder(batch: BatchOperation, idxEvent: Int, alarm: VAlarm) { val builder = ContentProviderOperation.newInsert(calendar.syncAdapterURI(Reminders.CONTENT_URI)) - val action = alarm.action - val method = when (action?.value) { + val method = when (alarm.action?.value?.toUpperCase(Locale.US)) { Action.DISPLAY.value, Action.AUDIO.value -> Reminders.METHOD_ALERT Action.EMAIL.value -> Reminders.METHOD_EMAIL diff --git a/src/main/java/at/bitfire/ical4android/AndroidTask.kt b/src/main/java/at/bitfire/ical4android/AndroidTask.kt index 3f102c8..8e30c07 100644 --- a/src/main/java/at/bitfire/ical4android/AndroidTask.kt +++ b/src/main/java/at/bitfire/ical4android/AndroidTask.kt @@ -15,17 +15,21 @@ import android.content.ContentValues import android.net.Uri import android.os.RemoteException import at.bitfire.ical4android.MiscUtils.CursorHelper.toValues +import net.fortuna.ical4j.model.* import net.fortuna.ical4j.model.Date -import net.fortuna.ical4j.model.DateTime -import net.fortuna.ical4j.model.Dur +import net.fortuna.ical4j.model.Property +import net.fortuna.ical4j.model.component.VAlarm +import net.fortuna.ical4j.model.parameter.Related import net.fortuna.ical4j.model.property.* import org.dmfs.tasks.contract.TaskContract.* import org.dmfs.tasks.contract.TaskContract.Properties +import org.dmfs.tasks.contract.TaskContract.Property.Alarm import org.dmfs.tasks.contract.TaskContract.Property.Category import java.io.FileNotFoundException import java.net.URI import java.net.URISyntaxException import java.util.* +import java.util.TimeZone import java.util.logging.Level /** @@ -71,7 +75,7 @@ abstract class AndroidTask( val client = taskList.provider.client client.query(taskSyncURI(), null, null, null, null)?.use { cursor -> if (cursor.moveToFirst()) { - val values = cursor.toValues() + val values = cursor.toValues(true) Constants.log.log(Level.FINER, "Found task", values) populateTask(values) @@ -81,7 +85,7 @@ abstract class AndroidTask( "${Properties.TASK_ID}=?", arrayOf(id.toString()), null)?.use { propCursor -> while (propCursor.moveToNext()) { - val propValues = propCursor.toValues() + val propValues = propCursor.toValues(true) Constants.log.log(Level.FINER, "Found property", propValues) populateProperty(propValues) } @@ -96,8 +100,6 @@ abstract class AndroidTask( protected open fun populateTask(values: ContentValues) { val task = requireNotNull(task) - MiscUtils.removeEmptyStrings(values) - task.uid = values.getAsString(Tasks._UID) task.sequence = values.getAsInteger(Tasks.SYNC_VERSION) task.summary = values.getAsString(Tasks.TITLE) @@ -177,16 +179,47 @@ abstract class AndroidTask( values.getAsString(Tasks.RRULE)?.let { task.rRule = RRule(it) } } - protected open fun populateProperty(values: ContentValues) { + protected open fun populateProperty(row: ContentValues) { val task = requireNotNull(task) - when (val type = values.getAsString(Properties.MIMETYPE)) { + when (val type = row.getAsString(Properties.MIMETYPE)) { + Alarm.CONTENT_ITEM_TYPE -> + populateAlarm(row) Category.CONTENT_ITEM_TYPE -> - task.categories += values.getAsString(Category.CATEGORY_NAME) + task.categories += row.getAsString(Category.CATEGORY_NAME) else -> Constants.log.warning("Found unknown property of type $type") } } + protected open fun populateAlarm(row: ContentValues) { + Constants.log.log(Level.FINE, "Read task reminder from tasks provider", row) + val task = requireNotNull(task) + val props = PropertyList() + + val trigger = Trigger(Dur(0, 0, -row.getAsInteger(Alarm.MINUTES_BEFORE), 0)) + when (row.getAsInteger(Alarm.REFERENCE)) { + Alarm.ALARM_REFERENCE_START_DATE -> + trigger.parameters.add(Related.START) + Alarm.ALARM_REFERENCE_DUE_DATE -> + trigger.parameters.add(Related.END) + } + props += trigger + + props += when (row.getAsInteger(Alarm.ALARM_TYPE)) { + Alarm.ALARM_TYPE_EMAIL -> + Action.EMAIL + Alarm.ALARM_TYPE_SOUND -> + Action.AUDIO + else -> + // show alarm by default + Action.DISPLAY + } + + props += Description(row.getAsString(Alarm.MESSAGE) ?: task.summary) + + task.alarms += VAlarm(props) + } + fun add(): Uri { val batch = BatchOperation(taskList.provider.client) @@ -224,10 +257,45 @@ abstract class AndroidTask( } private fun insertProperties(batch: BatchOperation) { - val task = requireNotNull(task) + insertAlarms(batch) + insertCategories(batch) + } + + private fun insertAlarms(batch: BatchOperation) { + for (alarm in requireNotNull(task).alarms) { + val alarmRef = when (alarm.trigger.getParameter(Parameter.RELATED)) { + Related.END -> + Alarm.ALARM_REFERENCE_DUE_DATE + else /* Related.START is the default value */ -> + Alarm.ALARM_REFERENCE_START_DATE + } + + val alarmType = when (alarm.action?.value?.toUpperCase(Locale.US)) { + Action.AUDIO.value -> + Alarm.ALARM_TYPE_SOUND + Action.DISPLAY.value -> + Alarm.ALARM_TYPE_MESSAGE + Action.EMAIL.value -> + Alarm.ALARM_TYPE_EMAIL + else -> + Alarm.ALARM_TYPE_NOTHING + } + + val builder = ContentProviderOperation.newInsert(taskList.tasksPropertiesSyncUri()) + builder .withValue(Alarm.TASK_ID, id) + .withValue(Alarm.MIMETYPE, Alarm.CONTENT_ITEM_TYPE) + .withValue(Alarm.MINUTES_BEFORE, ICalendar.alarmMinBefore(alarm)) + .withValue(Alarm.REFERENCE, alarmRef) + .withValue(Alarm.MESSAGE, alarm.description?.value ?: alarm.summary) + .withValue(Alarm.ALARM_TYPE, alarmType) + + Constants.log.log(Level.FINE, "Inserting alarm", builder.build()) + batch.enqueue(BatchOperation.Operation(builder)) + } + } - // insert categories - for (category in task.categories) { + private fun insertCategories(batch: BatchOperation) { + for (category in requireNotNull(task).categories) { val builder = ContentProviderOperation.newInsert(taskList.tasksPropertiesSyncUri()) builder .withValue(Category.TASK_ID, id) .withValue(Category.MIMETYPE, Category.CONTENT_ITEM_TYPE) diff --git a/src/main/java/at/bitfire/ical4android/MiscUtils.kt b/src/main/java/at/bitfire/ical4android/MiscUtils.kt index d3dfce5..5b004bb 100644 --- a/src/main/java/at/bitfire/ical4android/MiscUtils.kt +++ b/src/main/java/at/bitfire/ical4android/MiscUtils.kt @@ -101,11 +101,17 @@ object MiscUtils { /** * Returns the entire contents of the current row as a [ContentValues] object. + * + * @param removeEmptyRows whether rows with empty values should be removed * @return entire contents of the current row */ - fun Cursor.toValues(): ContentValues { + fun Cursor.toValues(removeEmptyRows: Boolean = false): ContentValues { val values = ContentValues(columnCount) DatabaseUtils.cursorRowToContentValues(this, values) + + if (removeEmptyRows) + removeEmptyStrings(values) + return values } -- GitLab From 9dae2365fed0829b28df2815abee452afb366ff3 Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Sat, 9 Nov 2019 12:44:29 +0100 Subject: [PATCH 36/58] Require privileged tag for Anroid tests, but allow documentation to be built by shared runner --- .gitlab-ci.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index ea47e0e..496a0e7 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -1,5 +1,4 @@ -# https://gitlab.com/bitfireAT/docker-android-emulator -image: registry.gitlab.com/bitfireat/docker-android-emulator:latest +image: openjdk:8-jdk-slim before_script: - export GRADLE_USER_HOME=`pwd`/.gradle; chmod +x gradlew @@ -9,6 +8,9 @@ cache: - .gradle/ test: + image: registry.gitlab.com/bitfireat/docker-android-emulator:latest + tags: + - privileged script: - start-emulator.sh - adb install src/androidTest/resources/org.dmfs.tasks_6880.apk -- GitLab From 237995770d8c00bdd847c37fc9efcd0a6e58a575 Mon Sep 17 00:00:00 2001 From: Alex Baker Date: Sat, 9 Nov 2019 17:39:23 +0000 Subject: [PATCH 37/58] Exclude Uid from unknownProperties --- src/main/java/at/bitfire/ical4android/Task.kt | 2 +- src/test/java/at/bitfire/ical4android/TaskTest.kt | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/at/bitfire/ical4android/Task.kt b/src/main/java/at/bitfire/ical4android/Task.kt index a3e7fd4..b47b638 100644 --- a/src/main/java/at/bitfire/ical4android/Task.kt +++ b/src/main/java/at/bitfire/ical4android/Task.kt @@ -118,7 +118,7 @@ class Task: ICalendar() { is RDate -> t.rDates += prop is ExDate -> t.exDates += prop is Categories -> t.categories.addAll(prop.categories.toList()) - is ProdId, is DtStamp -> { /* don't save these as unknown properties */ } + is ProdId, is DtStamp, is Uid -> { /* don't save these as unknown properties */ } else -> t.unknownProperties += prop } diff --git a/src/test/java/at/bitfire/ical4android/TaskTest.kt b/src/test/java/at/bitfire/ical4android/TaskTest.kt index 01475d7..7c9aed5 100644 --- a/src/test/java/at/bitfire/ical4android/TaskTest.kt +++ b/src/test/java/at/bitfire/ical4android/TaskTest.kt @@ -87,11 +87,13 @@ class TaskTest { assertEquals(828106200000L, t.createdAt) assertEquals(840288600000L, t.lastModified) + assertTrue(t.unknownProperties.isEmpty()) t = regenerate(parseCalendar("most-fields2.ics")) assertEquals("most-fields2@example.com", t.uid) assertEquals(DtStart(DateTime("20100101T101010Z")), t.dtStart) assertEquals(Duration(Dur(4, 3, 2, 1)), t.duration) + assertTrue(t.unknownProperties.isEmpty()) } -- GitLab From df24aad5ad5fa4b7c62b771e4302914844331068 Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Sat, 9 Nov 2019 18:54:24 +0100 Subject: [PATCH 38/58] Add contributors --- README.md | 2 +- src/main/java/at/bitfire/ical4android/Task.kt | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 9022621..0c370c6 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ Email: [play@bitfire.at](mailto:play@bitfire.at) (do not use this) ## License -Copyright (C) bitfire web engineering (Ricki Hirner, Bernhard Stockmann). +Copyright (C) bitfire web engineering (Ricki Hirner, Bernhard Stockmann) and contributors. This program comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it under the conditions of the [GNU GPL v3](https://www.gnu.org/licenses/gpl-3.0.html). diff --git a/src/main/java/at/bitfire/ical4android/Task.kt b/src/main/java/at/bitfire/ical4android/Task.kt index b47b638..e2bc5f6 100644 --- a/src/main/java/at/bitfire/ical4android/Task.kt +++ b/src/main/java/at/bitfire/ical4android/Task.kt @@ -1,9 +1,11 @@ /* - * Copyright © Ricki Hirner (bitfire web engineering). + * Copyright © Ricki Hirner and contributors (bitfire web engineering). * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html + * + * Contributors: Alex Baker */ package at.bitfire.ical4android -- GitLab From 4c871398d8628e1f173f88d8375ee30a7bd4697a Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Sat, 9 Nov 2019 19:18:10 +0100 Subject: [PATCH 39/58] Update dokka --- .gitlab-ci.yml | 3 +-- build.gradle | 6 +++--- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 496a0e7..8c6e58e 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -1,4 +1,4 @@ -image: openjdk:8-jdk-slim +image: registry.gitlab.com/bitfireat/docker-android-emulator:latest before_script: - export GRADLE_USER_HOME=`pwd`/.gradle; chmod +x gradlew @@ -8,7 +8,6 @@ cache: - .gradle/ test: - image: registry.gitlab.com/bitfireat/docker-android-emulator:latest tags: - privileged script: diff --git a/build.gradle b/build.gradle index 39fb685..caeebdf 100644 --- a/build.gradle +++ b/build.gradle @@ -2,7 +2,7 @@ buildscript { ext.versions = [ kotlin: '1.3.50', - dokka: '0.9.18', + dokka: '0.10.0', ical4j: '2.2.6' ] @@ -14,7 +14,7 @@ buildscript { dependencies { classpath 'com.android.tools.build:gradle:3.5.2' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${versions.kotlin}" - classpath "org.jetbrains.dokka:dokka-android-gradle-plugin:${versions.dokka}" + classpath "org.jetbrains.dokka:dokka-gradle-plugin:${versions.dokka}" } } @@ -25,7 +25,7 @@ repositories { apply plugin: 'com.android.library' apply plugin: 'kotlin-android' -apply plugin: 'org.jetbrains.dokka-android' +apply plugin: 'org.jetbrains.dokka' android { compileSdkVersion 29 -- GitLab From 1925b714c247468552bac5a05f67f6e4ad8e95f4 Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Sun, 10 Nov 2019 23:48:39 +0100 Subject: [PATCH 40/58] Tasks: support saving/restoring unknown properties --- .../bitfire/ical4android/AndroidEventTest.kt | 8 ++ .../bitfire/ical4android/AndroidTaskTest.kt | 7 ++ .../ical4android/UnknownPropertyTest.kt | 14 ++-- .../at/bitfire/ical4android/AndroidEvent.kt | 82 +++---------------- .../at/bitfire/ical4android/AndroidTask.kt | 49 +++++++---- .../bitfire/ical4android/UnknownProperty.kt | 80 ++++++++++++++++++ .../java/at/bitfire/ical4android/EventTest.kt | 7 +- .../java/at/bitfire/ical4android/TaskTest.kt | 9 +- src/test/resources/events/utf8.ics | 1 + src/test/resources/tasks/most-fields1.ics | 2 + 10 files changed, 165 insertions(+), 94 deletions(-) create mode 100644 src/main/java/at/bitfire/ical4android/UnknownProperty.kt diff --git a/src/androidTest/java/at/bitfire/ical4android/AndroidEventTest.kt b/src/androidTest/java/at/bitfire/ical4android/AndroidEventTest.kt index 80bf296..f0fa8a9 100644 --- a/src/androidTest/java/at/bitfire/ical4android/AndroidEventTest.kt +++ b/src/androidTest/java/at/bitfire/ical4android/AndroidEventTest.kt @@ -24,6 +24,7 @@ import at.bitfire.ical4android.impl.TestEvent import net.fortuna.ical4j.model.Date import net.fortuna.ical4j.model.DateList import net.fortuna.ical4j.model.Dur +import net.fortuna.ical4j.model.Property import net.fortuna.ical4j.model.component.VAlarm import net.fortuna.ical4j.model.parameter.Value import net.fortuna.ical4j.model.property.* @@ -115,6 +116,10 @@ class AndroidEventTest { // add EXDATE event.exDates += ExDate(DateList("20150502T120000", Value.DATE_TIME, tzVienna)) + // add special properties + event.unknownProperties.add(Categories("CAT1,CAT2")) + event.unknownProperties.add(XProperty("X-NAME", "X-Value")) + // add to calendar val uri = TestEvent(calendar, event).add() assertNotNull(uri) @@ -172,6 +177,9 @@ class AndroidEventTest { // compare EXDATE assertEquals(1, event2.exDates.size) assertEquals(event.exDates.first, event2.exDates.first) + + // compare unknown properties + assertArrayEquals(event.unknownProperties.toArray(), event2.unknownProperties.toArray()) } finally { testEvent.delete() } diff --git a/src/androidTest/java/at/bitfire/ical4android/AndroidTaskTest.kt b/src/androidTest/java/at/bitfire/ical4android/AndroidTaskTest.kt index 37d8b53..1b74c30 100644 --- a/src/androidTest/java/at/bitfire/ical4android/AndroidTaskTest.kt +++ b/src/androidTest/java/at/bitfire/ical4android/AndroidTaskTest.kt @@ -20,6 +20,7 @@ import net.fortuna.ical4j.model.TimeZone import net.fortuna.ical4j.model.property.DtStart import net.fortuna.ical4j.model.property.Due import net.fortuna.ical4j.model.property.Organizer +import net.fortuna.ical4j.model.property.XProperty import org.dmfs.tasks.contract.TaskContract import org.junit.After import org.junit.Assert.* @@ -77,6 +78,10 @@ class AndroidTaskTest { task.organizer = Organizer("mailto:organizer@example.com") assertFalse(task.isAllDay()) + // extended properties + task.categories.addAll(arrayOf("Cat1", "Cat2")) + task.unknownProperties += XProperty("X-UNKNOWN-PROP", "Unknown Value") + // add to task list val uri = TestTask(taskList!!, task).add() assertNotNull("Couldn't add task", uri) @@ -93,6 +98,8 @@ class AndroidTaskTest { assertEquals(task.description, task2.description) assertEquals(task.location, task2.location) assertEquals(task.dtStart, task2.dtStart) + assertEquals(task.categories, task2.categories) + assertEquals(task.unknownProperties, task2.unknownProperties) } finally { testTask.delete() } diff --git a/src/androidTest/java/at/bitfire/ical4android/UnknownPropertyTest.kt b/src/androidTest/java/at/bitfire/ical4android/UnknownPropertyTest.kt index 04772a8..b116f5d 100644 --- a/src/androidTest/java/at/bitfire/ical4android/UnknownPropertyTest.kt +++ b/src/androidTest/java/at/bitfire/ical4android/UnknownPropertyTest.kt @@ -14,8 +14,8 @@ class UnknownPropertyTest { @Test @SmallTest - fun testFromExtendedProperty() { - val prop = AndroidEvent.UnknownProperty.fromExtendedProperty("[ \"UID\", \"PropValue\" ]") + fun testFromJsonString() { + val prop = UnknownProperty.fromJsonString("[ \"UID\", \"PropValue\" ]") assertTrue(prop is Uid) assertEquals("UID", prop.name) assertEquals("PropValue", prop.value) @@ -23,8 +23,8 @@ class UnknownPropertyTest { @Test @SmallTest - fun testFromExtendedPropertyWithParameters() { - val prop = AndroidEvent.UnknownProperty.fromExtendedProperty("[ \"ATTENDEE\", \"PropValue\", { \"x-param1\": \"value1\", \"x-param2\": \"value2\" } ]") + fun testFromJsonStringWithParameters() { + val prop = UnknownProperty.fromJsonString("[ \"ATTENDEE\", \"PropValue\", { \"x-param1\": \"value1\", \"x-param2\": \"value2\" } ]") assertTrue(prop is Attendee) assertEquals("ATTENDEE", prop.name) assertEquals("PropValue", prop.value) @@ -35,14 +35,14 @@ class UnknownPropertyTest { @Test(expected = JSONException::class) @SmallTest - fun testFromInvalidExtendedProperty() { - AndroidEvent.UnknownProperty.fromExtendedProperty("This isn't JSON") + fun testFromInvalidJsonString() { + UnknownProperty.fromJsonString("This isn't JSON") } @Test @SmallTest - fun testToExtendedProperty() { + fun testToJsonString() { val attendee = Attendee("mailto:test@test.at") assertEquals( "ATTENDEE:mailto:test@test.at", diff --git a/src/main/java/at/bitfire/ical4android/AndroidEvent.kt b/src/main/java/at/bitfire/ical4android/AndroidEvent.kt index e7a8ef9..41e5e36 100644 --- a/src/main/java/at/bitfire/ical4android/AndroidEvent.kt +++ b/src/main/java/at/bitfire/ical4android/AndroidEvent.kt @@ -25,8 +25,6 @@ import net.fortuna.ical4j.model.component.VAlarm import net.fortuna.ical4j.model.parameter.* import net.fortuna.ical4j.model.property.* import net.fortuna.ical4j.util.TimeZones -import org.json.JSONArray -import org.json.JSONObject import java.io.ByteArrayInputStream import java.io.FileNotFoundException import java.io.ObjectInputStream @@ -52,13 +50,15 @@ abstract class AndroidEvent( companion object { - /** [ExtendedProperties.NAME] for unknown iCal properties */ @Deprecated("New serialization format", ReplaceWith("EXT_UNKNOWN_PROPERTY2")) const val EXT_UNKNOWN_PROPERTY = "unknown-property" + + @Deprecated("New content item MIME type", ReplaceWith("UnknownProperty.CONTENT_ITEM_TYPE")) const val EXT_UNKNOWN_PROPERTY2 = "unknown-property.v2" - const val MAX_UNKNOWN_PROPERTY_SIZE = 25000 - // not declared in ical4j Parameters class yet + /** + * EMAIL parameter name (as used for ORGANIZER). Not declared in ical4j Parameters class yet. + */ private const val PARAMETER_EMAIL = "EMAIL" } @@ -329,17 +329,15 @@ abstract class AndroidEvent( try { when (row.getAsString(ExtendedProperties.NAME)) { EXT_UNKNOWN_PROPERTY -> { - // deserialize unknown property v1 (deprecated) + // deserialize unknown property (deprecated format) val stream = ByteArrayInputStream(Base64.decode(row.getAsString(ExtendedProperties.VALUE), Base64.NO_WRAP)) ObjectInputStream(stream).use { event.unknownProperties += it.readObject() as Property } } - EXT_UNKNOWN_PROPERTY2 -> { - // deserialize unknown property v2 - event.unknownProperties += UnknownProperty.fromExtendedProperty(row.getAsString(ExtendedProperties.VALUE)) - } + EXT_UNKNOWN_PROPERTY2, UnknownProperty.CONTENT_ITEM_TYPE -> + event.unknownProperties += UnknownProperty.fromJsonString(row.getAsString(ExtendedProperties.VALUE)) } } catch(e: Exception) { Constants.log.log(Level.WARNING, "Couldn't parse extended property", e) @@ -694,14 +692,14 @@ abstract class AndroidEvent( } protected open fun insertUnknownProperty(batch: BatchOperation, idxEvent: Int, property: Property) { - if (property.value.length > MAX_UNKNOWN_PROPERTY_SIZE) { + if (property.value.length > UnknownProperty.MAX_UNKNOWN_PROPERTY_SIZE) { Constants.log.warning("Ignoring unknown property with ${property.value.length} octets (too long)") return } val builder = ContentProviderOperation.newInsert(calendar.syncAdapterURI(ExtendedProperties.CONTENT_URI)) - builder .withValue(ExtendedProperties.NAME, EXT_UNKNOWN_PROPERTY2) - .withValue(ExtendedProperties.VALUE, UnknownProperty.toExtendedProperty(property)) + .withValue(ExtendedProperties.NAME, UnknownProperty.CONTENT_ITEM_TYPE) + .withValue(ExtendedProperties.VALUE, UnknownProperty.toJsonString(property)) batch.enqueue(BatchOperation.Operation(builder, ExtendedProperties.EVENT_ID, idxEvent)) } @@ -735,62 +733,4 @@ abstract class AndroidEvent( override fun toString() = MiscUtils.reflectionToString(this) - /** - * Helpers to (de)serialize unknown properties as JSON to store it in an Android ExtendedProperty row. - * - * Format: `{ propertyName, propertyValue, { param1Name: param1Value, ... } }`, with the third - * array (parameters) being optional. - */ - object UnknownProperty { - - private val parameterFactory = ParameterFactoryRegistry() - private val propertyFactory = PropertyFactoryRegistry() - - /** - * Deserializes a JSON string from an ExtendedProperty value to an ical4j property. - * - * @param jsonString JSON representation of an ical4j property - * @return ical4j property, generated from [jsonString] - * @throws org.json.JSONException when the input value can't be parsed - */ - fun fromExtendedProperty(jsonString: String): Property { - val json = JSONArray(jsonString) - val name = json.getString(0) - val value = json.getString(1) - - val params = ParameterList() - json.optJSONObject(2)?.let { jsonParams -> - for (paramName in jsonParams.keys()) - params.add(parameterFactory.createParameter( - paramName, - jsonParams.getString(paramName) - )) - } - - return propertyFactory.createProperty(name, params, value) - } - - /** - * Serializes an ical4j property to a JSON string that can be stored in an ExtendedProperty. - * - * @param prop property to serialize as JSON - * @return JSON representation of [prop] - */ - fun toExtendedProperty(prop: Property): String { - val json = JSONArray() - json.put(prop.name) - json.put(prop.value) - - if (!prop.parameters.isEmpty) { - val jsonParams = JSONObject() - for (param in prop.parameters) - jsonParams.put(param.name, param.value) - json.put(jsonParams) - } - - return json.toString() - } - - } - } diff --git a/src/main/java/at/bitfire/ical4android/AndroidTask.kt b/src/main/java/at/bitfire/ical4android/AndroidTask.kt index 8e30c07..24b0781 100644 --- a/src/main/java/at/bitfire/ical4android/AndroidTask.kt +++ b/src/main/java/at/bitfire/ical4android/AndroidTask.kt @@ -46,6 +46,10 @@ abstract class AndroidTask( val taskList: AndroidTaskList ) { + companion object { + const val UNKNOWN_PROPERTY_DATA = Properties.DATA0 + } + var id: Long? = null @@ -84,11 +88,8 @@ abstract class AndroidTask( client.query(taskList.tasksPropertiesSyncUri(), null, "${Properties.TASK_ID}=?", arrayOf(id.toString()), null)?.use { propCursor -> - while (propCursor.moveToNext()) { - val propValues = propCursor.toValues(true) - Constants.log.log(Level.FINER, "Found property", propValues) - populateProperty(propValues) - } + while (propCursor.moveToNext()) + populateProperty(propCursor.toValues(true)) } return task @@ -180,12 +181,16 @@ abstract class AndroidTask( } protected open fun populateProperty(row: ContentValues) { + Constants.log.log(Level.FINER, "Found property", row) + val task = requireNotNull(task) when (val type = row.getAsString(Properties.MIMETYPE)) { Alarm.CONTENT_ITEM_TYPE -> populateAlarm(row) Category.CONTENT_ITEM_TYPE -> task.categories += row.getAsString(Category.CATEGORY_NAME) + UnknownProperty.CONTENT_ITEM_TYPE -> + task.unknownProperties += UnknownProperty.fromJsonString(row.getAsString(UNKNOWN_PROPERTY_DATA)) else -> Constants.log.warning("Found unknown property of type $type") } @@ -259,6 +264,7 @@ abstract class AndroidTask( private fun insertProperties(batch: BatchOperation) { insertAlarms(batch) insertCategories(batch) + insertUnknownProperties(batch) } private fun insertAlarms(batch: BatchOperation) { @@ -282,7 +288,7 @@ abstract class AndroidTask( } val builder = ContentProviderOperation.newInsert(taskList.tasksPropertiesSyncUri()) - builder .withValue(Alarm.TASK_ID, id) + .withValue(Alarm.TASK_ID, id) .withValue(Alarm.MIMETYPE, Alarm.CONTENT_ITEM_TYPE) .withValue(Alarm.MINUTES_BEFORE, ICalendar.alarmMinBefore(alarm)) .withValue(Alarm.REFERENCE, alarmRef) @@ -297,7 +303,7 @@ abstract class AndroidTask( private fun insertCategories(batch: BatchOperation) { for (category in requireNotNull(task).categories) { val builder = ContentProviderOperation.newInsert(taskList.tasksPropertiesSyncUri()) - builder .withValue(Category.TASK_ID, id) + .withValue(Category.TASK_ID, id) .withValue(Category.MIMETYPE, Category.CONTENT_ITEM_TYPE) .withValue(Category.CATEGORY_NAME, category) Constants.log.log(Level.FINE, "Inserting category", builder.build()) @@ -305,6 +311,22 @@ abstract class AndroidTask( } } + private fun insertUnknownProperties(batch: BatchOperation) { + for (property in requireNotNull(task).unknownProperties) { + if (property.value.length > UnknownProperty.MAX_UNKNOWN_PROPERTY_SIZE) { + Constants.log.warning("Ignoring unknown property with ${property.value.length} octets (too long)") + return + } + + val builder = ContentProviderOperation.newInsert(taskList.tasksPropertiesSyncUri()) + .withValue(Properties.TASK_ID, id) + .withValue(Properties.MIMETYPE, UnknownProperty.CONTENT_ITEM_TYPE) + .withValue(UNKNOWN_PROPERTY_DATA, UnknownProperty.toJsonString(property)) + Constants.log.log(Level.FINE, "Inserting unknown property", builder.build()) + batch.enqueue(BatchOperation.Operation(builder)) + } + } + fun delete(): Int { try { return taskList.provider.client.delete(taskSyncURI(), null, null) @@ -318,16 +340,15 @@ abstract class AndroidTask( builder .withValue(Tasks.LIST_ID, taskList.id) val task = requireNotNull(task) - builder - .withValue(Tasks._UID, task.uid) + builder .withValue(Tasks._UID, task.uid) .withValue(Tasks._DIRTY, 0) .withValue(Tasks.SYNC_VERSION, task.sequence) .withValue(Tasks.TITLE, task.summary) .withValue(Tasks.LOCATION, task.location) - builder .withValue(Tasks.GEO, task.geoPosition?.value) + .withValue(Tasks.GEO, task.geoPosition?.value) - builder .withValue(Tasks.DESCRIPTION, task.description) + .withValue(Tasks.DESCRIPTION, task.description) .withValue(Tasks.TASK_COLOR, task.color) .withValue(Tasks.URL, task.url) @@ -379,14 +400,14 @@ abstract class AndroidTask( builder .withValue(Tasks.CREATED, task.createdAt) .withValue(Tasks.LAST_MODIFIED, task.lastModified) - builder .withValue(Tasks.DTSTART, task.dtStart?.date?.time) + .withValue(Tasks.DTSTART, task.dtStart?.date?.time) .withValue(Tasks.DUE, task.due?.date?.time) .withValue(Tasks.DURATION, task.duration?.value) - builder .withValue(Tasks.RDATE, if (task.rDates.isEmpty()) null else DateUtils.recurrenceSetsToAndroidString(task.rDates, allDay)) + .withValue(Tasks.RDATE, if (task.rDates.isEmpty()) null else DateUtils.recurrenceSetsToAndroidString(task.rDates, allDay)) .withValue(Tasks.RRULE, task.rRule?.value) - builder .withValue(Tasks.EXDATE, if (task.exDates.isEmpty()) null else DateUtils.recurrenceSetsToAndroidString(task.exDates, allDay)) + .withValue(Tasks.EXDATE, if (task.exDates.isEmpty()) null else DateUtils.recurrenceSetsToAndroidString(task.exDates, allDay)) Constants.log.log(Level.FINE, "Built task object", builder.build()) } diff --git a/src/main/java/at/bitfire/ical4android/UnknownProperty.kt b/src/main/java/at/bitfire/ical4android/UnknownProperty.kt new file mode 100644 index 0000000..58a36f2 --- /dev/null +++ b/src/main/java/at/bitfire/ical4android/UnknownProperty.kt @@ -0,0 +1,80 @@ +package at.bitfire.ical4android + +import android.content.ContentResolver +import net.fortuna.ical4j.model.ParameterFactoryRegistry +import net.fortuna.ical4j.model.ParameterList +import net.fortuna.ical4j.model.Property +import net.fortuna.ical4j.model.PropertyFactoryRegistry +import org.json.JSONArray +import org.json.JSONObject + +/** + * Helpers to (de)serialize unknown properties as JSON to store it in an Android ExtendedProperty row. + * + * Format: `{ propertyName, propertyValue, { param1Name: param1Value, ... } }`, with the third + * array (parameters) being optional. + */ +object UnknownProperty { + + /** + * Use this value for [android.provider.CalendarContract.ExtendedProperties.NAME] and + * [org.dmfs.tasks.contract.TaskContract.Properties.MIMETYPE]. + */ + const val CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/vnd.ical4android.unknown-property" + + /** + * Recommended maximum size of properties for serialization. Won't be enforced by this + * class (should be checked by caller). + */ + const val MAX_UNKNOWN_PROPERTY_SIZE = 25000 + + + private val parameterFactory = ParameterFactoryRegistry() + private val propertyFactory = PropertyFactoryRegistry() + + /** + * Deserializes a JSON string from an ExtendedProperty value to an ical4j property. + * + * @param jsonString JSON representation of an ical4j property + * @return ical4j property, generated from [jsonString] + * @throws org.json.JSONException when the input value can't be parsed + */ + fun fromJsonString(jsonString: String): Property { + val json = JSONArray(jsonString) + val name = json.getString(0) + val value = json.getString(1) + + val params = ParameterList() + json.optJSONObject(2)?.let { jsonParams -> + for (paramName in jsonParams.keys()) + params.add(parameterFactory.createParameter( + paramName, + jsonParams.getString(paramName) + )) + } + + return propertyFactory.createProperty(name, params, value) + } + + /** + * Serializes an ical4j property to a JSON string that can be stored in an ExtendedProperty. + * + * @param prop property to serialize as JSON + * @return JSON representation of [prop] + */ + fun toJsonString(prop: Property): String { + val json = JSONArray() + json.put(prop.name) + json.put(prop.value) + + if (!prop.parameters.isEmpty) { + val jsonParams = JSONObject() + for (param in prop.parameters) + jsonParams.put(param.name, param.value) + json.put(jsonParams) + } + + return json.toString() + } + +} \ No newline at end of file diff --git a/src/test/java/at/bitfire/ical4android/EventTest.kt b/src/test/java/at/bitfire/ical4android/EventTest.kt index 8d147f6..f1b8d5c 100644 --- a/src/test/java/at/bitfire/ical4android/EventTest.kt +++ b/src/test/java/at/bitfire/ical4android/EventTest.kt @@ -71,7 +71,7 @@ class EventTest { } @Test - fun testParseAndWrite() { + fun testParse() { val event = parseCalendar("utf8.ics").first() assertEquals("utf8@ical4android.EventTest", event.uid) assertEquals("© äö — üß", event.summary) @@ -79,6 +79,11 @@ class EventTest { assertEquals("中华人民共和国", event.location) assertEquals(Css3Color.aliceblue, event.color) assertEquals("cyrus@example.com", event.attendees.first.parameters.getParameter("EMAIL").value) + + val unknown = event.unknownProperties.first + assertEquals("X-UNKNOWN-PROP", unknown.name) + assertEquals("xxx", unknown.getParameter("param1").value) + assertEquals("Unknown Value", unknown.value) } @Test diff --git a/src/test/java/at/bitfire/ical4android/TaskTest.kt b/src/test/java/at/bitfire/ical4android/TaskTest.kt index 7c9aed5..1359513 100644 --- a/src/test/java/at/bitfire/ical4android/TaskTest.kt +++ b/src/test/java/at/bitfire/ical4android/TaskTest.kt @@ -87,8 +87,15 @@ class TaskTest { assertEquals(828106200000L, t.createdAt) assertEquals(840288600000L, t.lastModified) - assertTrue(t.unknownProperties.isEmpty()) + assertArrayEquals(arrayOf("Test","Sample"), t.categories.toArray()) + + val unknown = t.unknownProperties.first + assertEquals("X-UNKNOWN-PROP", unknown.name) + assertEquals("xxx", unknown.getParameter("param1").value) + assertEquals("Unknown Value", unknown.value) + + // other file t = regenerate(parseCalendar("most-fields2.ics")) assertEquals("most-fields2@example.com", t.uid) assertEquals(DtStart(DateTime("20100101T101010Z")), t.dtStart) diff --git a/src/test/resources/events/utf8.ics b/src/test/resources/events/utf8.ics index 11644b6..87171a9 100644 --- a/src/test/resources/events/utf8.ics +++ b/src/test/resources/events/utf8.ics @@ -8,6 +8,7 @@ DESCRIPTION:Test Description LOCATION:中华人民共和国 COLOR:aliceblue ATTENDEE;CN=Cyrus Daboo;EMAIL=cyrus@example.com:mailto:opaque-token-1234@example.com +X-UNKNOWN-PROP;param1=xxx:Unknown Value DTSTART:20131009T170000T DTEND:20131009T180000T END:VEVENT diff --git a/src/test/resources/tasks/most-fields1.ics b/src/test/resources/tasks/most-fields1.ics index fdf002f..85613d9 100644 --- a/src/test/resources/tasks/most-fields1.ics +++ b/src/test/resources/tasks/most-fields1.ics @@ -18,11 +18,13 @@ STATUS:IN-PROCESS PERCENT-COMPLETE:25 DTSTART;VALUE=DATE:20100101 DUE;VALUE=DATE:20101001 +CATEGORIES:Test,Sample RRULE:FREQ=YEARLY;INTERVAL=2 EXDATE;VALUE=DATE:20120101 EXDATE;VALUE=DATE:20140101,20180101 RDATE;VALUE=DATE:20100310,20100315 RDATE;VALUE=DATE:20100810 +X-UNKNOWN-PROP;param1=xxx:Unknown Value CREATED:19960329T133000Z LAST-MODIFIED:19960817T133000Z END:VTODO -- GitLab From 1caba7515c4308a1945439b9862a1d6b5e5b3896 Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Mon, 11 Nov 2019 00:09:31 +0100 Subject: [PATCH 41/58] Remove useless applicationName --- src/main/AndroidManifest.xml | 2 +- src/main/res/values/strings.xml | 15 --------------- 2 files changed, 1 insertion(+), 16 deletions(-) delete mode 100644 src/main/res/values/strings.xml diff --git a/src/main/AndroidManifest.xml b/src/main/AndroidManifest.xml index 3f82687..fd3b851 100644 --- a/src/main/AndroidManifest.xml +++ b/src/main/AndroidManifest.xml @@ -19,6 +19,6 @@ - + diff --git a/src/main/res/values/strings.xml b/src/main/res/values/strings.xml deleted file mode 100644 index 59c48ce..0000000 --- a/src/main/res/values/strings.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - iCal4Android - -- GitLab From 232477eca62684dfd35fe8ff20d505991fa21b30 Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Tue, 12 Nov 2019 13:09:48 +0100 Subject: [PATCH 42/58] Dokka: add source and JDK links --- build.gradle | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/build.gradle b/build.gradle index caeebdf..4b41001 100644 --- a/build.gradle +++ b/build.gradle @@ -52,6 +52,14 @@ android { sourceSets { main.java.srcDirs = [ "src/main/java", "opentasks-contract/src/main/java" ] } + + dokka.configuration { + sourceLink { + url = "https://gitlab.com/bitfireAT/ical4android/tree/master/" + lineSuffix = "#L" + } + jdkVersion = 7 + } } dependencies { -- GitLab From 7b5dfda1e9278a8728ee7f33b1ab4f089bec22ec Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Tue, 12 Nov 2019 13:06:25 +0100 Subject: [PATCH 43/58] Full support for RELATED-TO --- .../bitfire/ical4android/AndroidEventTest.kt | 1 - .../ical4android/AndroidTaskListTest.kt | 100 ++++++++++++++---- .../bitfire/ical4android/AndroidTaskTest.kt | 14 ++- .../at/bitfire/ical4android/AndroidTask.kt | 98 +++++++++++++++-- .../bitfire/ical4android/AndroidTaskList.kt | 57 +++++++++- src/main/java/at/bitfire/ical4android/Task.kt | 9 +- .../java/at/bitfire/ical4android/TaskTest.kt | 10 +- src/test/resources/tasks/most-fields1.ics | 1 + 8 files changed, 248 insertions(+), 42 deletions(-) diff --git a/src/androidTest/java/at/bitfire/ical4android/AndroidEventTest.kt b/src/androidTest/java/at/bitfire/ical4android/AndroidEventTest.kt index f0fa8a9..8bab8c6 100644 --- a/src/androidTest/java/at/bitfire/ical4android/AndroidEventTest.kt +++ b/src/androidTest/java/at/bitfire/ical4android/AndroidEventTest.kt @@ -24,7 +24,6 @@ import at.bitfire.ical4android.impl.TestEvent import net.fortuna.ical4j.model.Date import net.fortuna.ical4j.model.DateList import net.fortuna.ical4j.model.Dur -import net.fortuna.ical4j.model.Property import net.fortuna.ical4j.model.component.VAlarm import net.fortuna.ical4j.model.parameter.Value import net.fortuna.ical4j.model.property.* diff --git a/src/androidTest/java/at/bitfire/ical4android/AndroidTaskListTest.kt b/src/androidTest/java/at/bitfire/ical4android/AndroidTaskListTest.kt index ce04501..871a48b 100644 --- a/src/androidTest/java/at/bitfire/ical4android/AndroidTaskListTest.kt +++ b/src/androidTest/java/at/bitfire/ical4android/AndroidTaskListTest.kt @@ -11,13 +11,16 @@ package at.bitfire.ical4android import android.accounts.Account import android.content.ContentUris import android.content.ContentValues -import androidx.test.filters.MediumTest +import android.database.DatabaseUtils import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation +import at.bitfire.ical4android.impl.TestTask import at.bitfire.ical4android.impl.TestTaskList +import net.fortuna.ical4j.model.property.RelatedTo import org.dmfs.tasks.contract.TaskContract +import org.dmfs.tasks.contract.TaskContract.Properties +import org.dmfs.tasks.contract.TaskContract.Property.Relation import org.junit.After -import org.junit.Assert.assertEquals -import org.junit.Assert.assertNotNull +import org.junit.Assert.* import org.junit.Assume.assumeNotNull import org.junit.Before import org.junit.Test @@ -43,35 +46,92 @@ class AndroidTaskListTest { provider?.close() } - - @MediumTest - @Test - fun testManageTaskLists() { - // create task list + private fun createTaskList(): TestTaskList { val info = ContentValues() info.put(TaskContract.TaskLists.LIST_NAME, "Test Task List") info.put(TaskContract.TaskLists.LIST_COLOR, 0xffff0000) info.put(TaskContract.TaskLists.OWNER, "test@example.com") info.put(TaskContract.TaskLists.SYNC_ENABLED, 1) info.put(TaskContract.TaskLists.VISIBLE, 1) + val uri = AndroidTaskList.create(testAccount, provider!!, info) assertNotNull(uri) - // query task list - val taskList = AndroidTaskList.findByID(testAccount, provider!!, TestTaskList.Factory, ContentUris.parseId(uri)) - assertNotNull(taskList) + return AndroidTaskList.findByID(testAccount, provider!!, TestTaskList.Factory, ContentUris.parseId(uri)) + } + + + @Test + fun testManageTaskLists() { + val taskList = createTaskList() + + try { + // sync URIs + assertEquals("true", taskList.taskListSyncUri().getQueryParameter(TaskContract.CALLER_IS_SYNCADAPTER)) + assertEquals(testAccount.type, taskList.taskListSyncUri().getQueryParameter(TaskContract.ACCOUNT_TYPE)) + assertEquals(testAccount.name, taskList.taskListSyncUri().getQueryParameter(TaskContract.ACCOUNT_NAME)) + + assertEquals("true", taskList.tasksSyncUri().getQueryParameter(TaskContract.CALLER_IS_SYNCADAPTER)) + assertEquals(testAccount.type, taskList.tasksSyncUri().getQueryParameter(TaskContract.ACCOUNT_TYPE)) + assertEquals(testAccount.name, taskList.tasksSyncUri().getQueryParameter(TaskContract.ACCOUNT_NAME)) + } finally { + // delete task list + assertEquals(1, taskList.delete()) + } + } + + @Test + fun testCommitRelations() { + val taskList = createTaskList() + assertTrue(taskList.useDelayedRelations) + try { + val parent = Task() + parent.uid = "parent" + parent.summary = "Parent task" + val parentContentUri = TestTask(taskList, parent).add() + + val child = Task() + child.uid = "child" + child.summary = "Child task" + child.relatedTo.add(RelatedTo(parent.uid)) + val childContentUri = TestTask(taskList, child).add() + + // there should be one DelayedRelation row + taskList.provider.client.query(taskList.tasksPropertiesSyncUri(), null, + "${Properties.TASK_ID}=?", arrayOf(ContentUris.parseId(childContentUri).toString()), + null, null)!!.use { cursor -> + assertEquals(1, cursor.count) + cursor.moveToNext() + + val row = ContentValues() + DatabaseUtils.cursorRowToContentValues(cursor, row) + + assertEquals(AndroidTask.DelayedRelation.CONTENT_ITEM_TYPE, row.getAsString(Properties.MIMETYPE)) + assertNull(row.getAsLong(Relation.RELATED_ID)) + assertEquals(parent.uid, row.getAsString(Relation.RELATED_UID)) + assertEquals(Relation.RELTYPE_PARENT, row.getAsInteger(Relation.RELATED_TYPE)) + } + + taskList.commitRelations() - // sync URIs - assertEquals("true", taskList.taskListSyncUri().getQueryParameter(TaskContract.CALLER_IS_SYNCADAPTER)) - assertEquals(testAccount.type, taskList.taskListSyncUri().getQueryParameter(TaskContract.ACCOUNT_TYPE)) - assertEquals(testAccount.name, taskList.taskListSyncUri().getQueryParameter(TaskContract.ACCOUNT_NAME)) + // now there must be a real Relation row + taskList.provider.client.query(taskList.tasksPropertiesSyncUri(), null, + "${Properties.TASK_ID}=?", arrayOf(ContentUris.parseId(childContentUri).toString()), + null, null)!!.use { cursor -> + assertEquals(1, cursor.count) + cursor.moveToNext() - assertEquals("true", taskList.tasksSyncUri().getQueryParameter(TaskContract.CALLER_IS_SYNCADAPTER)) - assertEquals(testAccount.type, taskList.tasksSyncUri().getQueryParameter(TaskContract.ACCOUNT_TYPE)) - assertEquals(testAccount.name, taskList.tasksSyncUri().getQueryParameter(TaskContract.ACCOUNT_NAME)) + val row = ContentValues() + DatabaseUtils.cursorRowToContentValues(cursor, row) - // delete task list - assertEquals(1, taskList.delete()) + assertEquals(Relation.CONTENT_ITEM_TYPE, row.getAsString(Properties.MIMETYPE)) + assertEquals(ContentUris.parseId(parentContentUri), row.getAsLong(Relation.RELATED_ID)) + assertEquals(parent.uid, row.getAsString(Relation.RELATED_UID)) + assertEquals(Relation.RELTYPE_PARENT, row.getAsInteger(Relation.RELATED_TYPE)) + } + } finally { + taskList.delete() + } } } diff --git a/src/androidTest/java/at/bitfire/ical4android/AndroidTaskTest.kt b/src/androidTest/java/at/bitfire/ical4android/AndroidTaskTest.kt index 1b74c30..e77ce01 100644 --- a/src/androidTest/java/at/bitfire/ical4android/AndroidTaskTest.kt +++ b/src/androidTest/java/at/bitfire/ical4android/AndroidTaskTest.kt @@ -17,10 +17,8 @@ import at.bitfire.ical4android.impl.TestTask import at.bitfire.ical4android.impl.TestTaskList import net.fortuna.ical4j.model.Date import net.fortuna.ical4j.model.TimeZone -import net.fortuna.ical4j.model.property.DtStart -import net.fortuna.ical4j.model.property.Due -import net.fortuna.ical4j.model.property.Organizer -import net.fortuna.ical4j.model.property.XProperty +import net.fortuna.ical4j.model.parameter.RelType +import net.fortuna.ical4j.model.property.* import org.dmfs.tasks.contract.TaskContract import org.junit.After import org.junit.Assert.* @@ -51,6 +49,7 @@ class AndroidTaskTest { taskList = TestTaskList.create(testAccount, providerOrNull) assertNotNull("Couldn't find/create test task list", taskList) + taskList!!.useDelayedRelations = false taskListUri = ContentUris.withAppendedId(provider!!.taskListsUri(), taskList!!.id) } @@ -80,6 +79,11 @@ class AndroidTaskTest { // extended properties task.categories.addAll(arrayOf("Cat1", "Cat2")) + + val sibling = RelatedTo("most-fields2@example.com") + sibling.parameters.add(RelType.SIBLING) + task.relatedTo.add(sibling) + task.unknownProperties += XProperty("X-UNKNOWN-PROP", "Unknown Value") // add to task list @@ -98,7 +102,9 @@ class AndroidTaskTest { assertEquals(task.description, task2.description) assertEquals(task.location, task2.location) assertEquals(task.dtStart, task2.dtStart) + assertEquals(task.categories, task2.categories) + assertEquals(task.relatedTo, task2.relatedTo) assertEquals(task.unknownProperties, task2.unknownProperties) } finally { testTask.delete() diff --git a/src/main/java/at/bitfire/ical4android/AndroidTask.kt b/src/main/java/at/bitfire/ical4android/AndroidTask.kt index 24b0781..96cdbc9 100644 --- a/src/main/java/at/bitfire/ical4android/AndroidTask.kt +++ b/src/main/java/at/bitfire/ical4android/AndroidTask.kt @@ -10,21 +10,23 @@ package at.bitfire.ical4android import android.content.ContentProviderOperation import android.content.ContentProviderOperation.Builder +import android.content.ContentResolver import android.content.ContentUris import android.content.ContentValues import android.net.Uri import android.os.RemoteException +import at.bitfire.ical4android.AndroidTask.DelayedRelation.Companion.CONTENT_ITEM_TYPE import at.bitfire.ical4android.MiscUtils.CursorHelper.toValues import net.fortuna.ical4j.model.* import net.fortuna.ical4j.model.Date import net.fortuna.ical4j.model.Property import net.fortuna.ical4j.model.component.VAlarm +import net.fortuna.ical4j.model.parameter.RelType import net.fortuna.ical4j.model.parameter.Related import net.fortuna.ical4j.model.property.* import org.dmfs.tasks.contract.TaskContract.* import org.dmfs.tasks.contract.TaskContract.Properties -import org.dmfs.tasks.contract.TaskContract.Property.Alarm -import org.dmfs.tasks.contract.TaskContract.Property.Category +import org.dmfs.tasks.contract.TaskContract.Property.* import java.io.FileNotFoundException import java.net.URI import java.net.URISyntaxException @@ -92,6 +94,26 @@ abstract class AndroidTask( populateProperty(propCursor.toValues(true)) } + // Special case: parent_id set, but no matching parent Relation row (like given by aCalendar+) + // In this case, we create the relation ourselves. + val relatedToList = task!!.relatedTo + values.getAsLong(Tasks.PARENT_ID)?.let { parentId -> + val hasParentRelation = relatedToList.any { relatedTo -> + val relatedType = relatedTo.getParameter(Parameter.RELTYPE) + relatedType == null || relatedType == RelType.PARENT + } + if (!hasParentRelation) { + // get UID of parent task + val parentContentUri = ContentUris.withAppendedId(taskList.tasksSyncUri(), parentId) + client.query(parentContentUri, arrayOf(Tasks._UID), null, null, null)?.use { cursor -> + if (cursor.moveToNext()) { + // add RelatedTo for parent task + relatedToList += RelatedTo(cursor.getString(0)) + } + } + } + } + return task } } @@ -189,6 +211,8 @@ abstract class AndroidTask( populateAlarm(row) Category.CONTENT_ITEM_TYPE -> task.categories += row.getAsString(Category.CATEGORY_NAME) + Relation.CONTENT_ITEM_TYPE -> + populateRelatedTo(row) UnknownProperty.CONTENT_ITEM_TYPE -> task.unknownProperties += UnknownProperty.fromJsonString(row.getAsString(UNKNOWN_PROPERTY_DATA)) else -> @@ -197,7 +221,6 @@ abstract class AndroidTask( } protected open fun populateAlarm(row: ContentValues) { - Constants.log.log(Level.FINE, "Read task reminder from tasks provider", row) val task = requireNotNull(task) val props = PropertyList() @@ -225,6 +248,28 @@ abstract class AndroidTask( task.alarms += VAlarm(props) } + protected open fun populateRelatedTo(row: ContentValues) { + val uid = row.getAsString(Relation.RELATED_UID) + if (uid == null) { + Constants.log.warning("Task relation doesn't refer to same task list; can't be synchronized") + return + } + + val relatedTo = RelatedTo(uid) + + // add relation type as reltypeparam + relatedTo.parameters.add(when (row.getAsInteger(Relation.RELATED_TYPE)) { + Relation.RELTYPE_CHILD -> + RelType.CHILD + Relation.RELTYPE_SIBLING -> + RelType.SIBLING + else /* Relation.RELTYPE_PARENT, default value */ -> + RelType.PARENT + }) + + requireNotNull(task).relatedTo.add(relatedTo) + } + fun add(): Uri { val batch = BatchOperation(taskList.provider.client) @@ -261,13 +306,14 @@ abstract class AndroidTask( return uri } - private fun insertProperties(batch: BatchOperation) { + protected open fun insertProperties(batch: BatchOperation) { insertAlarms(batch) insertCategories(batch) + insertRelatedTo(batch) insertUnknownProperties(batch) } - private fun insertAlarms(batch: BatchOperation) { + protected open fun insertAlarms(batch: BatchOperation) { for (alarm in requireNotNull(task).alarms) { val alarmRef = when (alarm.trigger.getParameter(Parameter.RELATED)) { Related.END -> @@ -300,7 +346,7 @@ abstract class AndroidTask( } } - private fun insertCategories(batch: BatchOperation) { + protected open fun insertCategories(batch: BatchOperation) { for (category in requireNotNull(task).categories) { val builder = ContentProviderOperation.newInsert(taskList.tasksPropertiesSyncUri()) .withValue(Category.TASK_ID, id) @@ -311,7 +357,32 @@ abstract class AndroidTask( } } - private fun insertUnknownProperties(batch: BatchOperation) { + protected open fun insertRelatedTo(batch: BatchOperation) { + val mimeType = if (taskList.useDelayedRelations) + DelayedRelation.CONTENT_ITEM_TYPE + else + Relation.CONTENT_ITEM_TYPE + + for (relatedTo in requireNotNull(task).relatedTo) { + val relType = when ((relatedTo.getParameter(Parameter.RELTYPE) as RelType?)) { + RelType.CHILD -> + Relation.RELTYPE_CHILD + RelType.SIBLING -> + Relation.RELTYPE_SIBLING + else /* RelType.PARENT, default value */ -> + Relation.RELTYPE_PARENT + } + val builder = ContentProviderOperation.newInsert(taskList.tasksPropertiesSyncUri()) + .withValue(Relation.TASK_ID, id) + .withValue(Relation.MIMETYPE, mimeType) + .withValue(Relation.RELATED_UID, relatedTo.value) + .withValue(Relation.RELATED_TYPE, relType) + Constants.log.log(Level.FINE, "Inserting relation", builder.build()) + batch.enqueue(BatchOperation.Operation(builder)) + } + } + + protected open fun insertUnknownProperties(batch: BatchOperation) { for (property in requireNotNull(task).unknownProperties) { if (property.value.length > UnknownProperty.MAX_UNKNOWN_PROPERTY_SIZE) { Constants.log.warning("Ignoring unknown property with ${property.value.length} octets (too long)") @@ -434,4 +505,17 @@ abstract class AndroidTask( override fun toString() = MiscUtils.reflectionToString(this) + + /** + * A delayed relation row represents a relation which possibly can't be resolved yet. + * Same definition as [Relation], only the row type is [CONTENT_ITEM_TYPE] instead of [Relation.CONTENT_ITEM_TYPE]. + */ + class DelayedRelation { + + companion object { + const val CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/vnd.ical4android.delayed-relation" + } + + } + } diff --git a/src/main/java/at/bitfire/ical4android/AndroidTaskList.kt b/src/main/java/at/bitfire/ical4android/AndroidTaskList.kt index 83a67a3..3167418 100644 --- a/src/main/java/at/bitfire/ical4android/AndroidTaskList.kt +++ b/src/main/java/at/bitfire/ical4android/AndroidTaskList.kt @@ -9,14 +9,16 @@ package at.bitfire.ical4android import android.accounts.Account +import android.content.ContentProviderOperation import android.content.ContentUris import android.content.ContentValues import android.content.Context import android.net.Uri import at.bitfire.ical4android.MiscUtils.CursorHelper.toValues import org.dmfs.tasks.contract.TaskContract -import org.dmfs.tasks.contract.TaskContract.TaskLists -import org.dmfs.tasks.contract.TaskContract.Tasks +import org.dmfs.tasks.contract.TaskContract.* +import org.dmfs.tasks.contract.TaskContract.Properties +import org.dmfs.tasks.contract.TaskContract.Property.Relation import java.io.FileNotFoundException import java.util.* @@ -38,8 +40,9 @@ abstract class AndroidTaskList( /** * Acquires a [android.content.ContentProviderClient] for a supported task provider. If multiple providers are * available, a pre-defined priority list is taken into account. + * * @return A [TaskProvider], or null if task storage is not available/accessible. - * Caller is responsible for calling release()! + * Caller is responsible for calling [TaskProvider.close]! */ fun acquireTaskProvider(context: Context): TaskProvider? { val byPriority = arrayOf( @@ -96,6 +99,16 @@ abstract class AndroidTaskList( var isSynced = false var isVisible = false + /** + * When tasks are added or updated, they may refer to related tasks ([Task.relatedTo]), + * but these related tasks may not be available yet (for instance, because they have not been + * synchronized yet), so that the tasks provider can't establish the relation in the database. + * + * When delayed relations are used, [commitRelations] must be called after + * operations which potentially add relations (namely [AndroidTask.add] and [AndroidTask.update]). + */ + var useDelayedRelations = true + protected fun populate(values: ContentValues) { syncId = values.getAsString(TaskLists._SYNC_ID) @@ -108,12 +121,50 @@ abstract class AndroidTaskList( fun update(info: ContentValues) = provider.client.update(taskListSyncUri(), info, null, null) fun delete() = provider.client.delete(taskListSyncUri(), null, null) + /** + * Transforms [AndroidTask.DelayedRelation]s to real [org.dmfs.tasks.contract.TaskContract.Property.Relation]s. Only + * useful when [useDelayedRelations] is active. + */ + fun commitRelations() { + Constants.log.fine("Commiting relations") + + val batch = BatchOperation(provider.client) + provider.client.query(tasksPropertiesSyncUri(), + arrayOf(Properties.PROPERTY_ID, Properties.TASK_ID, Relation.RELATED_TYPE, Relation.RELATED_UID), + "${Properties.MIMETYPE}=?", arrayOf(AndroidTask.DelayedRelation.CONTENT_ITEM_TYPE), null)?.use { cursor -> + while (cursor.moveToNext()) { + val id = cursor.getLong(0) + val taskId = cursor.getLong(1) + val relatedType = cursor.getInt(2) + val relatedUid = cursor.getString(3) + + // create new Relation row + batch.enqueue(BatchOperation.Operation( + ContentProviderOperation.newInsert(tasksPropertiesSyncUri()) + .withValue(Relation.TASK_ID, taskId) + .withValue(Relation.MIMETYPE, Relation.CONTENT_ITEM_TYPE) + .withValue(Relation.RELATED_TYPE, relatedType) + .withValue(Relation.RELATED_UID, relatedUid) + )) + + // delete DelayedRelation row + val delayedRelationUri = ContentUris.withAppendedId(tasksPropertiesSyncUri(), id) + batch.enqueue(BatchOperation.Operation( + ContentProviderOperation.newDelete(delayedRelationUri) + )) + } + } + batch.commit() + } + /** * Queries tasks from this task list. Adds a WHERE clause that restricts the * query to [Tasks.LIST_ID] = [id]. + * * @param _where selection * @param _whereArgs arguments for selection + * * @return events from this task list which match the selection */ fun queryTasks(_where: String? = null, _whereArgs: Array? = null): List { diff --git a/src/main/java/at/bitfire/ical4android/Task.kt b/src/main/java/at/bitfire/ical4android/Task.kt index e2bc5f6..ddce17c 100644 --- a/src/main/java/at/bitfire/ical4android/Task.kt +++ b/src/main/java/at/bitfire/ical4android/Task.kt @@ -55,10 +55,12 @@ class Task: ICalendar() { val rDates = LinkedList() val exDates = LinkedList() - val alarms = LinkedList() val categories = LinkedList() + var relatedTo = LinkedList() val unknownProperties = LinkedList() + val alarms = LinkedList() + companion object { /** @@ -120,7 +122,8 @@ class Task: ICalendar() { is RDate -> t.rDates += prop is ExDate -> t.exDates += prop is Categories -> t.categories.addAll(prop.categories.toList()) - is ProdId, is DtStamp, is Uid -> { /* don't save these as unknown properties */ } + is RelatedTo -> t.relatedTo.add(prop) + is Uid, is ProdId, is DtStamp -> { /* don't save these as unknown properties */ } else -> t.unknownProperties += prop } @@ -174,7 +177,7 @@ class Task: ICalendar() { if (categories.isNotEmpty()) props += Categories(TextList(categories.toTypedArray())) - + props.addAll(relatedTo) props.addAll(unknownProperties) // remember used time zones diff --git a/src/test/java/at/bitfire/ical4android/TaskTest.kt b/src/test/java/at/bitfire/ical4android/TaskTest.kt index 1359513..1e3e020 100644 --- a/src/test/java/at/bitfire/ical4android/TaskTest.kt +++ b/src/test/java/at/bitfire/ical4android/TaskTest.kt @@ -8,10 +8,8 @@ package at.bitfire.ical4android -import net.fortuna.ical4j.model.Date -import net.fortuna.ical4j.model.DateList -import net.fortuna.ical4j.model.DateTime -import net.fortuna.ical4j.model.Dur +import net.fortuna.ical4j.model.* +import net.fortuna.ical4j.model.parameter.RelType import net.fortuna.ical4j.model.parameter.Value import net.fortuna.ical4j.model.property.* import org.junit.Assert.* @@ -90,6 +88,10 @@ class TaskTest { assertArrayEquals(arrayOf("Test","Sample"), t.categories.toArray()) + val sibling = t.relatedTo.first + assertEquals("most-fields2@example.com", sibling.value) + assertEquals(RelType.SIBLING, (sibling.getParameter(Parameter.RELTYPE) as RelType)) + val unknown = t.unknownProperties.first assertEquals("X-UNKNOWN-PROP", unknown.name) assertEquals("xxx", unknown.getParameter("param1").value) diff --git a/src/test/resources/tasks/most-fields1.ics b/src/test/resources/tasks/most-fields1.ics index 85613d9..ff4dbb0 100644 --- a/src/test/resources/tasks/most-fields1.ics +++ b/src/test/resources/tasks/most-fields1.ics @@ -24,6 +24,7 @@ EXDATE;VALUE=DATE:20120101 EXDATE;VALUE=DATE:20140101,20180101 RDATE;VALUE=DATE:20100310,20100315 RDATE;VALUE=DATE:20100810 +RELATED-TO;RELTYPE=SIBLING:most-fields2@example.com X-UNKNOWN-PROP;param1=xxx:Unknown Value CREATED:19960329T133000Z LAST-MODIFIED:19960817T133000Z -- GitLab From 958983959aa6988710c441ecccd54cfc676b7a85 Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Wed, 13 Nov 2019 14:10:25 +0100 Subject: [PATCH 44/58] Tasks: directly use Relation rows, no need for DelayedRelation anymore --- .../ical4android/AndroidTaskListTest.kt | 46 +++++----- .../bitfire/ical4android/AndroidTaskTest.kt | 1 - .../at/bitfire/ical4android/AndroidTask.kt | 49 +++-------- .../bitfire/ical4android/AndroidTaskList.kt | 86 ++++++++++--------- 4 files changed, 81 insertions(+), 101 deletions(-) diff --git a/src/androidTest/java/at/bitfire/ical4android/AndroidTaskListTest.kt b/src/androidTest/java/at/bitfire/ical4android/AndroidTaskListTest.kt index 871a48b..7f36451 100644 --- a/src/androidTest/java/at/bitfire/ical4android/AndroidTaskListTest.kt +++ b/src/androidTest/java/at/bitfire/ical4android/AndroidTaskListTest.kt @@ -19,6 +19,7 @@ import net.fortuna.ical4j.model.property.RelatedTo import org.dmfs.tasks.contract.TaskContract import org.dmfs.tasks.contract.TaskContract.Properties import org.dmfs.tasks.contract.TaskContract.Property.Relation +import org.dmfs.tasks.contract.TaskContract.Tasks import org.junit.After import org.junit.Assert.* import org.junit.Assume.assumeNotNull @@ -81,24 +82,27 @@ class AndroidTaskListTest { } @Test - fun testCommitRelations() { + fun testTouchRelations() { val taskList = createTaskList() - assertTrue(taskList.useDelayedRelations) try { val parent = Task() parent.uid = "parent" parent.summary = "Parent task" - val parentContentUri = TestTask(taskList, parent).add() val child = Task() child.uid = "child" child.summary = "Child task" child.relatedTo.add(RelatedTo(parent.uid)) + + // insert child before parent val childContentUri = TestTask(taskList, child).add() + val childId = ContentUris.parseId(childContentUri) + val parentContentUri = TestTask(taskList, parent).add() + val parentId = ContentUris.parseId(parentContentUri) - // there should be one DelayedRelation row + // OpenTasks should provide the correct relation… taskList.provider.client.query(taskList.tasksPropertiesSyncUri(), null, - "${Properties.TASK_ID}=?", arrayOf(ContentUris.parseId(childContentUri).toString()), + "${Properties.TASK_ID}=?", arrayOf(childId.toString()), null, null)!!.use { cursor -> assertEquals(1, cursor.count) cursor.moveToNext() @@ -106,28 +110,26 @@ class AndroidTaskListTest { val row = ContentValues() DatabaseUtils.cursorRowToContentValues(cursor, row) - assertEquals(AndroidTask.DelayedRelation.CONTENT_ITEM_TYPE, row.getAsString(Properties.MIMETYPE)) - assertNull(row.getAsLong(Relation.RELATED_ID)) + assertEquals(Relation.CONTENT_ITEM_TYPE, row.getAsString(Properties.MIMETYPE)) + assertEquals(parentId, row.getAsLong(Relation.RELATED_ID)) assertEquals(parent.uid, row.getAsString(Relation.RELATED_UID)) assertEquals(Relation.RELTYPE_PARENT, row.getAsInteger(Relation.RELATED_TYPE)) } + // … BUT the parent_id is not updated (https://github.com/dmfs/opentasks/issues/877) + taskList.provider.client.query(childContentUri, arrayOf(Tasks.PARENT_ID), + null, null, null)!!.use { cursor -> + assertTrue(cursor.moveToNext()) + assertTrue(cursor.isNull(0)) + } - taskList.commitRelations() - - // now there must be a real Relation row - taskList.provider.client.query(taskList.tasksPropertiesSyncUri(), null, - "${Properties.TASK_ID}=?", arrayOf(ContentUris.parseId(childContentUri).toString()), - null, null)!!.use { cursor -> - assertEquals(1, cursor.count) - cursor.moveToNext() - - val row = ContentValues() - DatabaseUtils.cursorRowToContentValues(cursor, row) + // touch the relations to update parent_id values + taskList.touchRelations() - assertEquals(Relation.CONTENT_ITEM_TYPE, row.getAsString(Properties.MIMETYPE)) - assertEquals(ContentUris.parseId(parentContentUri), row.getAsLong(Relation.RELATED_ID)) - assertEquals(parent.uid, row.getAsString(Relation.RELATED_UID)) - assertEquals(Relation.RELTYPE_PARENT, row.getAsInteger(Relation.RELATED_TYPE)) + // now parent_id should bet set + taskList.provider.client.query(childContentUri, arrayOf(Tasks.PARENT_ID), + null, null, null)!!.use { cursor -> + assertTrue(cursor.moveToNext()) + assertEquals(parentId, cursor.getLong(0)) } } finally { taskList.delete() diff --git a/src/androidTest/java/at/bitfire/ical4android/AndroidTaskTest.kt b/src/androidTest/java/at/bitfire/ical4android/AndroidTaskTest.kt index e77ce01..600e56f 100644 --- a/src/androidTest/java/at/bitfire/ical4android/AndroidTaskTest.kt +++ b/src/androidTest/java/at/bitfire/ical4android/AndroidTaskTest.kt @@ -49,7 +49,6 @@ class AndroidTaskTest { taskList = TestTaskList.create(testAccount, providerOrNull) assertNotNull("Couldn't find/create test task list", taskList) - taskList!!.useDelayedRelations = false taskListUri = ContentUris.withAppendedId(provider!!.taskListsUri(), taskList!!.id) } diff --git a/src/main/java/at/bitfire/ical4android/AndroidTask.kt b/src/main/java/at/bitfire/ical4android/AndroidTask.kt index 96cdbc9..ded4d62 100644 --- a/src/main/java/at/bitfire/ical4android/AndroidTask.kt +++ b/src/main/java/at/bitfire/ical4android/AndroidTask.kt @@ -10,12 +10,10 @@ package at.bitfire.ical4android import android.content.ContentProviderOperation import android.content.ContentProviderOperation.Builder -import android.content.ContentResolver import android.content.ContentUris import android.content.ContentValues import android.net.Uri import android.os.RemoteException -import at.bitfire.ical4android.AndroidTask.DelayedRelation.Companion.CONTENT_ITEM_TYPE import at.bitfire.ical4android.MiscUtils.CursorHelper.toValues import net.fortuna.ical4j.model.* import net.fortuna.ical4j.model.Date @@ -79,28 +77,28 @@ abstract class AndroidTask( task = Task() val client = taskList.provider.client - client.query(taskSyncURI(), null, null, null, null)?.use { cursor -> + client.query(taskSyncURI(true), null, null, null, null)?.use { cursor -> if (cursor.moveToFirst()) { val values = cursor.toValues(true) Constants.log.log(Level.FINER, "Found task", values) populateTask(values) - if (values.getAsInteger(Tasks.HAS_PROPERTIES) != 0) - // fetch properties - client.query(taskList.tasksPropertiesSyncUri(), null, - "${Properties.TASK_ID}=?", arrayOf(id.toString()), - null)?.use { propCursor -> - while (propCursor.moveToNext()) - populateProperty(propCursor.toValues(true)) + if (values.containsKey(Properties.PROPERTY_ID)) { + // process the first property, which is combined with the task row + populateProperty(values) + + while (cursor.moveToNext()) { + // process the other properties + populateProperty(cursor.toValues(true)) } + } // Special case: parent_id set, but no matching parent Relation row (like given by aCalendar+) - // In this case, we create the relation ourselves. val relatedToList = task!!.relatedTo values.getAsLong(Tasks.PARENT_ID)?.let { parentId -> val hasParentRelation = relatedToList.any { relatedTo -> val relatedType = relatedTo.getParameter(Parameter.RELTYPE) - relatedType == null || relatedType == RelType.PARENT + relatedType == RelType.PARENT || relatedType == null /* RelType.PARENT is the default value */ } if (!hasParentRelation) { // get UID of parent task @@ -358,11 +356,6 @@ abstract class AndroidTask( } protected open fun insertRelatedTo(batch: BatchOperation) { - val mimeType = if (taskList.useDelayedRelations) - DelayedRelation.CONTENT_ITEM_TYPE - else - Relation.CONTENT_ITEM_TYPE - for (relatedTo in requireNotNull(task).relatedTo) { val relType = when ((relatedTo.getParameter(Parameter.RELTYPE) as RelType?)) { RelType.CHILD -> @@ -374,7 +367,7 @@ abstract class AndroidTask( } val builder = ContentProviderOperation.newInsert(taskList.tasksPropertiesSyncUri()) .withValue(Relation.TASK_ID, id) - .withValue(Relation.MIMETYPE, mimeType) + .withValue(Relation.MIMETYPE, Relation.CONTENT_ITEM_TYPE) .withValue(Relation.RELATED_UID, relatedTo.value) .withValue(Relation.RELATED_TYPE, relType) Constants.log.log(Level.FINE, "Inserting relation", builder.build()) @@ -494,28 +487,12 @@ abstract class AndroidTask( return tz ?: TimeZone.getDefault() } - protected fun taskSyncURI(): Uri { + protected fun taskSyncURI(loadProperties: Boolean = false): Uri { val id = requireNotNull(id) - val builder = taskList.tasksSyncUri().buildUpon() - return ContentUris.appendId(builder, id) - .appendQueryParameter(LOAD_PROPERTIES, "1") - .build() + return ContentUris.withAppendedId(taskList.tasksSyncUri(loadProperties), id) } override fun toString() = MiscUtils.reflectionToString(this) - - /** - * A delayed relation row represents a relation which possibly can't be resolved yet. - * Same definition as [Relation], only the row type is [CONTENT_ITEM_TYPE] instead of [Relation.CONTENT_ITEM_TYPE]. - */ - class DelayedRelation { - - companion object { - const val CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/vnd.ical4android.delayed-relation" - } - - } - } diff --git a/src/main/java/at/bitfire/ical4android/AndroidTaskList.kt b/src/main/java/at/bitfire/ical4android/AndroidTaskList.kt index 3167418..7ecf0d2 100644 --- a/src/main/java/at/bitfire/ical4android/AndroidTaskList.kt +++ b/src/main/java/at/bitfire/ical4android/AndroidTaskList.kt @@ -16,9 +16,9 @@ import android.content.Context import android.net.Uri import at.bitfire.ical4android.MiscUtils.CursorHelper.toValues import org.dmfs.tasks.contract.TaskContract -import org.dmfs.tasks.contract.TaskContract.* -import org.dmfs.tasks.contract.TaskContract.Properties import org.dmfs.tasks.contract.TaskContract.Property.Relation +import org.dmfs.tasks.contract.TaskContract.TaskLists +import org.dmfs.tasks.contract.TaskContract.Tasks import java.io.FileNotFoundException import java.util.* @@ -99,16 +99,6 @@ abstract class AndroidTaskList( var isSynced = false var isVisible = false - /** - * When tasks are added or updated, they may refer to related tasks ([Task.relatedTo]), - * but these related tasks may not be available yet (for instance, because they have not been - * synchronized yet), so that the tasks provider can't establish the relation in the database. - * - * When delayed relations are used, [commitRelations] must be called after - * operations which potentially add relations (namely [AndroidTask.add] and [AndroidTask.update]). - */ - var useDelayedRelations = true - protected fun populate(values: ContentValues) { syncId = values.getAsString(TaskLists._SYNC_ID) @@ -122,39 +112,43 @@ abstract class AndroidTaskList( fun delete() = provider.client.delete(taskListSyncUri(), null, null) /** - * Transforms [AndroidTask.DelayedRelation]s to real [org.dmfs.tasks.contract.TaskContract.Property.Relation]s. Only - * useful when [useDelayedRelations] is active. - */ - fun commitRelations() { - Constants.log.fine("Commiting relations") - - val batch = BatchOperation(provider.client) - provider.client.query(tasksPropertiesSyncUri(), - arrayOf(Properties.PROPERTY_ID, Properties.TASK_ID, Relation.RELATED_TYPE, Relation.RELATED_UID), - "${Properties.MIMETYPE}=?", arrayOf(AndroidTask.DelayedRelation.CONTENT_ITEM_TYPE), null)?.use { cursor -> + * When tasks are added or updated, they may refer to related tasks by UID ([Relation.RELATED_UID]). + * However, those related tasks may not be available (for instance, because they have not been + * synchronized yet), so that the tasks provider can't establish the actual relation (= set + * [Relation.TASK_ID]) in the database. + * + * As soon as such a related task is added, OpenTasks updates the [Relation.RELATED_ID], + * but it does *not* update [Tasks.PARENT_ID] of the parent task: + * https://github.com/dmfs/opentasks/issues/877 + * + * This method shall be called after all tasks have been synchronized. It touches + * + * - all [Relation] rows + * - with [Relation.RELATED_ID] (→ related task is already synchronized) + * - of tasks without [Tasks.PARENT_ID] (→ only touch relevant rows) + * + * so that missing [Tasks.PARENT_ID] fields are updated. + * + * @return number of touched [Relation] rows + */ + fun touchRelations(): Int { + Constants.log.fine("Touching relations to set parent_id") + val batchOperation = BatchOperation(provider.client) + provider.client.query(tasksSyncUri(true), null, + "${Tasks.LIST_ID}=? AND ${Tasks.PARENT_ID} IS NULL AND ${Relation.MIMETYPE}=? AND ${Relation.RELATED_ID} IS NOT NULL", + arrayOf(id.toString(), Relation.CONTENT_ITEM_TYPE), + null, null)?.use { cursor -> while (cursor.moveToNext()) { - val id = cursor.getLong(0) - val taskId = cursor.getLong(1) - val relatedType = cursor.getInt(2) - val relatedUid = cursor.getString(3) - - // create new Relation row - batch.enqueue(BatchOperation.Operation( - ContentProviderOperation.newInsert(tasksPropertiesSyncUri()) - .withValue(Relation.TASK_ID, taskId) - .withValue(Relation.MIMETYPE, Relation.CONTENT_ITEM_TYPE) - .withValue(Relation.RELATED_TYPE, relatedType) - .withValue(Relation.RELATED_UID, relatedUid) - )) - - // delete DelayedRelation row - val delayedRelationUri = ContentUris.withAppendedId(tasksPropertiesSyncUri(), id) - batch.enqueue(BatchOperation.Operation( - ContentProviderOperation.newDelete(delayedRelationUri) + val values = cursor.toValues() + val id = values.getAsLong(Relation.PROPERTY_ID) + val propertyContentUri = ContentUris.withAppendedId(tasksPropertiesSyncUri(), id) + batchOperation.enqueue(BatchOperation.Operation( + ContentProviderOperation.newUpdate(propertyContentUri) + .withValue(Relation.RELATED_ID, values.getAsLong(Relation.RELATED_ID)) )) } } - batch.commit() + return batchOperation.commit() } @@ -187,7 +181,15 @@ abstract class AndroidTaskList( fun taskListSyncUri() = TaskProvider.syncAdapterUri(ContentUris.withAppendedId(provider.taskListsUri(), id), account) - fun tasksSyncUri() = TaskProvider.syncAdapterUri(provider.tasksUri(), account) + fun tasksSyncUri(loadProperties: Boolean = false): Uri { + val uri = TaskProvider.syncAdapterUri(provider.tasksUri(), account) + return if (loadProperties) + uri .buildUpon() + .appendQueryParameter(TaskContract.LOAD_PROPERTIES, "1") + .build() + else + uri + } fun tasksPropertiesSyncUri() = TaskProvider.syncAdapterUri(provider.propertiesUri(), account) } -- GitLab From 6415355aad2cd0ec3b7fb3ea6a94c912a4feef67 Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Fri, 15 Nov 2019 23:13:10 +0100 Subject: [PATCH 45/58] Correctly handle EMAIL reminders --- .../bitfire/ical4android/impl/TestCalendar.kt | 3 +- .../bitfire/ical4android/AndroidCalendar.kt | 19 ++++++---- .../at/bitfire/ical4android/AndroidEvent.kt | 35 ++++++++++++++----- 3 files changed, 41 insertions(+), 16 deletions(-) diff --git a/src/androidTest/java/at/bitfire/ical4android/impl/TestCalendar.kt b/src/androidTest/java/at/bitfire/ical4android/impl/TestCalendar.kt index ea0ccc4..e127ec6 100644 --- a/src/androidTest/java/at/bitfire/ical4android/impl/TestCalendar.kt +++ b/src/androidTest/java/at/bitfire/ical4android/impl/TestCalendar.kt @@ -29,8 +29,7 @@ class TestCalendar( val values = ContentValues(3) values.put(CalendarContract.Calendars.NAME, "TestCalendar") values.put(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, "ical4android Test Calendar") - values.put(CalendarContract.Calendars.ALLOWED_REMINDERS, - CalendarContract.Reminders.METHOD_DEFAULT) + values.put(CalendarContract.Calendars.ALLOWED_REMINDERS, CalendarContract.Reminders.METHOD_DEFAULT) val uri = AndroidCalendar.create(account, provider, values) TestCalendar(account, provider, ContentUris.parseId(uri)) diff --git a/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt b/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt index 1c3e328..cb59e7d 100644 --- a/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt +++ b/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt @@ -13,7 +13,6 @@ import android.content.ContentProviderClient import android.content.ContentUris import android.content.ContentValues import android.net.Uri -import android.provider.CalendarContract import android.provider.CalendarContract.* import at.bitfire.ical4android.MiscUtils.CursorHelper.toValues import java.io.FileNotFoundException @@ -30,18 +29,28 @@ abstract class AndroidCalendar( val provider: ContentProviderClient, val eventFactory: AndroidEventFactory, - /** the calendar ID ([CalendarContract.Calendars._ID]) **/ + /** the calendar ID ([Calendars._ID]) **/ val id: Long ) { companion object { + /** + * Recommended initial values when creating Android [Calendars]. + */ + val calendarBaseValues = ContentValues(3) + init { + calendarBaseValues.put(Calendars.ALLOWED_AVAILABILITY, "${Events.AVAILABILITY_BUSY},${Events.AVAILABILITY_FREE},${Events.AVAILABILITY_TENTATIVE}") + calendarBaseValues.put(Calendars.ALLOWED_ATTENDEE_TYPES, "${Attendees.TYPE_NONE},${Attendees.TYPE_OPTIONAL},${Attendees.TYPE_REQUIRED},${Attendees.TYPE_RESOURCE}") + calendarBaseValues.put(Calendars.ALLOWED_REMINDERS, "${Reminders.METHOD_DEFAULT},${Reminders.METHOD_ALERT},${Reminders.METHOD_EMAIL}") + } + /** * Creates a local (Android calendar provider) calendar. * * @param account account which the calendar should be assigned to * @param provider client for Android calendar provider - * @param info initial calendar properties ([Calendars.CALENDAR_DISPLAY_NAME] etc.) + * @param info initial calendar properties ([Calendars.CALENDAR_DISPLAY_NAME] etc.) – *may be modified by this method* * * @return [Uri] of the created calendar * @@ -51,9 +60,7 @@ abstract class AndroidCalendar( info.put(Calendars.ACCOUNT_NAME, account.name) info.put(Calendars.ACCOUNT_TYPE, account.type) - // these values are generated by ical4android - info.put(Calendars.ALLOWED_AVAILABILITY, "${Events.AVAILABILITY_BUSY},${Events.AVAILABILITY_FREE},${Events.AVAILABILITY_TENTATIVE}") - info.put(Calendars.ALLOWED_ATTENDEE_TYPES, "${Attendees.TYPE_NONE},${Attendees.TYPE_OPTIONAL},${Attendees.TYPE_REQUIRED},${Attendees.TYPE_RESOURCE}") + info.putAll(calendarBaseValues) Constants.log.info("Creating local calendar: $info") return provider.insert(syncAdapterURI(Calendars.CONTENT_URI, account), info) ?: diff --git a/src/main/java/at/bitfire/ical4android/AndroidEvent.kt b/src/main/java/at/bitfire/ical4android/AndroidEvent.kt index 41e5e36..9836fb4 100644 --- a/src/main/java/at/bitfire/ical4android/AndroidEvent.kt +++ b/src/main/java/at/bitfire/ical4android/AndroidEvent.kt @@ -17,6 +17,7 @@ import android.net.Uri import android.os.RemoteException import android.provider.CalendarContract.* import android.util.Base64 +import android.util.Patterns import at.bitfire.ical4android.MiscUtils.CursorHelper.toValues import net.fortuna.ical4j.model.* import net.fortuna.ical4j.model.Date @@ -310,15 +311,30 @@ abstract class AndroidEvent( val alarm = VAlarm(Dur(0, 0, -row.getAsInteger(Reminders.MINUTES), 0)) val props = alarm.properties - props += when (row.getAsInteger(Reminders.METHOD)) { - Reminders.METHOD_EMAIL, - Reminders.METHOD_SMS -> - Action.EMAIL - else -> - // show alarm by default - Action.DISPLAY + when (row.getAsInteger(Reminders.METHOD)) { + Reminders.METHOD_EMAIL -> { + val accountName = calendar.account.name + if (Patterns.EMAIL_ADDRESS.matcher(accountName).matches()) { + props += Action.EMAIL + // ACTION:EMAIL requires SUMMARY, DESCRIPTION, ATTENDEE + props += Summary(event.summary) + props += Description(event.description ?: event.summary) + // Android doesn't allow to save email reminder recipients, so we always use the + // account name (should be account owner's email address) + props += Attendee(URI("mailto", calendar.account.name, null)) + } else { + Constants.log.warning("Account name is not an email address; changing EMAIL reminder to DISPLAY") + props += Action.DISPLAY + props += Description(event.summary) + } + } + + // default: set ACTION:DISPLAY (requires DESCRIPTION) + else -> { + props += Action.DISPLAY + props += Description(event.summary) + } } - props += Description(event.summary) event.alarms += alarm } @@ -622,7 +638,10 @@ abstract class AndroidEvent( val method = when (alarm.action?.value?.toUpperCase(Locale.US)) { Action.DISPLAY.value, Action.AUDIO.value -> Reminders.METHOD_ALERT + + // Note: The calendar provider doesn't support saving specific attendees for email reminders. Action.EMAIL.value -> Reminders.METHOD_EMAIL + else -> Reminders.METHOD_DEFAULT } -- GitLab From ef872cf3710cedbbeb2914146e9ba895589c0a0e Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Fri, 15 Nov 2019 23:17:31 +0100 Subject: [PATCH 46/58] Calendars: only allow BUSY and FREE for AVAILABILITY (= TRANSP) of events --- src/main/java/at/bitfire/ical4android/AndroidCalendar.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt b/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt index cb59e7d..601a3ed 100644 --- a/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt +++ b/src/main/java/at/bitfire/ical4android/AndroidCalendar.kt @@ -40,7 +40,7 @@ abstract class AndroidCalendar( */ val calendarBaseValues = ContentValues(3) init { - calendarBaseValues.put(Calendars.ALLOWED_AVAILABILITY, "${Events.AVAILABILITY_BUSY},${Events.AVAILABILITY_FREE},${Events.AVAILABILITY_TENTATIVE}") + calendarBaseValues.put(Calendars.ALLOWED_AVAILABILITY, "${Events.AVAILABILITY_BUSY},${Events.AVAILABILITY_FREE}") calendarBaseValues.put(Calendars.ALLOWED_ATTENDEE_TYPES, "${Attendees.TYPE_NONE},${Attendees.TYPE_OPTIONAL},${Attendees.TYPE_REQUIRED},${Attendees.TYPE_RESOURCE}") calendarBaseValues.put(Calendars.ALLOWED_REMINDERS, "${Reminders.METHOD_DEFAULT},${Reminders.METHOD_ALERT},${Reminders.METHOD_EMAIL}") } -- GitLab From 5b6ab803e462dade3aea587505bf806e393d4e5c Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Sat, 16 Nov 2019 17:38:08 +0100 Subject: [PATCH 47/58] Clear parent_id when it's not set anymore after a remote update --- src/main/java/at/bitfire/ical4android/AndroidTask.kt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/at/bitfire/ical4android/AndroidTask.kt b/src/main/java/at/bitfire/ical4android/AndroidTask.kt index ded4d62..15e3add 100644 --- a/src/main/java/at/bitfire/ical4android/AndroidTask.kt +++ b/src/main/java/at/bitfire/ical4android/AndroidTask.kt @@ -416,6 +416,9 @@ abstract class AndroidTask( .withValue(Tasks.TASK_COLOR, task.color) .withValue(Tasks.URL, task.url) + // parent_id will be re-calculated when the relation row is inserted (if there is any) + .withValue(Tasks.PARENT_ID, null) + var organizer: String? = null task.organizer?.let { try { -- GitLab From ea01dcd55af7fa2a84e849fa0c00ebd76ff39aac Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Sat, 16 Nov 2019 17:38:42 +0100 Subject: [PATCH 48/58] Ignore empty strings when processing locally stored events --- .../java/at/bitfire/ical4android/AndroidEvent.kt | 12 +++++++----- src/main/java/at/bitfire/ical4android/MiscUtils.kt | 6 ++++-- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/src/main/java/at/bitfire/ical4android/AndroidEvent.kt b/src/main/java/at/bitfire/ical4android/AndroidEvent.kt index 9836fb4..90ff0e5 100644 --- a/src/main/java/at/bitfire/ical4android/AndroidEvent.kt +++ b/src/main/java/at/bitfire/ical4android/AndroidEvent.kt @@ -110,14 +110,16 @@ abstract class AndroidEvent( field = event val e = iterEvents.next() - populateEvent(e.entityValues) + populateEvent(MiscUtils.removeEmptyStrings(e.entityValues)) - for (subValue in e.subValues) + for (subValue in e.subValues) { + val subValues = MiscUtils.removeEmptyStrings(subValue.values) when (subValue.uri) { - Attendees.CONTENT_URI -> populateAttendee(subValue.values) - Reminders.CONTENT_URI -> populateReminder(subValue.values) - ExtendedProperties.CONTENT_URI -> populateExtended(subValue.values) + Attendees.CONTENT_URI -> populateAttendee(subValues) + Reminders.CONTENT_URI -> populateReminder(subValues) + ExtendedProperties.CONTENT_URI -> populateExtended(subValues) } + } populateExceptions() useRetainedClassification() diff --git a/src/main/java/at/bitfire/ical4android/MiscUtils.kt b/src/main/java/at/bitfire/ical4android/MiscUtils.kt index 5b004bb..d2b7ae3 100644 --- a/src/main/java/at/bitfire/ical4android/MiscUtils.kt +++ b/src/main/java/at/bitfire/ical4android/MiscUtils.kt @@ -85,15 +85,17 @@ object MiscUtils { /** * Removes empty [String] values from [values]. * - * @param values set of values to be processed + * @param values set of values to be modified + * @return the modified object (which is the same object as passed in; for chaining) */ - fun removeEmptyStrings(values: ContentValues) { + fun removeEmptyStrings(values: ContentValues): ContentValues { val it = values.keySet().iterator() while (it.hasNext()) { val obj = values[it.next()] if (obj is String && obj.isEmpty()) it.remove() } + return values } -- GitLab From 9459f80ddf32dec83969848428b949a649ff2502 Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Fri, 22 Nov 2019 21:00:17 +0100 Subject: [PATCH 49/58] Apply ical4j rules to change Outlook timezone IDs to more Android-friendly values --- build.gradle | 2 +- .../java/at/bitfire/ical4android/Event.kt | 7 ++ .../bitfire/ical4android/ICalPreprocessor.kt | 47 ++++++++++++ .../java/at/bitfire/ical4android/MiscUtils.kt | 2 +- .../java/at/bitfire/ical4android/EventTest.kt | 4 +- .../ical4android/ICalPreprocessorTest.kt | 25 +++++++ src/test/resources/events/outlook1.ics | 72 +++++++++++++++++++ 7 files changed, 155 insertions(+), 4 deletions(-) create mode 100644 src/main/java/at/bitfire/ical4android/ICalPreprocessor.kt create mode 100644 src/test/java/at/bitfire/ical4android/ICalPreprocessorTest.kt create mode 100644 src/test/resources/events/outlook1.ics diff --git a/build.gradle b/build.gradle index 4b41001..cf155e3 100644 --- a/build.gradle +++ b/build.gradle @@ -1,7 +1,7 @@ buildscript { ext.versions = [ - kotlin: '1.3.50', + kotlin: '1.3.60', dokka: '0.10.0', ical4j: '2.2.6' ] diff --git a/src/main/java/at/bitfire/ical4android/Event.kt b/src/main/java/at/bitfire/ical4android/Event.kt index b915798..4efc660 100644 --- a/src/main/java/at/bitfire/ical4android/Event.kt +++ b/src/main/java/at/bitfire/ical4android/Event.kt @@ -21,6 +21,7 @@ import java.io.IOException import java.io.OutputStream import java.io.Reader import java.util.* +import java.util.logging.Level class Event: ICalendar() { @@ -82,6 +83,12 @@ class Event: ICalendar() { throw InvalidCalendarException("iCalendar object contains invalid value", e) } + try { + ICalPreprocessor.preProcess(ical) + } catch (e: Exception) { + Constants.log.log(Level.WARNING, "Couldn't pre-process iCalendar", e) + } + // fill calendar properties properties?.let { ical.getProperty(CALENDAR_NAME)?.let { calName -> diff --git a/src/main/java/at/bitfire/ical4android/ICalPreprocessor.kt b/src/main/java/at/bitfire/ical4android/ICalPreprocessor.kt new file mode 100644 index 0000000..cd97032 --- /dev/null +++ b/src/main/java/at/bitfire/ical4android/ICalPreprocessor.kt @@ -0,0 +1,47 @@ +package at.bitfire.ical4android + +import net.fortuna.ical4j.model.Calendar +import net.fortuna.ical4j.model.Property +import net.fortuna.ical4j.transform.rfc5545.DateListPropertyRule +import net.fortuna.ical4j.transform.rfc5545.DatePropertyRule +import net.fortuna.ical4j.transform.rfc5545.Rfc5545PropertyRule +import java.util.logging.Level + +/** + * Applies some rules to increase compatibility or parsed iCalendars: + * + * - [DatePropertyRule], [DateListPropertyRule]: to rename Outlook-specific TZID parameters + * (like "W. Europe Standard Time" to an Android-friendly name like "Europe/Vienna") + * + */ +object ICalPreprocessor { + + private val propertyRules = arrayOf( + DatePropertyRule(), + DateListPropertyRule() + ) + + /** + * Applies the set of rules (see class definition) to a given calendar object. + * + * @param calendar the calendar object that is going to be modified + */ + fun preProcess(calendar: Calendar) { + for (component in calendar.components) { + for (property in component.properties) + applyRules(property) + } + } + + @Suppress("UNCHECKED_CAST") + private fun applyRules(property: Property) { + propertyRules + .filter { rule -> rule.supportedType.isAssignableFrom(property::class.java) } + .forEach { + Constants.log.log(Level.INFO, "Applying rules to ${property.toString()}") + (it as Rfc5545PropertyRule).applyTo(property) + Constants.log.log(Level.INFO, "-> ${property.toString()}") + } + } + +} \ No newline at end of file diff --git a/src/main/java/at/bitfire/ical4android/MiscUtils.kt b/src/main/java/at/bitfire/ical4android/MiscUtils.kt index d2b7ae3..548738c 100644 --- a/src/main/java/at/bitfire/ical4android/MiscUtils.kt +++ b/src/main/java/at/bitfire/ical4android/MiscUtils.kt @@ -30,7 +30,7 @@ object MiscUtils { val tzID = tz.id ?: return val deviceTzID = DateUtils.findAndroidTimezoneID(tzID) if (tzID != deviceTzID) { - Constants.log.warning("Android doesn't know time zone \"$tzID\", storing event in time zone \"$deviceTzID\"") + Constants.log.warning("Android doesn't know time zone \"$tzID\", assuming device time zone \"$deviceTzID\"") date.timeZone = DateUtils.tzRegistry.getTimeZone(deviceTzID) } } diff --git a/src/test/java/at/bitfire/ical4android/EventTest.kt b/src/test/java/at/bitfire/ical4android/EventTest.kt index f1b8d5c..2db7b7e 100644 --- a/src/test/java/at/bitfire/ical4android/EventTest.kt +++ b/src/test/java/at/bitfire/ical4android/EventTest.kt @@ -102,9 +102,9 @@ class EventTest { // event with start+end date-time val eViennaEvolution = parseCalendar("vienna-evolution.ics").first() assertEquals(1381330800000L, eViennaEvolution.dtStart!!.date.time) - assertEquals("/freeassociation.sourceforge.net/Tzfile/Europe/Vienna", eViennaEvolution.dtStart!!.timeZone.id) + assertEquals("Europe/Vienna", eViennaEvolution.dtStart!!.timeZone.id) assertEquals(1381334400000L, eViennaEvolution.dtEnd!!.date.time) - assertEquals("/freeassociation.sourceforge.net/Tzfile/Europe/Vienna", eViennaEvolution.dtEnd!!.timeZone.id) + assertEquals("Europe/Vienna", eViennaEvolution.dtEnd!!.timeZone.id) } @Test diff --git a/src/test/java/at/bitfire/ical4android/ICalPreprocessorTest.kt b/src/test/java/at/bitfire/ical4android/ICalPreprocessorTest.kt new file mode 100644 index 0000000..d88e04a --- /dev/null +++ b/src/test/java/at/bitfire/ical4android/ICalPreprocessorTest.kt @@ -0,0 +1,25 @@ +package at.bitfire.ical4android + +import net.fortuna.ical4j.data.CalendarBuilder +import net.fortuna.ical4j.model.Component +import net.fortuna.ical4j.model.component.VEvent +import org.junit.Assert.assertEquals +import org.junit.Test +import java.io.InputStreamReader + +class ICalPreprocessorTest { + + @Test + fun testMsTimeZones() { + javaClass.classLoader!!.getResourceAsStream("events/outlook1.ics").use { stream -> + val reader = InputStreamReader(stream, Charsets.UTF_8) + val calendar = CalendarBuilder().build(reader) + val vEvent = calendar.getComponent(Component.VEVENT) as VEvent + + assertEquals("W. Europe Standard Time", vEvent.startDate.timeZone.id) + ICalPreprocessor.preProcess(calendar) + assertEquals("Europe/Vienna", vEvent.startDate.timeZone.id) + } + } + +} \ No newline at end of file diff --git a/src/test/resources/events/outlook1.ics b/src/test/resources/events/outlook1.ics new file mode 100644 index 0000000..000afaa --- /dev/null +++ b/src/test/resources/events/outlook1.ics @@ -0,0 +1,72 @@ +BEGIN:VCALENDAR +METHOD:PUBLISH +PRODID:Microsoft Exchange Server 2010 +VERSION:2.0 +X-WR-CALNAME:Calendar +BEGIN:VTIMEZONE +TZID:China Standard Time +BEGIN:STANDARD +DTSTART:16010101T000000 +TZOFFSETFROM:+0800 +TZOFFSETTO:+0800 +END:STANDARD +BEGIN:DAYLIGHT +DTSTART:16010101T000000 +TZOFFSETFROM:+0800 +TZOFFSETTO:+0800 +END:DAYLIGHT +END:VTIMEZONE +BEGIN:VTIMEZONE +TZID:W. Europe Standard Time +BEGIN:STANDARD +DTSTART:16010101T030000 +TZOFFSETFROM:+0200 +TZOFFSETTO:+0100 +RRULE:FREQ=YEARLY;INTERVAL=1;BYDAY=-1SU;BYMONTH=10 +END:STANDARD +BEGIN:DAYLIGHT +DTSTART:16010101T020000 +TZOFFSETFROM:+0100 +TZOFFSETTO:+0200 +RRULE:FREQ=YEARLY;INTERVAL=1;BYDAY=-1SU;BYMONTH=3 +END:DAYLIGHT +END:VTIMEZONE +BEGIN:VTIMEZONE +TZID:India Standard Time +BEGIN:STANDARD +DTSTART:16010101T000000 +TZOFFSETFROM:+0530 +TZOFFSETTO:+0530 +END:STANDARD +BEGIN:DAYLIGHT +DTSTART:16010101T000000 +TZOFFSETFROM:+0530 +TZOFFSETTO:+0530 +END:DAYLIGHT +END:VTIMEZONE +BEGIN:VEVENT +DESCRIPTION:\n............................................................. + .................................\n\n\n +RRULE:FREQ=WEEKLY;UNTIL=20191218T080000Z;INTERVAL=1;BYDAY=WE;WKST=MO +UID:040000008200E00074C5B7101A82E00800000000907682BE2B88D501000000000000000 + 01000000077F6CDA3B634104B9BC1ED539119F558 +SUMMARY:Weekly Meeting - Test +DTSTART;TZID=W. Europe Standard Time:20191023T090000 +DTEND;TZID=W. Europe Standard Time:20191023T093000 +CLASS:PUBLIC +PRIORITY:5 +DTSTAMP:20191119T090349Z +TRANSP:OPAQUE +STATUS:CONFIRMED +SEQUENCE:1 +LOCATION:Skype-Besprechung +X-MICROSOFT-CDO-APPT-SEQUENCE:1 +X-MICROSOFT-CDO-BUSYSTATUS:BUSY +X-MICROSOFT-CDO-INTENDEDSTATUS:BUSY +X-MICROSOFT-CDO-ALLDAYEVENT:FALSE +X-MICROSOFT-CDO-IMPORTANCE:1 +X-MICROSOFT-CDO-INSTTYPE:1 +X-MICROSOFT-DONOTFORWARDMEETING:FALSE +X-MICROSOFT-DISALLOW-COUNTER:FALSE +END:VEVENT +END:VCALENDAR -- GitLab From e6cca0765812cc62a17af2ade98c55f983410d11 Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Sun, 24 Nov 2019 15:32:50 +0100 Subject: [PATCH 50/58] Unify VEVENT/VTODO parsing --- .../java/at/bitfire/ical4android/Event.kt | 45 +++++----------- .../java/at/bitfire/ical4android/ICalendar.kt | 53 +++++++++++++++++++ src/main/java/at/bitfire/ical4android/Task.kt | 27 ++++------ .../java/at/bitfire/ical4android/EventTest.kt | 6 +-- .../java/at/bitfire/ical4android/TaskTest.kt | 4 +- 5 files changed, 81 insertions(+), 54 deletions(-) diff --git a/src/main/java/at/bitfire/ical4android/Event.kt b/src/main/java/at/bitfire/ical4android/Event.kt index 4efc660..212aa17 100644 --- a/src/main/java/at/bitfire/ical4android/Event.kt +++ b/src/main/java/at/bitfire/ical4android/Event.kt @@ -8,7 +8,7 @@ package at.bitfire.ical4android -import net.fortuna.ical4j.data.CalendarBuilder +import at.bitfire.ical4android.ICalendar.Companion.CALENDAR_NAME import net.fortuna.ical4j.data.CalendarOutputter import net.fortuna.ical4j.data.ParserException import net.fortuna.ical4j.model.* @@ -21,7 +21,6 @@ import java.io.IOException import java.io.OutputStream import java.io.Reader import java.util.* -import java.util.logging.Level class Event: ICalendar() { @@ -59,42 +58,22 @@ class Event: ICalendar() { val unknownProperties = LinkedList() companion object { - const val CALENDAR_NAME = "X-WR-CALNAME" - /** - * Parses an InputStream that contains iCalendar VEVENTs. + * Parses an iCalendar resource, applies [ICalPreprocessor] to increase compatibility + * and extracts the VEVENTs. + * + * @param reader where the iCalendar is taken from + * @param properties Known iCalendar properties (like [CALENDAR_NAME]) will be put into this map. Key: property name; value: property value + * + * @return array of filled [Event] data objects (may have size 0) * - * @param reader reader for the input stream containing the VEVENTs (pay attention to the charset) - * @param properties map of properties, will be filled with CALENDAR_* values, if applicable (may be null) - * @return array of filled Event data objects (may have size 0) – doesn't return null + * @throws ParserException when the iCalendar can't be parsed + * @throws IllegalArgumentException when the iCalendar resource contains an invalid value * @throws IOException on I/O errors * @throws InvalidCalendarException on parsing exceptions */ - fun fromReader(reader: Reader, properties: MutableMap? = null): List { - Constants.log.fine("Parsing iCalendar stream") - - // parse stream - val ical: Calendar - try { - ical = CalendarBuilder().build(reader) - } catch(e: ParserException) { - throw InvalidCalendarException("Couldn't parse iCalendar object", e) - } catch(e: IllegalArgumentException) { - throw InvalidCalendarException("iCalendar object contains invalid value", e) - } - - try { - ICalPreprocessor.preProcess(ical) - } catch (e: Exception) { - Constants.log.log(Level.WARNING, "Couldn't pre-process iCalendar", e) - } - - // fill calendar properties - properties?.let { - ical.getProperty(CALENDAR_NAME)?.let { calName -> - properties[CALENDAR_NAME] = calName.value - } - } + fun eventsFromReader(reader: Reader, properties: MutableMap? = null): List { + val ical = fromReader(reader, properties) // process VEVENTs val vEvents = ical.getComponents(Component.VEVENT) diff --git a/src/main/java/at/bitfire/ical4android/ICalendar.kt b/src/main/java/at/bitfire/ical4android/ICalendar.kt index 3169211..5177f7f 100644 --- a/src/main/java/at/bitfire/ical4android/ICalendar.kt +++ b/src/main/java/at/bitfire/ical4android/ICalendar.kt @@ -10,12 +10,14 @@ package at.bitfire.ical4android import net.fortuna.ical4j.data.CalendarBuilder import net.fortuna.ical4j.data.ParserException +import net.fortuna.ical4j.model.Calendar import net.fortuna.ical4j.model.Date import net.fortuna.ical4j.model.DateTime import net.fortuna.ical4j.model.component.* import net.fortuna.ical4j.model.property.DateProperty import net.fortuna.ical4j.model.property.ProdId import net.fortuna.ical4j.model.property.TzUrl +import java.io.Reader import java.io.StringReader import java.util.* import java.util.logging.Level @@ -27,6 +29,7 @@ open class ICalendar { var sequence: Int? = null companion object { + // static ical4j initialization init { // reduce verbosity of those two loggers @@ -36,9 +39,59 @@ open class ICalendar { Logger.getLogger(net.fortuna.ical4j.model.Recur::class.java.name).level = Level.CONFIG } + // known iCalendar properties + const val CALENDAR_NAME = "X-WR-CALNAME" + + /** + * Default PRODID used when generating iCalendars. If you want another value, set it + * statically before writing the first iCalendar. + */ var prodId = ProdId("+//IDN bitfire.at//ical4android") + // parser + + /** + * Parses an iCalendar resource and applies [ICalPreprocessor] to increase compatibility. + * + * @param reader where the iCalendar is taken from + * @param properties Known iCalendar properties (like [CALENDAR_NAME]) will be put into this map. Key: property name; value: property value + * + * @return parsed iCalendar resource + * @throws ParserException when the iCalendar can't be parsed + * @throws IllegalArgumentException when the iCalendar resource contains an invalid value + */ + fun fromReader(reader: Reader, properties: MutableMap? = null): Calendar { + Constants.log.fine("Parsing iCalendar stream") + + // parse stream + val calendar: Calendar + try { + calendar = CalendarBuilder().build(reader) + } catch(e: ParserException) { + throw InvalidCalendarException("Couldn't parse iCalendar", e) + } catch(e: IllegalArgumentException) { + throw InvalidCalendarException("iCalendar contains invalid value", e) + } + + // apply ICalPreprocessor for increased compatibility + try { + ICalPreprocessor.preProcess(calendar) + } catch (e: Exception) { + Constants.log.log(Level.WARNING, "Couldn't pre-process iCalendar", e) + } + + // fill calendar properties + properties?.let { + calendar.getProperty(CALENDAR_NAME)?.let { calName -> + properties[CALENDAR_NAME] = calName.value + } + } + + return calendar + } + + // time zone helpers fun isDateTime(date: DateProperty?) = date != null && date.date is DateTime diff --git a/src/main/java/at/bitfire/ical4android/Task.kt b/src/main/java/at/bitfire/ical4android/Task.kt index ddce17c..56880dc 100644 --- a/src/main/java/at/bitfire/ical4android/Task.kt +++ b/src/main/java/at/bitfire/ical4android/Task.kt @@ -11,7 +11,6 @@ package at.bitfire.ical4android import at.bitfire.ical4android.MiscUtils.TextListHelper.toList -import net.fortuna.ical4j.data.CalendarBuilder import net.fortuna.ical4j.data.CalendarOutputter import net.fortuna.ical4j.data.ParserException import net.fortuna.ical4j.model.* @@ -64,23 +63,19 @@ class Task: ICalendar() { companion object { /** - * Parses an InputStream that contains iCalendar VTODOs. + * Parses an iCalendar resource, applies [ICalPreprocessor] to increase compatibility + * and extracts the VTODOs. * - * @param reader reader for the input stream containing the VTODOs (pay attention to the charset) - * @return array of filled Task data objects (may have size 0) – doesn't return null - * @throws IOException - * @throws InvalidCalendarException on parser exceptions + * @param reader where the iCalendar is taken from + * + * @return array of filled [Task] data objects (may have size 0) + * + * @throws ParserException when the iCalendar can't be parsed + * @throws IllegalArgumentException when the iCalendar resource contains an invalid value + * @throws IOException on I/O errors */ - fun fromReader(reader: Reader): List { - val ical: Calendar - try { - ical = CalendarBuilder().build(reader) - } catch(e: ParserException) { - throw InvalidCalendarException("Couldn't parse iCalendar object", e) - } catch(e: IllegalArgumentException) { - throw InvalidCalendarException("iCalendar object contains invalid value", e) - } - + fun tasksFromReader(reader: Reader): List { + val ical = fromReader(reader) val vToDos = ical.getComponents(Component.VTODO) return vToDos.mapTo(LinkedList()) { this.fromVToDo(it) } } diff --git a/src/test/java/at/bitfire/ical4android/EventTest.kt b/src/test/java/at/bitfire/ical4android/EventTest.kt index 2db7b7e..be8b419 100644 --- a/src/test/java/at/bitfire/ical4android/EventTest.kt +++ b/src/test/java/at/bitfire/ical4android/EventTest.kt @@ -21,9 +21,9 @@ class EventTest { fun testCalendarProperties() { javaClass.classLoader!!.getResourceAsStream("events/multiple.ics").use { stream -> val properties = mutableMapOf() - Event.fromReader(InputStreamReader(stream, Charsets.UTF_8), properties) + Event.eventsFromReader(InputStreamReader(stream, Charsets.UTF_8), properties) assertEquals(1, properties.size) - assertEquals("Test-Kalender", properties[Event.CALENDAR_NAME]) + assertEquals("Test-Kalender", properties[ICalendar.CALENDAR_NAME]) } } @@ -203,7 +203,7 @@ class EventTest { private fun parseCalendar(fname: String, charset: Charset = Charsets.UTF_8): List = javaClass.classLoader!!.getResourceAsStream("events/$fname").use { stream -> - return Event.fromReader(InputStreamReader(stream, charset)) + return Event.eventsFromReader(InputStreamReader(stream, charset)) } } diff --git a/src/test/java/at/bitfire/ical4android/TaskTest.kt b/src/test/java/at/bitfire/ical4android/TaskTest.kt index 1e3e020..91a5fa6 100644 --- a/src/test/java/at/bitfire/ical4android/TaskTest.kt +++ b/src/test/java/at/bitfire/ical4android/TaskTest.kt @@ -110,14 +110,14 @@ class TaskTest { private fun parseCalendar(fname: String, charset: Charset = Charsets.UTF_8): Task { javaClass.classLoader!!.getResourceAsStream("tasks/$fname").use { stream -> - return Task.fromReader(InputStreamReader(stream, charset)).first() + return Task.tasksFromReader(InputStreamReader(stream, charset)).first() } } private fun regenerate(t: Task): Task { val os = ByteArrayOutputStream() t.write(os) - return Task.fromReader(InputStreamReader(ByteArrayInputStream(os.toByteArray()), Charsets.UTF_8)).first() + return Task.tasksFromReader(InputStreamReader(ByteArrayInputStream(os.toByteArray()), Charsets.UTF_8)).first() } } -- GitLab From cc4bcc614b19a621b486cfcfca8581519ec474f4 Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Mon, 25 Nov 2019 18:12:21 +0100 Subject: [PATCH 51/58] Add DTSTAMP to generated VEVENTs again --- .../java/at/bitfire/ical4android/Event.kt | 13 +++++++-- .../bitfire/ical4android/ICalPreprocessor.kt | 4 +-- src/main/java/at/bitfire/ical4android/Task.kt | 26 ++++++++--------- .../java/at/bitfire/ical4android/EventTest.kt | 29 +++++++++++++++++++ .../java/at/bitfire/ical4android/TaskTest.kt | 26 +++++++++++++++++ 5 files changed, 80 insertions(+), 18 deletions(-) diff --git a/src/main/java/at/bitfire/ical4android/Event.kt b/src/main/java/at/bitfire/ical4android/Event.kt index 212aa17..46c3ded 100644 --- a/src/main/java/at/bitfire/ical4android/Event.kt +++ b/src/main/java/at/bitfire/ical4android/Event.kt @@ -238,10 +238,15 @@ class Event: ICalendar() { * @return generated VEvent */ private fun toVEvent(): VEvent { - val props = PropertyList() + val event = VEvent(true /* generates DTSTAMP */) + val props = event.properties props += Uid(uid) + recurrenceId?.let { props += it } - sequence?.let { if (it != 0) props += Sequence(it) } + sequence?.let { + if (it != 0) + props += Sequence(it) + } summary?.let { props += Summary(it) } location?.let { props += Location(it) } @@ -269,7 +274,9 @@ class Event: ICalendar() { lastModified?.let { props += it } - return VEvent(props, ComponentList(alarms)) + event.alarms.addAll(alarms) + + return event } diff --git a/src/main/java/at/bitfire/ical4android/ICalPreprocessor.kt b/src/main/java/at/bitfire/ical4android/ICalPreprocessor.kt index cd97032..0b90c68 100644 --- a/src/main/java/at/bitfire/ical4android/ICalPreprocessor.kt +++ b/src/main/java/at/bitfire/ical4android/ICalPreprocessor.kt @@ -38,9 +38,9 @@ object ICalPreprocessor { propertyRules .filter { rule -> rule.supportedType.isAssignableFrom(property::class.java) } .forEach { - Constants.log.log(Level.INFO, "Applying rules to ${property.toString()}") + Constants.log.log(Level.FINER, "Applying rules to ${property.toString()}") (it as Rfc5545PropertyRule).applyTo(property) - Constants.log.log(Level.INFO, "-> ${property.toString()}") + Constants.log.log(Level.FINER, "-> ${property.toString()}") } } diff --git a/src/main/java/at/bitfire/ical4android/Task.kt b/src/main/java/at/bitfire/ical4android/Task.kt index 56880dc..5c1a82a 100644 --- a/src/main/java/at/bitfire/ical4android/Task.kt +++ b/src/main/java/at/bitfire/ical4android/Task.kt @@ -16,7 +16,6 @@ import net.fortuna.ical4j.data.ParserException import net.fortuna.ical4j.model.* import net.fortuna.ical4j.model.Calendar import net.fortuna.ical4j.model.TimeZone -import net.fortuna.ical4j.model.component.CalendarComponent import net.fortuna.ical4j.model.component.VAlarm import net.fortuna.ical4j.model.component.VToDo import net.fortuna.ical4j.model.property.* @@ -140,9 +139,19 @@ class Task: ICalendar() { fun write(os: OutputStream) { - val props = PropertyList() + val ical = Calendar() + ical.properties += Version.VERSION_2_0 + ical.properties += prodId + + val vTodo = VToDo(true /* generates DTSTAMP */) + ical.components += vTodo + val props = vTodo.properties + uid?.let { props += Uid(uid) } - sequence?.let { if (it != 0) props += Sequence(sequence as Int) } + sequence?.let { + if (it != 0) + props += Sequence(it) + } createdAt?.let { props += Created(DateTime(it)) } lastModified?.let { props += LastModified(DateTime(it)) } @@ -192,20 +201,11 @@ class Task: ICalendar() { } percentComplete?.let { props += PercentComplete(it) } - // generate VTODO - val iCalProps = PropertyList(2) - iCalProps += Version.VERSION_2_0 - iCalProps += prodId - - val vTodo = VToDo(props) if (alarms.isNotEmpty()) vTodo.alarms.addAll(alarms) - val iCalComponents = ComponentList(2) - iCalComponents.add(vTodo) - iCalComponents.addAll(usedTimeZones.map { it.vTimeZone }) + ical.components.addAll(usedTimeZones.map { it.vTimeZone }) - val ical = Calendar(iCalProps, iCalComponents) CalendarOutputter(false).output(ical, os) } diff --git a/src/test/java/at/bitfire/ical4android/EventTest.kt b/src/test/java/at/bitfire/ical4android/EventTest.kt index be8b419..2f4ca91 100644 --- a/src/test/java/at/bitfire/ical4android/EventTest.kt +++ b/src/test/java/at/bitfire/ical4android/EventTest.kt @@ -7,8 +7,13 @@ */ package at.bitfire.ical4android +import net.fortuna.ical4j.model.Dur +import net.fortuna.ical4j.model.TimeZoneRegistryFactory +import net.fortuna.ical4j.model.component.VAlarm +import net.fortuna.ical4j.model.property.DtStart import org.junit.Assert.* import org.junit.Test +import java.io.ByteArrayOutputStream import java.io.FileNotFoundException import java.io.InputStreamReader import java.nio.charset.Charset @@ -153,6 +158,30 @@ class EventTest { } + /* generating */ + + @Test + fun testWrite() { + val e = Event() + e.uid = "SAMPLEUID" + e.dtStart = DtStart("20190101T100000", TimeZoneRegistryFactory.getInstance().createRegistry().getTimeZone("Europe/Berlin")) + e.alarms += VAlarm(Dur(0, -1, 0, 0)) + + val os = ByteArrayOutputStream() + e.write(os) + val raw = os.toString(Charsets.UTF_8.name()) + + assertTrue(raw.contains("PRODID:${ICalendar.prodId.value}")) + assertTrue(raw.contains("UID:SAMPLEUID")) + assertTrue(raw.contains("DTSTART;TZID=Europe/Berlin:20190101T100000")) + assertTrue(raw.contains("DTSTAMP:")) + assertTrue(raw.contains("BEGIN:VALARM\r\n" + + "TRIGGER:-PT1H\r\n" + + "END:VALARM\r\n")) + assertTrue(raw.contains("BEGIN:VTIMEZONE")) + } + + /* internal tests */ @Test diff --git a/src/test/java/at/bitfire/ical4android/TaskTest.kt b/src/test/java/at/bitfire/ical4android/TaskTest.kt index 91a5fa6..778d06b 100644 --- a/src/test/java/at/bitfire/ical4android/TaskTest.kt +++ b/src/test/java/at/bitfire/ical4android/TaskTest.kt @@ -9,9 +9,11 @@ package at.bitfire.ical4android import net.fortuna.ical4j.model.* +import net.fortuna.ical4j.model.component.VAlarm import net.fortuna.ical4j.model.parameter.RelType import net.fortuna.ical4j.model.parameter.Value import net.fortuna.ical4j.model.property.* +import net.fortuna.ical4j.util.TimeZones import org.junit.Assert.* import org.junit.Test import java.io.ByteArrayInputStream @@ -106,6 +108,30 @@ class TaskTest { } + /* generating */ + + @Test + fun testWrite() { + val t = Task() + t.uid = "SAMPLEUID" + t.dtStart = DtStart("20190101T100000", TimeZoneRegistryFactory.getInstance().createRegistry().getTimeZone("Europe/Berlin")) + t.alarms += VAlarm(Dur(0, -1, 0, 0)) + + val os = ByteArrayOutputStream() + t.write(os) + val raw = os.toString(Charsets.UTF_8.name()) + + assertTrue(raw.contains("PRODID:${ICalendar.prodId.value}")) + assertTrue(raw.contains("UID:SAMPLEUID")) + assertTrue(raw.contains("DTSTAMP:")) + assertTrue(raw.contains("DTSTART;TZID=Europe/Berlin:20190101T100000")) + assertTrue(raw.contains("BEGIN:VALARM\r\n" + + "TRIGGER:-PT1H\r\n" + + "END:VALARM\r\n")) + assertTrue(raw.contains("BEGIN:VTIMEZONE")) + } + + /* helpers */ private fun parseCalendar(fname: String, charset: Charset = Charsets.UTF_8): Task { -- GitLab From ab2c11377c7095ab1269f1f1021dd9741178e3d9 Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Mon, 25 Nov 2019 23:50:40 +0100 Subject: [PATCH 52/58] Validate generated VEVENT/VTODOs - debug builds: ValidationExceptions are hard errors - release builds: ValidationExceptions are catched and logged as warning --- .../java/at/bitfire/ical4android/Event.kt | 1 + .../java/at/bitfire/ical4android/ICalendar.kt | 24 ++++++++++++++++++- src/main/java/at/bitfire/ical4android/Task.kt | 1 + src/main/resources/ical4j.properties | 1 - .../java/at/bitfire/ical4android/TaskTest.kt | 6 ++++- src/test/resources/tasks/rfc5545-sample1.ics | 2 +- 6 files changed, 31 insertions(+), 4 deletions(-) diff --git a/src/main/java/at/bitfire/ical4android/Event.kt b/src/main/java/at/bitfire/ical4android/Event.kt index 46c3ded..d8c84ff 100644 --- a/src/main/java/at/bitfire/ical4android/Event.kt +++ b/src/main/java/at/bitfire/ical4android/Event.kt @@ -229,6 +229,7 @@ class Event: ICalendar() { ical.components += tz } + softValidate(ical) CalendarOutputter(false).output(ical, os) } diff --git a/src/main/java/at/bitfire/ical4android/ICalendar.kt b/src/main/java/at/bitfire/ical4android/ICalendar.kt index 5177f7f..ba9c559 100644 --- a/src/main/java/at/bitfire/ical4android/ICalendar.kt +++ b/src/main/java/at/bitfire/ical4android/ICalendar.kt @@ -17,6 +17,7 @@ import net.fortuna.ical4j.model.component.* import net.fortuna.ical4j.model.property.DateProperty import net.fortuna.ical4j.model.property.ProdId import net.fortuna.ical4j.model.property.TzUrl +import net.fortuna.ical4j.validate.ValidationException import java.io.Reader import java.io.StringReader import java.util.* @@ -32,11 +33,15 @@ open class ICalendar { // static ical4j initialization init { - // reduce verbosity of those two loggers + // reduce verbosity of various ical4j loggers org.slf4j.LoggerFactory.getLogger(net.fortuna.ical4j.data.CalendarParserImpl::class.java) Logger.getLogger(net.fortuna.ical4j.data.CalendarParserImpl::class.java.name).level = Level.CONFIG + org.slf4j.LoggerFactory.getLogger(net.fortuna.ical4j.model.Recur::class.java) Logger.getLogger(net.fortuna.ical4j.model.Recur::class.java.name).level = Level.CONFIG + + org.slf4j.LoggerFactory.getLogger(net.fortuna.ical4j.data.FoldingWriter::class.java) + Logger.getLogger(net.fortuna.ical4j.data.FoldingWriter::class.java.name).level = Level.CONFIG } // known iCalendar properties @@ -167,6 +172,23 @@ open class ICalendar { return null } + /** + * Validates an iCalendar resource and catches/logs a potential [ValidationException]. + * + * @param ical iCalendar resource to be validated + */ + fun softValidate(ical: Calendar) { + try { + ical.validate(true) + } catch (e: ValidationException) { + if (BuildConfig.DEBUG) + // debug build, re-throw ValidationException + throw e + else + Constants.log.log(Level.WARNING, "iCalendar validation failed - This is only a warning!", e) + } + } + // misc. iCalendar helpers diff --git a/src/main/java/at/bitfire/ical4android/Task.kt b/src/main/java/at/bitfire/ical4android/Task.kt index 5c1a82a..237fc85 100644 --- a/src/main/java/at/bitfire/ical4android/Task.kt +++ b/src/main/java/at/bitfire/ical4android/Task.kt @@ -206,6 +206,7 @@ class Task: ICalendar() { ical.components.addAll(usedTimeZones.map { it.vTimeZone }) + softValidate(ical) CalendarOutputter(false).output(ical, os) } diff --git a/src/main/resources/ical4j.properties b/src/main/resources/ical4j.properties index cf9d49b..dfa5830 100644 --- a/src/main/resources/ical4j.properties +++ b/src/main/resources/ical4j.properties @@ -2,5 +2,4 @@ net.fortuna.ical4j.timezone.cache.impl=net.fortuna.ical4j.util.MapTimeZoneCache net.fortuna.ical4j.timezone.update.enabled=false ical4j.parsing.relaxed=true ical4j.unfolding.relaxed=true -ical4j.validation.relaxed=true ical4j.compatibility.outlook=true diff --git a/src/test/java/at/bitfire/ical4android/TaskTest.kt b/src/test/java/at/bitfire/ical4android/TaskTest.kt index 778d06b..5ebcae5 100644 --- a/src/test/java/at/bitfire/ical4android/TaskTest.kt +++ b/src/test/java/at/bitfire/ical4android/TaskTest.kt @@ -115,7 +115,10 @@ class TaskTest { val t = Task() t.uid = "SAMPLEUID" t.dtStart = DtStart("20190101T100000", TimeZoneRegistryFactory.getInstance().createRegistry().getTimeZone("Europe/Berlin")) - t.alarms += VAlarm(Dur(0, -1, 0, 0)) + + val alarm = VAlarm(Dur(0, -1, 0, 0)) + alarm.properties += Action.AUDIO + t.alarms += alarm val os = ByteArrayOutputStream() t.write(os) @@ -127,6 +130,7 @@ class TaskTest { assertTrue(raw.contains("DTSTART;TZID=Europe/Berlin:20190101T100000")) assertTrue(raw.contains("BEGIN:VALARM\r\n" + "TRIGGER:-PT1H\r\n" + + "ACTION:AUDIO\r\n" + "END:VALARM\r\n")) assertTrue(raw.contains("BEGIN:VTIMEZONE")) } diff --git a/src/test/resources/tasks/rfc5545-sample1.ics b/src/test/resources/tasks/rfc5545-sample1.ics index 7f797ad..18d53df 100644 --- a/src/test/resources/tasks/rfc5545-sample1.ics +++ b/src/test/resources/tasks/rfc5545-sample1.ics @@ -12,7 +12,7 @@ STATUS:NEEDS-ACTION SUMMARY:Submit Income Taxes BEGIN:VALARM ACTION:AUDIO -TRIGGER:19980403T120000Z +TRIGGER;VALUE=DATE-TIME:19980403T120000Z ATTACH;FMTTYPE=audio/basic:http://example.com/pub/audio- files/ssbanner.aud REPEAT:4 -- GitLab From 1fcb759079f953779ec3f1cc451a47e9849af468 Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Tue, 26 Nov 2019 18:05:12 +0100 Subject: [PATCH 53/58] Very minor refactoring --- src/main/java/at/bitfire/ical4android/AndroidEvent.kt | 1 - src/main/java/at/bitfire/ical4android/ICalendar.kt | 7 ++++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/main/java/at/bitfire/ical4android/AndroidEvent.kt b/src/main/java/at/bitfire/ical4android/AndroidEvent.kt index 90ff0e5..1d491ac 100644 --- a/src/main/java/at/bitfire/ical4android/AndroidEvent.kt +++ b/src/main/java/at/bitfire/ical4android/AndroidEvent.kt @@ -256,7 +256,6 @@ abstract class AndroidEvent( protected open fun populateAttendee(row: ContentValues) { Constants.log.log(Level.FINE, "Read event attendee from calender provider", row) - MiscUtils.removeEmptyStrings(row) try { val attendee: Attendee diff --git a/src/main/java/at/bitfire/ical4android/ICalendar.kt b/src/main/java/at/bitfire/ical4android/ICalendar.kt index ba9c559..c6324db 100644 --- a/src/main/java/at/bitfire/ical4android/ICalendar.kt +++ b/src/main/java/at/bitfire/ical4android/ICalendar.kt @@ -173,9 +173,14 @@ open class ICalendar { } /** - * Validates an iCalendar resource and catches/logs a potential [ValidationException]. + * Validates an iCalendar resource. + * + * Debug builds only: throws [ValidationException] when the resource is invalid. + * Release builds only: prints a warning to the log when the resource is invalid. * * @param ical iCalendar resource to be validated + * + * @throws ValidationException when the resource is invalid (only if [BuildConfig.DEBUG] is set) */ fun softValidate(ical: Calendar) { try { -- GitLab From a3dc0d06a8f40ee99888b233ed26851c2a553e6f Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Wed, 11 Dec 2019 12:46:35 +0100 Subject: [PATCH 54/58] Update gradle plugin, Kotlin --- build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index cf155e3..0ffed48 100644 --- a/build.gradle +++ b/build.gradle @@ -1,7 +1,7 @@ buildscript { ext.versions = [ - kotlin: '1.3.60', + kotlin: '1.3.61', dokka: '0.10.0', ical4j: '2.2.6' ] @@ -12,7 +12,7 @@ buildscript { } dependencies { - classpath 'com.android.tools.build:gradle:3.5.2' + classpath 'com.android.tools.build:gradle:3.5.3' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${versions.kotlin}" classpath "org.jetbrains.dokka:dokka-gradle-plugin:${versions.dokka}" } -- GitLab From c14424291ba70224d009be6f045122fa07468e70 Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Thu, 12 Dec 2019 12:46:04 +0100 Subject: [PATCH 55/58] Events: process CATEGORIES explicitly (and not only as unknown properties) - process/store CATEGORIES in Event data class - AndroidEvent reads/saves categories in the same format used by the AOSP Exchange ActiveSync adapter - ICalPreprocessor: rewrite invalid CREATED properties which are not in UTC to UTC --- .../at/bitfire/ical4android/MiscUtilsTest.kt | 9 ----- .../at/bitfire/ical4android/AndroidEvent.kt | 35 ++++++++++++++++++- .../java/at/bitfire/ical4android/Event.kt | 6 ++++ .../bitfire/ical4android/ICalPreprocessor.kt | 2 ++ .../java/at/bitfire/ical4android/MiscUtils.kt | 13 ------- src/main/java/at/bitfire/ical4android/Task.kt | 5 +-- 6 files changed, 45 insertions(+), 25 deletions(-) diff --git a/src/androidTest/java/at/bitfire/ical4android/MiscUtilsTest.kt b/src/androidTest/java/at/bitfire/ical4android/MiscUtilsTest.kt index c00cb41..f1be2e7 100644 --- a/src/androidTest/java/at/bitfire/ical4android/MiscUtilsTest.kt +++ b/src/androidTest/java/at/bitfire/ical4android/MiscUtilsTest.kt @@ -12,11 +12,9 @@ import android.content.ContentValues import android.database.MatrixCursor import androidx.test.filters.SmallTest import at.bitfire.ical4android.MiscUtils.CursorHelper.toValues -import at.bitfire.ical4android.MiscUtils.TextListHelper.toList import net.fortuna.ical4j.data.CalendarBuilder import net.fortuna.ical4j.model.Date import net.fortuna.ical4j.model.DateTime -import net.fortuna.ical4j.model.TextList import net.fortuna.ical4j.model.TimeZone import net.fortuna.ical4j.model.component.VTimeZone import net.fortuna.ical4j.model.property.DtStart @@ -114,13 +112,6 @@ class MiscUtilsTest { assertEquals("row1_val2", values.getAsString("col2")) } - @Test - @SmallTest - fun testTextListToList() { - assertEquals(listOf("str1", "str2"), TextList(arrayOf("str1", "str2")).toList()) - assertEquals(emptyList(), TextList(arrayOf()).toList()) - } - @Suppress("unused") private class TestClass { diff --git a/src/main/java/at/bitfire/ical4android/AndroidEvent.kt b/src/main/java/at/bitfire/ical4android/AndroidEvent.kt index 1d491ac..880e0e4 100644 --- a/src/main/java/at/bitfire/ical4android/AndroidEvent.kt +++ b/src/main/java/at/bitfire/ical4android/AndroidEvent.kt @@ -57,6 +57,18 @@ abstract class AndroidEvent( @Deprecated("New content item MIME type", ReplaceWith("UnknownProperty.CONTENT_ITEM_TYPE")) const val EXT_UNKNOWN_PROPERTY2 = "unknown-property.v2" + /** + * VEVENT CATEGORIES will be stored as an extended property with this [ExtendedProperties.NAME]. + * + * The [ExtendedProperties.VALUE] format is the same as used by the AOSP Exchange ActiveSync adapter: + * the category values are stored as list, separated by [EXT_CATEGORIES_SEPARATOR]. (If a category + * value contains [EXT_CATEGORIES_SEPARATOR], [EXT_CATEGORIES_SEPARATOR] will be dropped.) + * + * Example: `Cat1\Cat2` + */ + const val EXT_CATEGORIES = "categories" + const val EXT_CATEGORIES_SEPARATOR = '\\' + /** * EMAIL parameter name (as used for ORGANIZER). Not declared in ical4j Parameters class yet. */ @@ -340,11 +352,17 @@ abstract class AndroidEvent( } protected open fun populateExtended(row: ContentValues) { - Constants.log.log(Level.FINE, "Read extended property from calender provider", row.getAsString(ExtendedProperties.NAME)) + val name = row.getAsString(ExtendedProperties.NAME) + Constants.log.log(Level.FINE, "Read extended property from calender provider (name=$name)") val event = requireNotNull(event) try { when (row.getAsString(ExtendedProperties.NAME)) { + EXT_CATEGORIES -> { + val rawCategories = row.getAsString(ExtendedProperties.VALUE) + event.categories += rawCategories.split(EXT_CATEGORIES_SEPARATOR) + } + EXT_UNKNOWN_PROPERTY -> { // deserialize unknown property (deprecated format) val stream = ByteArrayInputStream(Base64.decode(row.getAsString(ExtendedProperties.VALUE), Base64.NO_WRAP)) @@ -426,6 +444,8 @@ abstract class AndroidEvent( // add unknown properties retainClassification() + if (event.categories.isNotEmpty()) + insertCategories(batch, idxEvent) event.unknownProperties.forEach { insertUnknownProperty(batch, idxEvent, it) } // add exceptions @@ -711,6 +731,18 @@ abstract class AndroidEvent( batch.enqueue(BatchOperation.Operation(builder, Attendees.EVENT_ID, idxEvent)) } + protected open fun insertCategories(batch: BatchOperation, idxEvent: Int) { + val rawCategories = event!!.categories + .map { it.filter { it != EXT_CATEGORIES_SEPARATOR } } // drop backslashes + .joinToString(EXT_CATEGORIES_SEPARATOR.toString()) // concatenate, separate by backslash + val builder = ContentProviderOperation.newInsert(calendar.syncAdapterURI(ExtendedProperties.CONTENT_URI)) + .withValue(ExtendedProperties.NAME, EXT_CATEGORIES) + .withValue(ExtendedProperties.VALUE, rawCategories) + + Constants.log.log(Level.FINE, "Built categories", builder.build()) + batch.enqueue(BatchOperation.Operation(builder, ExtendedProperties.EVENT_ID, idxEvent)) + } + protected open fun insertUnknownProperty(batch: BatchOperation, idxEvent: Int, property: Property) { if (property.value.length > UnknownProperty.MAX_UNKNOWN_PROPERTY_SIZE) { Constants.log.warning("Ignoring unknown property with ${property.value.length} octets (too long)") @@ -721,6 +753,7 @@ abstract class AndroidEvent( .withValue(ExtendedProperties.NAME, UnknownProperty.CONTENT_ITEM_TYPE) .withValue(ExtendedProperties.VALUE, UnknownProperty.toJsonString(property)) + Constants.log.log(Level.FINE, "Built unknown property: ${property.name}") batch.enqueue(BatchOperation.Operation(builder, ExtendedProperties.EVENT_ID, idxEvent)) } diff --git a/src/main/java/at/bitfire/ical4android/Event.kt b/src/main/java/at/bitfire/ical4android/Event.kt index d8c84ff..bbfbba2 100644 --- a/src/main/java/at/bitfire/ical4android/Event.kt +++ b/src/main/java/at/bitfire/ical4android/Event.kt @@ -55,6 +55,7 @@ class Event: ICalendar() { var lastModified: LastModified? = null + val categories = LinkedList() val unknownProperties = LinkedList() companion object { @@ -150,6 +151,9 @@ class Event: ICalendar() { is Summary -> e.summary = prop.value is Location -> e.location = prop.value is Description -> e.description = prop.value + is Categories -> + for (category in prop.categories) + e.categories += category is Color -> e.color = Css3Color.fromString(prop.value) is DtStart -> e.dtStart = prop is DtEnd -> e.dtEnd = prop @@ -271,6 +275,8 @@ class Event: ICalendar() { organizer?.let { props += it } props.addAll(attendees) + if (categories.isNotEmpty()) + props += Categories(TextList(categories.toTypedArray())) props.addAll(unknownProperties) lastModified?.let { props += it } diff --git a/src/main/java/at/bitfire/ical4android/ICalPreprocessor.kt b/src/main/java/at/bitfire/ical4android/ICalPreprocessor.kt index 0b90c68..4675fa4 100644 --- a/src/main/java/at/bitfire/ical4android/ICalPreprocessor.kt +++ b/src/main/java/at/bitfire/ical4android/ICalPreprocessor.kt @@ -2,6 +2,7 @@ package at.bitfire.ical4android import net.fortuna.ical4j.model.Calendar import net.fortuna.ical4j.model.Property +import net.fortuna.ical4j.transform.rfc5545.CreatedPropertyRule import net.fortuna.ical4j.transform.rfc5545.DateListPropertyRule import net.fortuna.ical4j.transform.rfc5545.DatePropertyRule import net.fortuna.ical4j.transform.rfc5545.Rfc5545PropertyRule @@ -17,6 +18,7 @@ import java.util.logging.Level object ICalPreprocessor { private val propertyRules = arrayOf( + CreatedPropertyRule(), // make sure CREATED is UTC DatePropertyRule(), DateListPropertyRule() ) diff --git a/src/main/java/at/bitfire/ical4android/MiscUtils.kt b/src/main/java/at/bitfire/ical4android/MiscUtils.kt index 548738c..ed5ec90 100644 --- a/src/main/java/at/bitfire/ical4android/MiscUtils.kt +++ b/src/main/java/at/bitfire/ical4android/MiscUtils.kt @@ -119,17 +119,4 @@ object MiscUtils { } - - object TextListHelper { - - fun TextList.toList(): List { - val list = LinkedList() - val it = iterator() - while (it.hasNext()) - list += it.next() - return list - } - - } - } \ No newline at end of file diff --git a/src/main/java/at/bitfire/ical4android/Task.kt b/src/main/java/at/bitfire/ical4android/Task.kt index 237fc85..50324b6 100644 --- a/src/main/java/at/bitfire/ical4android/Task.kt +++ b/src/main/java/at/bitfire/ical4android/Task.kt @@ -10,7 +10,6 @@ package at.bitfire.ical4android -import at.bitfire.ical4android.MiscUtils.TextListHelper.toList import net.fortuna.ical4j.data.CalendarOutputter import net.fortuna.ical4j.data.ParserException import net.fortuna.ical4j.model.* @@ -115,7 +114,9 @@ class Task: ICalendar() { is RRule -> t.rRule = prop is RDate -> t.rDates += prop is ExDate -> t.exDates += prop - is Categories -> t.categories.addAll(prop.categories.toList()) + is Categories -> + for (category in prop.categories) + t.categories += category is RelatedTo -> t.relatedTo.add(prop) is Uid, is ProdId, is DtStamp -> { /* don't save these as unknown properties */ } else -> t.unknownProperties += prop -- GitLab From 605b90452d76da0455e41d44895c358c2cf486d4 Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Wed, 1 Jan 2020 19:03:23 +0100 Subject: [PATCH 56/58] Event: improved local handling of exceptions of recurring events --- .../at/bitfire/ical4android/AndroidEvent.kt | 4 +- .../java/at/bitfire/ical4android/DateUtils.kt | 9 ++++ .../java/at/bitfire/ical4android/Event.kt | 46 ++++++++++++------- .../java/at/bitfire/ical4android/ICalendar.kt | 2 - .../java/at/bitfire/ical4android/MiscUtils.kt | 6 +-- .../java/at/bitfire/ical4android/EventTest.kt | 42 +++++++++++++++++ 6 files changed, 85 insertions(+), 24 deletions(-) diff --git a/src/main/java/at/bitfire/ical4android/AndroidEvent.kt b/src/main/java/at/bitfire/ical4android/AndroidEvent.kt index 880e0e4..4f62d08 100644 --- a/src/main/java/at/bitfire/ical4android/AndroidEvent.kt +++ b/src/main/java/at/bitfire/ical4android/AndroidEvent.kt @@ -254,9 +254,7 @@ abstract class AndroidEvent( // exceptions from recurring events row.getAsLong(Events.ORIGINAL_INSTANCE_TIME)?.let { originalInstanceTime -> - var originalAllDay = false - row.getAsInteger(Events.ORIGINAL_ALL_DAY)?.let { originalAllDay = it != 0 } - + val originalAllDay = (row.getAsInteger(Events.ORIGINAL_ALL_DAY) ?: 0) != 0 val originalDate = if (originalAllDay) Date(originalInstanceTime) else DateTime(originalInstanceTime) diff --git a/src/main/java/at/bitfire/ical4android/DateUtils.kt b/src/main/java/at/bitfire/ical4android/DateUtils.kt index fbbd27c..96278e3 100644 --- a/src/main/java/at/bitfire/ical4android/DateUtils.kt +++ b/src/main/java/at/bitfire/ical4android/DateUtils.kt @@ -15,6 +15,7 @@ import net.fortuna.ical4j.model.TimeZone import net.fortuna.ical4j.model.component.VTimeZone import net.fortuna.ical4j.model.parameter.Value import net.fortuna.ical4j.model.property.DateListProperty +import net.fortuna.ical4j.model.property.DateProperty import net.fortuna.ical4j.model.property.ExDate import net.fortuna.ical4j.model.property.RDate import java.io.StringReader @@ -74,6 +75,14 @@ object DateUtils { return deviceTZ } + /** + * Determines whether a given date represents a DATE-TIME value. + * @param date date property to check + * @return *true* if the date is a DATE-TIME value; *false* otherwise (for instance, when the + * date is a DATE value or null) + */ + fun isDateTime(date: DateProperty?) = date != null && date.date is DateTime + /** * Parses a VTIMEZONE definition to a VTimeZone object. * @param timezoneDef VTIMEZONE definition diff --git a/src/main/java/at/bitfire/ical4android/Event.kt b/src/main/java/at/bitfire/ical4android/Event.kt index bbfbba2..a9f710f 100644 --- a/src/main/java/at/bitfire/ical4android/Event.kt +++ b/src/main/java/at/bitfire/ical4android/Event.kt @@ -8,6 +8,7 @@ package at.bitfire.ical4android +import at.bitfire.ical4android.DateUtils.isDateTime import at.bitfire.ical4android.ICalendar.Companion.CALENDAR_NAME import net.fortuna.ical4j.data.CalendarOutputter import net.fortuna.ical4j.data.ParserException @@ -206,24 +207,37 @@ class Event: ICalendar() { // recurrence exceptions for (exception in exceptions) { - // make sure that - // - exceptions have the same UID as the main event and - // - RECURRENCE-IDs have the same timezone as the main event's DTSTART + // exceptions must always have the same UID as the main event exception.uid = uid - exception.recurrenceId?.let { recurrenceId -> - if (recurrenceId.timeZone != dtStart.timeZone) { - recurrenceId.timeZone = dtStart.timeZone - exception.recurrenceId = recurrenceId - } - // create VEVENT for exception - val vException = exception.toVEvent() - components += vException + val recurrenceId = exception.recurrenceId + if (recurrenceId == null) { + Constants.log.warning("Ignoring exception without recurrenceId") + continue + } + + /* Exceptions must always have the same value type as DTSTART [RFC 5545 3.8.4.4]. + If this is not the case, we don't add the exception to the event because we're + strict in what we send (and servers may reject such a case). + */ + if (isDateTime(recurrenceId) != isDateTime(dtStart)) { + Constants.log.warning("Ignoring exception $recurrenceId with other date type than dtStart: $dtStart") + continue + } - // remember used time zones - exception.dtStart?.timeZone?.let(usedTimeZones::add) - exception.dtEnd?.timeZone?.let(usedTimeZones::add) + // for simplicity and compatibility, rewrite date-time exceptions to the same time zone as DTSTART + if (isDateTime(recurrenceId) && recurrenceId.timeZone != dtStart.timeZone) { + Constants.log.fine("Changing timezone of $recurrenceId to same time zone as dtStart: $dtStart") + recurrenceId.timeZone = dtStart.timeZone } + + // create and add VEVENT for exception + val vException = exception.toVEvent() + components += vException + + // remember used time zones + exception.dtStart?.timeZone?.let(usedTimeZones::add) + exception.dtEnd?.timeZone?.let(usedTimeZones::add) } // add VTIMEZONE components @@ -243,7 +257,7 @@ class Event: ICalendar() { * @return generated VEvent */ private fun toVEvent(): VEvent { - val event = VEvent(true /* generates DTSTAMP */) + val event = VEvent(/* generates DTSTAMP */) val props = event.properties props += Uid(uid) @@ -258,7 +272,7 @@ class Event: ICalendar() { description?.let { props += Description(it) } color?.let { props += Color(null, it.name) } - props += dtStart + dtStart?.let { props += it } dtEnd?.let { props += it } duration?.let { props += it } diff --git a/src/main/java/at/bitfire/ical4android/ICalendar.kt b/src/main/java/at/bitfire/ical4android/ICalendar.kt index c6324db..e5c8298 100644 --- a/src/main/java/at/bitfire/ical4android/ICalendar.kt +++ b/src/main/java/at/bitfire/ical4android/ICalendar.kt @@ -99,8 +99,6 @@ open class ICalendar { // time zone helpers - fun isDateTime(date: DateProperty?) = date != null && date.date is DateTime - /** * Minifies a VTIMEZONE so that only components after [start] are kept. * Doesn't return the smallest possible VTIMEZONE at the moment, but diff --git a/src/main/java/at/bitfire/ical4android/MiscUtils.kt b/src/main/java/at/bitfire/ical4android/MiscUtils.kt index ed5ec90..95ebaf9 100644 --- a/src/main/java/at/bitfire/ical4android/MiscUtils.kt +++ b/src/main/java/at/bitfire/ical4android/MiscUtils.kt @@ -11,7 +11,7 @@ package at.bitfire.ical4android import android.content.ContentValues import android.database.Cursor import android.database.DatabaseUtils -import net.fortuna.ical4j.model.TextList +import at.bitfire.ical4android.DateUtils.isDateTime import net.fortuna.ical4j.model.property.DateProperty import net.fortuna.ical4j.util.TimeZones import java.lang.reflect.Modifier @@ -25,7 +25,7 @@ object MiscUtils { * @param date DateProperty to validate. Values which are not DATE-TIME will be ignored. */ fun androidifyTimeZone(date: DateProperty?) { - if (ICalendar.isDateTime(date)) { + if (isDateTime(date)) { val tz = date!!.timeZone ?: return val tzID = tz.id ?: return val deviceTzID = DateUtils.findAndroidTimezoneID(tzID) @@ -47,7 +47,7 @@ object MiscUtils { * - the currently set default time zone ID for floating date-times */ fun getTzId(date: DateProperty): String = - if (ICalendar.isDateTime(date)) { + if (isDateTime(date)) { when { date.isUtc -> // DATE-TIME in UTC format diff --git a/src/test/java/at/bitfire/ical4android/EventTest.kt b/src/test/java/at/bitfire/ical4android/EventTest.kt index 2f4ca91..acb45bd 100644 --- a/src/test/java/at/bitfire/ical4android/EventTest.kt +++ b/src/test/java/at/bitfire/ical4android/EventTest.kt @@ -7,10 +7,14 @@ */ package at.bitfire.ical4android +import net.fortuna.ical4j.model.Date +import net.fortuna.ical4j.model.DateTime import net.fortuna.ical4j.model.Dur import net.fortuna.ical4j.model.TimeZoneRegistryFactory import net.fortuna.ical4j.model.component.VAlarm import net.fortuna.ical4j.model.property.DtStart +import net.fortuna.ical4j.model.property.RRule +import net.fortuna.ical4j.model.property.RecurrenceId import org.junit.Assert.* import org.junit.Test import java.io.ByteArrayOutputStream @@ -91,6 +95,44 @@ class EventTest { assertEquals("Unknown Value", unknown.value) } + @Test + fun testRecurringWriteFullDayException() { + val event = Event().apply { + uid = "test1" + dtStart = DtStart("20190117T083000", DateUtils.tzRegistry.getTimeZone("Europe/Berlin")) + summary = "Main event" + rRule = RRule("FREQ=DAILY;COUNT=5") + exceptions += arrayOf( + Event().apply { + uid = "test2" + recurrenceId = RecurrenceId(DateTime("20190118T073000", DateUtils.tzRegistry.getTimeZone("Europe/London"))) + summary = "Normal exception" + }, + Event().apply { + uid = "test3" + recurrenceId = RecurrenceId(Date("20190223")) + summary = "Full-day exception" + } + ) + } + val baos = ByteArrayOutputStream() + event.write(baos) + val iCal = baos.toString() + assertTrue(iCal.contains("UID:test1\r\n")) + assertTrue(iCal.contains("DTSTART;TZID=Europe/Berlin:20190117T083000\r\n")) + + // first RECURRENCE-ID has been rewritten + // - to main event's UID + // - to time zone Europe/Berlin (with one hour time difference) + assertTrue(iCal.contains("UID:test1\r\n" + + "RECURRENCE-ID;TZID=Europe/Berlin:20190118T083000\r\n" + + "SUMMARY:Normal exception\r\n" + + "END:VEVENT")) + + // no RECURRENCE-ID;VALUE=DATE:20190223 + assertFalse(iCal.contains(":20190223")) + } + @Test fun testRecurringWithException() { val event = parseCalendar("recurring-with-exception1.ics").first() -- GitLab From be6d515db8721008bdc93a9a6668f51b4a79502e Mon Sep 17 00:00:00 2001 From: Ricki Hirner Date: Tue, 7 Jan 2020 09:44:02 +0100 Subject: [PATCH 57/58] isAllDay: check for null --- src/main/java/at/bitfire/ical4android/Event.kt | 8 +++++++- src/test/java/at/bitfire/ical4android/EventTest.kt | 7 +++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/main/java/at/bitfire/ical4android/Event.kt b/src/main/java/at/bitfire/ical4android/Event.kt index a9f710f..544ab79 100644 --- a/src/main/java/at/bitfire/ical4android/Event.kt +++ b/src/main/java/at/bitfire/ical4android/Event.kt @@ -14,6 +14,7 @@ import net.fortuna.ical4j.data.CalendarOutputter import net.fortuna.ical4j.data.ParserException import net.fortuna.ical4j.model.* import net.fortuna.ical4j.model.Calendar +import net.fortuna.ical4j.model.Date import net.fortuna.ical4j.model.TimeZone import net.fortuna.ical4j.model.component.VAlarm import net.fortuna.ical4j.model.component.VEvent @@ -303,6 +304,11 @@ class Event: ICalendar() { // helpers - fun isAllDay() = !isDateTime(dtStart) + /** + * Determines whether this Event is an all-day event. + * + * @return *true* if [dtStart] is a DATE value; *false* otherwise ([dtStart] is a DATETIME value or *null*) + */ + fun isAllDay() = dtStart != null && !isDateTime(dtStart) } diff --git a/src/test/java/at/bitfire/ical4android/EventTest.kt b/src/test/java/at/bitfire/ical4android/EventTest.kt index acb45bd..ffd50c9 100644 --- a/src/test/java/at/bitfire/ical4android/EventTest.kt +++ b/src/test/java/at/bitfire/ical4android/EventTest.kt @@ -79,6 +79,13 @@ class EventTest { assertTrue("Event 2 Exception 2" == e.exceptions.first.summary || "Event 2 Exception 2" == e.exceptions[1].summary) } + @Test + fun testIsAllDay() { + assertFalse(Event().isAllDay()) + assertTrue(Event().apply { dtStart = DtStart(Date("20190101")) }.isAllDay()) + assertFalse(Event().apply { dtStart = DtStart(DateTime("20190101T010100")) }.isAllDay()) + } + @Test fun testParse() { val event = parseCalendar("utf8.ics").first() -- GitLab From fcbf4115666c5aa650fdbd062fc8a95fb09c1635 Mon Sep 17 00:00:00 2001 From: Romain Hunault Date: Fri, 7 Feb 2020 14:51:43 +0000 Subject: [PATCH 58/58] Switch to the Tasks fork (cherry picked from commit 50ffe62eec2d6017cc38c2f30ba71d577a8d044c) --- src/main/java/foundation/e/ical4android/TaskProvider.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/foundation/e/ical4android/TaskProvider.kt b/src/main/java/foundation/e/ical4android/TaskProvider.kt index bf8c098..adcf7aa 100644 --- a/src/main/java/foundation/e/ical4android/TaskProvider.kt +++ b/src/main/java/foundation/e/ical4android/TaskProvider.kt @@ -31,7 +31,7 @@ class TaskProvider private constructor( val minVersionName: String ) { //Mirakel("de.azapps.mirakel.provider"), - OpenTasks("org.dmfs.tasks", "org.dmfs.tasks", 103, "1.1.8.2") + OpenTasks("foundation.e.tasks", "foundation.e.tasks", 103, "1.1.8.2") } companion object { -- GitLab