├── .gitignore ├── LICENSE ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── sixthsolution │ │ └── lpisyncadapterapp │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── sixthsolution │ │ │ └── lpisyncadapterapp │ │ │ ├── CustomLoginActivity.java │ │ │ └── MainActivity.java │ └── res │ │ ├── layout │ │ ├── activity_custom_login.xml │ │ └── activity_main.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ └── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── sixthsolution │ └── lpisyncadapterapp │ └── ExampleUnitTest.java ├── build.gradle ├── easy-apple-syncadapter ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── sixthsolution │ │ └── lpisyncadapter │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── sixthsolution │ │ │ └── lpisyncadapter │ │ │ ├── App.java │ │ │ ├── GlobalConstant.java │ │ │ ├── authenticator │ │ │ ├── AuthServerHandler.java │ │ │ ├── AuthServerHandlerImpl.java │ │ │ ├── BaseLoginActivity.java │ │ │ ├── ICalAuthenticator.java │ │ │ ├── ICalAuthenticatorService.java │ │ │ ├── LoginActivity.java │ │ │ ├── SignInException.java │ │ │ └── crypto │ │ │ │ ├── Crypto.java │ │ │ │ └── KeyManager.java │ │ │ ├── download │ │ │ └── EventDownloader.java │ │ │ ├── entitiy │ │ │ ├── BaseCalendarData.java │ │ │ ├── BaseCollectionInfo.java │ │ │ ├── CalendarData.java │ │ │ └── CollectionInfo.java │ │ │ ├── exceptions │ │ │ └── InvalidAccountException.java │ │ │ ├── resource │ │ │ ├── LocalCalendar.java │ │ │ ├── LocalCollection.java │ │ │ ├── LocalEvent.java │ │ │ ├── LocalResource.java │ │ │ └── LocalTask.java │ │ │ ├── syncadapter │ │ │ ├── BaseSyncAdapter.java │ │ │ ├── ICalSyncAdapter.java │ │ │ ├── ICalSyncService.java │ │ │ ├── SyncManager.java │ │ │ ├── SyncServerHandler.java │ │ │ └── SyncServerHandlerImpl.java │ │ │ └── util │ │ │ ├── AccountSettings.java │ │ │ ├── ArrayUtils.java │ │ │ ├── DavResourceFinder.java │ │ │ ├── DavUtils.java │ │ │ ├── HttpClient.java │ │ │ ├── MemoryCookieStore.java │ │ │ ├── SSLSocketFactoryCompat.java │ │ │ └── Util.java │ ├── lombok.config │ └── res │ │ ├── drawable │ │ └── ical_icon.png │ │ ├── layout │ │ └── activity_login.xml │ │ ├── values │ │ └── strings.xml │ │ └── xml │ │ ├── authenticator.xml │ │ └── sync_adapter.xml │ └── test │ └── java │ └── com │ └── sixthsolution │ └── lpisyncadapter │ └── ExampleUnitTest.java ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | .gradle 3 | /local.properties 4 | .DS_Store 5 | /build 6 | # Android Studio 7 | .idea 8 | *.iml 9 | *.class 10 | *.apk 11 | /captures 12 | 13 | ## Android Studio and Intellij and Android in general 14 | *.ipr 15 | *.iws 16 | out/ 17 | com_crashlytics_export_strings.xml 18 | OkHttpClient/build 19 | lib/build -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Easy Apple Sync Adapter is an Android Library for syncing with **apple** calendar service. 2 | 3 | Performing authentication and full duplex sync with **apple caldav** server. 4 | 5 | _This library is based on [DavDroid](https://gitlab.com/bitfireAT/davdroid), and borrows many code from them. 6 | we just simplify the process of reusing the library_ 7 | 8 | ## Features 9 | * Easy to use. 10 | * Powerful encryption for passwords. 11 | 12 | ## Installation 13 | 1) Configure your top-level `build.gradle` to include our repository 14 | ```groovy 15 | allprojects { 16 | repositories { 17 | jcenter() 18 | maven { url "http://dl.bintray.com/6thsolution/public-maven" } 19 | } 20 | } 21 | ``` 22 | Then config your app-level `build.gradle` to include the library as dependency: 23 | ``` groovy 24 | compile 'com.sixthsolution:easyapplesyncadapter:1.0.0-beta1' 25 | ``` 26 | 27 | 2) config: 28 | 29 | **Authenticator config** : Add Authenticator service to your manifest: 30 | ```xml 31 | 35 | 36 | 37 | 38 | 39 | 43 | 47 | 51 | 52 | ``` 53 | There is a few metadata that you can pass your parameters to the service via them: 54 | 55 | 1) `android.accounts.AccountAuthenticator` 56 | The authenticator config file, something like this: 57 | ```xml 58 | 64 | 65 | ``` 66 | 2) `android:accountType` parameter must be the same value you passed via `unique_authentication_type` metadata. 67 | this must be **unique**, otherwise your app may not work. so use something package specific. 68 | 69 | 3) `login_activity_class` 70 | You can pass a custom login activity with custom ui for login process. 71 | The value must be _complete path with package name_ like: `com.sixthsolution.applecalendar.CustomLoginActivity`. 72 | Your activity must extend **BaseLoginActivity** and your layout must have some view that is necessary for login process. 73 | two _EditText_ with exact id as `user_name` and `password` . and one _Button_ with id `signin_button` and 74 | After calling _setContentView()_ in _onCreate()_ you must call **init()**. 75 | 76 | **SyncAdapter config** : 77 | You also need to add sync adapter service to your manifest: 78 | ```xml 79 | 83 | 84 | 85 | 86 | 90 | 91 | ``` 92 | 1) `sync_adapter` file is something like this: 93 | ```xml 94 | 101 | 102 | ``` 103 | 2) `android:contentAuthority="com.android.calendar"` always must be it. (do NOT change it except when you need to). 104 | 3) `android:accountType` must be the same value you set for authenticator config. 105 | 106 | ## Usage 107 | * **Add new account**: 108 | You must call `AccountManager#addAccount` for adding new account. it automatically you the config and open 109 | `LoginActivity` and handle add progress by itself. 110 | ```java 111 | accountManager.addAccount(AUTHTOKEN_TYPE_FULL_ACCESS, AUTHTOKEN_TYPE_FULL_ACCESS, null, null, this, 112 | new AccountManagerCallback() { 113 | @Override 114 | public void run(AccountManagerFuture future) { 115 | try { 116 | Bundle bnd = future.getResult(); 117 | } catch (Exception e) { 118 | e.printStackTrace(); 119 | } 120 | } 121 | }, null); 122 | ``` 123 | * **Get list of available accounts**: 124 | ```java 125 | AccountManager accountManager = AccountManager.get(this); 126 | Account availableAccounts[] = accountManager.getAccountsByType(AUTHTOKEN_TYPE_FULL_ACCESS); 127 | ``` 128 | * **Requesting manual sync**: 129 | ```java 130 | Bundle params = new Bundle(); 131 | params.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true); 132 | params.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); 133 | ContentResolver.requestSync(account, GlobalConstant.AUTHORITY, params); 134 | ``` 135 | * **Listening for sync finish**: 136 | if you wana know when the sync finish or show progress during progress use a `ContentObserver` : 137 | ```java 138 | ContentObserver contentObserver = new ContentObserver(new Handler()) { 139 | @Override 140 | public void onChange(boolean selfChange, Uri uri) { 141 | super.onChange(selfChange, uri); 142 | showMessage("Sync Finished"); 143 | } 144 | }; 145 | ``` 146 | ```java 147 | @Override 148 | protected void onCreate(Bundle savedInstanceState) { 149 | super.onCreate(savedInstanceState); 150 | setContentView(R.layout.activity_main); 151 | getContentResolver().registerContentObserver(GlobalConstant.CONTENT_URI, true, contentObserver); 152 | } 153 | ``` 154 | do NOT forget to unregister it: 155 | ```java 156 | @Override 157 | protected void onDestroy() { 158 | super.onDestroy(); 159 | getContentResolver().unregisterContentObserver(contentObserver); 160 | } 161 | ``` 162 | * **Get list of Calendars associated with account**: 163 | ```java 164 | LocalCalendar[] localCalendars = (LocalCalendar[]) LocalCalendar.find(account, 165 | // get contentProviderClient for your authority 166 | getContentResolver().acquireContentProviderClient(GlobalConstant.AUTHORITY), 167 | LocalCalendar.Factory.INSTANCE, 168 | null, 169 | null); 170 | ``` 171 | * **Get list of events associated with LocalCalendar**: 172 | You can get list of all resource by: 173 | ```java 174 | LocalResource[] localResources = localCalendar.getAll(); 175 | ``` 176 | Then cast if to `LocalEvent`: 177 | ```java 178 | (LocalEvent) localResources[i] 179 | ``` 180 | 181 | ## License 182 | ``` 183 | Copyright 2016-2017 6thSolution Technologies Inc. 184 | 185 | Licensed under the Apache License, Version 2.0 (the "License"); 186 | you may not use this file except in compliance with the License. 187 | You may obtain a copy of the License at 188 | 189 | http://www.apache.org/licenses/LICENSE-2.0 190 | 191 | Unless required by applicable law or agreed to in writing, software 192 | distributed under the License is distributed on an "AS IS" BASIS, 193 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 194 | See the License for the specific language governing permissions and 195 | limitations under the License. 196 | ``` 197 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | apply plugin: 'com.neenbedankt.android-apt' 3 | 4 | android { 5 | compileSdkVersion 25 6 | buildToolsVersion "25.0.2" 7 | defaultConfig { 8 | applicationId "com.sixthsolution.lpisyncadapterapp" 9 | minSdkVersion 16 10 | targetSdkVersion 25 11 | versionCode 1 12 | versionName "1.0" 13 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 14 | } 15 | buildTypes { 16 | release { 17 | minifyEnabled false 18 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 19 | } 20 | } 21 | } 22 | 23 | dependencies { 24 | compile fileTree(include: ['*.jar'], dir: 'libs') 25 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { 26 | exclude group: 'com.android.support', module: 'support-annotations' 27 | }) 28 | compile 'com.android.support:appcompat-v7:25.3.1' 29 | compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha9' 30 | testCompile 'junit:junit:4.12' 31 | compile project(':easy-apple-syncadapter') 32 | 33 | //for runtime permission 34 | compile 'com.github.hotchemi:permissionsdispatcher:2.2.1' 35 | apt 'com.github.hotchemi:permissionsdispatcher-processor:2.2.1' 36 | } 37 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in H:\Android\sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | 19 | # Uncomment this to preserve the line number information for 20 | # debugging stack traces. 21 | #-keepattributes SourceFile,LineNumberTable 22 | 23 | # If you keep the line number information, uncomment this to 24 | # hide the original source file name. 25 | #-renamesourcefileattribute SourceFile 26 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/sixthsolution/lpisyncadapterapp/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.sixthsolution.lpisyncadapterapp; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.assertEquals; 11 | 12 | /** 13 | * Instrumentation test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() throws Exception { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("com.sixthsolution.lpisyncadapterapp", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 37 | 38 | 39 | 40 | 41 | 45 | 49 | 53 | 54 | 55 | 59 | 60 | 61 | 62 | 66 | 67 | 68 | 69 | -------------------------------------------------------------------------------- /app/src/main/java/com/sixthsolution/lpisyncadapterapp/CustomLoginActivity.java: -------------------------------------------------------------------------------- 1 | package com.sixthsolution.lpisyncadapterapp; 2 | 3 | import android.os.Bundle; 4 | 5 | import com.sixthsolution.lpisyncadapter.authenticator.BaseLoginActivity; 6 | 7 | 8 | /** 9 | * @author mehdok (mehdok@gmail.com) on 3/15/2017. 10 | */ 11 | 12 | public class CustomLoginActivity extends BaseLoginActivity { 13 | 14 | 15 | @Override 16 | protected void onCreate(Bundle icicle) { 17 | super.onCreate(icicle); 18 | 19 | setContentView(R.layout.activity_custom_login); 20 | init(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /app/src/main/java/com/sixthsolution/lpisyncadapterapp/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.sixthsolution.lpisyncadapterapp; 2 | 3 | import android.Manifest; 4 | import android.accounts.Account; 5 | import android.accounts.AccountManager; 6 | import android.accounts.AccountManagerCallback; 7 | import android.accounts.AccountManagerFuture; 8 | import android.app.AlertDialog; 9 | import android.content.ContentResolver; 10 | import android.content.DialogInterface; 11 | import android.database.ContentObserver; 12 | import android.net.Uri; 13 | import android.os.Bundle; 14 | import android.os.Handler; 15 | import android.support.annotation.NonNull; 16 | import android.support.v7.app.AppCompatActivity; 17 | import android.util.Log; 18 | import android.view.View; 19 | import android.widget.ArrayAdapter; 20 | import android.widget.Toast; 21 | 22 | import com.sixthsolution.lpisyncadapter.GlobalConstant; 23 | import com.sixthsolution.lpisyncadapter.authenticator.crypto.Crypto; 24 | import com.sixthsolution.lpisyncadapter.resource.LocalCalendar; 25 | import com.sixthsolution.lpisyncadapter.resource.LocalEvent; 26 | import com.sixthsolution.lpisyncadapter.resource.LocalResource; 27 | 28 | import net.fortuna.ical4j.model.DateList; 29 | import net.fortuna.ical4j.model.Dur; 30 | import net.fortuna.ical4j.model.TimeZone; 31 | import net.fortuna.ical4j.model.component.VAlarm; 32 | import net.fortuna.ical4j.model.parameter.Value; 33 | import net.fortuna.ical4j.model.property.Attendee; 34 | import net.fortuna.ical4j.model.property.DtEnd; 35 | import net.fortuna.ical4j.model.property.DtStart; 36 | import net.fortuna.ical4j.model.property.ExDate; 37 | import net.fortuna.ical4j.model.property.Organizer; 38 | import net.fortuna.ical4j.model.property.RRule; 39 | import net.fortuna.ical4j.model.property.RecurrenceId; 40 | import net.fortuna.ical4j.model.property.Status; 41 | 42 | import java.io.FileNotFoundException; 43 | import java.net.URI; 44 | 45 | import at.bitfire.ical4android.CalendarStorageException; 46 | import at.bitfire.ical4android.DateUtils; 47 | import at.bitfire.ical4android.Event; 48 | import permissions.dispatcher.NeedsPermission; 49 | import permissions.dispatcher.RuntimePermissions; 50 | 51 | import static com.sixthsolution.lpisyncadapter.GlobalConstant.AUTHTOKEN_TYPE_FULL_ACCESS; 52 | import static com.sixthsolution.lpisyncadapterapp.MainActivity.ActionType.CREATE_EVENT; 53 | import static com.sixthsolution.lpisyncadapterapp.MainActivity.ActionType.GET_TOKEN; 54 | import static com.sixthsolution.lpisyncadapterapp.MainActivity.ActionType.SHOW_CALENDARS; 55 | import static com.sixthsolution.lpisyncadapterapp.MainActivity.ActionType.SHOW_EVENTS; 56 | import static com.sixthsolution.lpisyncadapterapp.MainActivity.ActionType.SYNC; 57 | import static com.sixthsolution.lpisyncadapterapp.MainActivityPermissionsDispatcher.showAccountPickerWithCheck; 58 | 59 | @RuntimePermissions 60 | public class MainActivity extends AppCompatActivity { 61 | private AccountManager accountManager; 62 | 63 | public enum ActionType { 64 | GET_TOKEN, 65 | SYNC, 66 | SHOW_CALENDARS, 67 | SHOW_EVENTS, 68 | CREATE_EVENT 69 | } 70 | 71 | ContentObserver contentObserver = new ContentObserver(new Handler()) { 72 | @Override 73 | public void onChange(boolean selfChange, Uri uri) { 74 | super.onChange(selfChange, uri); 75 | 76 | showMessage("Sync Finished"); 77 | } 78 | }; 79 | 80 | @Override 81 | protected void onCreate(Bundle savedInstanceState) { 82 | super.onCreate(savedInstanceState); 83 | setContentView(R.layout.activity_main); 84 | accountManager = AccountManager.get(this); 85 | 86 | findViewById(R.id.get_token).setOnClickListener(new View.OnClickListener() { 87 | @Override 88 | public void onClick(View v) { 89 | showAccountPickerWithCheck(MainActivity.this, AUTHTOKEN_TYPE_FULL_ACCESS, GET_TOKEN); 90 | } 91 | }); 92 | findViewById(R.id.add_account).setOnClickListener(new View.OnClickListener() { 93 | @Override 94 | public void onClick(View v) { 95 | addNewAccount(); 96 | } 97 | }); 98 | findViewById(R.id.sync).setOnClickListener(new View.OnClickListener() { 99 | @Override 100 | public void onClick(View v) { 101 | showAccountPickerWithCheck(MainActivity.this, AUTHTOKEN_TYPE_FULL_ACCESS, SYNC); 102 | } 103 | }); 104 | findViewById(R.id.show_calendars).setOnClickListener(new View.OnClickListener() { 105 | @Override 106 | public void onClick(View v) { 107 | showAccountPickerWithCheck(MainActivity.this, AUTHTOKEN_TYPE_FULL_ACCESS, SHOW_CALENDARS); 108 | } 109 | }); 110 | findViewById(R.id.show_events).setOnClickListener(new View.OnClickListener() { 111 | @Override 112 | public void onClick(View v) { 113 | showAccountPickerWithCheck(MainActivity.this, AUTHTOKEN_TYPE_FULL_ACCESS, SHOW_EVENTS); 114 | } 115 | }); 116 | findViewById(R.id.create_event).setOnClickListener(new View.OnClickListener() { 117 | @Override 118 | public void onClick(View v) { 119 | showAccountPickerWithCheck(MainActivity.this, AUTHTOKEN_TYPE_FULL_ACCESS, CREATE_EVENT); 120 | } 121 | }); 122 | 123 | syncAutomatically(); 124 | 125 | // register a content observer to notify when th sync is finished 126 | getContentResolver().registerContentObserver(GlobalConstant.CONTENT_URI, true, contentObserver); 127 | } 128 | 129 | public void addNewAccount() { 130 | final AccountManagerFuture future = 131 | accountManager.addAccount(AUTHTOKEN_TYPE_FULL_ACCESS, AUTHTOKEN_TYPE_FULL_ACCESS, null, null, this, 132 | new AccountManagerCallback() { 133 | @Override 134 | public void run(AccountManagerFuture future) { 135 | try { 136 | Bundle bnd = future.getResult(); 137 | showMessage("AddNewAccount Bundle is " + bnd); 138 | } catch (Exception e) { 139 | e.printStackTrace(); 140 | showMessage(e.getMessage()); 141 | } 142 | } 143 | }, null); 144 | accountManager.addAccount(AUTHTOKEN_TYPE_FULL_ACCESS, AUTHTOKEN_TYPE_FULL_ACCESS, null, null, this, 145 | new AccountManagerCallback() { 146 | @Override 147 | public void run(AccountManagerFuture future) { 148 | try { 149 | Bundle bnd = future.getResult(); 150 | showMessage("AddNewAccount Bundle is " + bnd); 151 | } catch (Exception e) { 152 | e.printStackTrace(); 153 | showMessage(e.getMessage()); 154 | } 155 | } 156 | }, null); 157 | } 158 | 159 | @NeedsPermission({Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR}) 160 | public void showAccountPicker(final String authTokenType, final ActionType actionType) { 161 | // get list of available account 162 | final Account availableAccounts[] = accountManager.getAccountsByType(AUTHTOKEN_TYPE_FULL_ACCESS); 163 | 164 | if (availableAccounts.length == 0) { 165 | showMessage("No accounts"); 166 | } else { 167 | String name[] = new String[availableAccounts.length]; 168 | for (int i = 0; i < availableAccounts.length; i++) { 169 | name[i] = availableAccounts[i].name; 170 | } 171 | 172 | // Account picker 173 | AlertDialog mAlertDialog = new AlertDialog.Builder(this).setTitle("Pick Account") 174 | .setAdapter( 175 | new ArrayAdapter(getBaseContext(), android.R.layout.simple_list_item_1, name), 176 | new DialogInterface.OnClickListener() { 177 | @Override 178 | public void onClick(DialogInterface dialog, int which) { 179 | // invalidateAuthToken(availableAccounts[which], authTokenType); 180 | 181 | switch (actionType) { 182 | case GET_TOKEN: 183 | getExistingAccountAuthToken(availableAccounts[which], authTokenType); 184 | break; 185 | case SYNC: 186 | sync(availableAccounts[which]); 187 | break; 188 | case SHOW_CALENDARS: 189 | showCalendars(availableAccounts[which], SHOW_EVENTS); 190 | break; 191 | case SHOW_EVENTS: 192 | showCalendars(availableAccounts[which], SHOW_EVENTS); 193 | break; 194 | case CREATE_EVENT: 195 | showCalendars(availableAccounts[which], CREATE_EVENT); 196 | } 197 | } 198 | }) 199 | .create(); 200 | mAlertDialog.show(); 201 | } 202 | } 203 | 204 | private void invalidateAuthToken(final Account account, String authTokenType) { 205 | final AccountManagerFuture future = 206 | accountManager.getAuthToken(account, authTokenType, null, this, null, null); 207 | 208 | new Thread(new Runnable() { 209 | @Override 210 | public void run() { 211 | try { 212 | Bundle bnd = future.getResult(); 213 | 214 | final String authtoken = bnd.getString(AccountManager.KEY_AUTHTOKEN); 215 | accountManager.invalidateAuthToken(account.type, authtoken); 216 | Log.d("MainActivity", account.name + " invalidated"); 217 | } catch (Exception e) { 218 | e.printStackTrace(); 219 | showMessage(e.getMessage()); 220 | } 221 | } 222 | }).start(); 223 | } 224 | 225 | private void getExistingAccountAuthToken(Account account, String authTokenType) { 226 | final AccountManagerFuture future = 227 | accountManager.getAuthToken(account, authTokenType, null, this, null, null); 228 | 229 | new Thread(new Runnable() { 230 | @Override 231 | public void run() { 232 | try { 233 | Bundle bnd = future.getResult(); 234 | 235 | String authtoken = bnd.getString(AccountManager.KEY_AUTHTOKEN, "UTF-8"); 236 | authtoken = Crypto.armorDecrypt(authtoken, MainActivity.this); 237 | showMessage(bnd.toString() + "\n encrypted user id: " + authtoken); 238 | } catch (Exception e) { 239 | e.printStackTrace(); 240 | showMessage(e.getMessage()); 241 | } 242 | } 243 | }).start(); 244 | } 245 | 246 | private void showMessage(final String str) { 247 | runOnUiThread(new Runnable() { 248 | @Override 249 | public void run() { 250 | Toast.makeText(MainActivity.this, str, Toast.LENGTH_LONG).show(); 251 | } 252 | }); 253 | } 254 | 255 | /** 256 | * The {@link ContentResolver#setSyncAutomatically} and {@link ContentResolver#addPeriodicSync} 257 | * must call programmatically 258 | */ 259 | private void syncAutomatically() { 260 | //get all account related to our app 261 | final Account availableAccounts[] = accountManager.getAccountsByType(AUTHTOKEN_TYPE_FULL_ACCESS); 262 | 263 | //set syncable status for all of them 264 | for (Account account : availableAccounts) { 265 | ContentResolver.setIsSyncable(account, GlobalConstant.AUTHORITY, 1); 266 | ContentResolver.setSyncAutomatically(account, GlobalConstant.AUTHORITY, true); 267 | ContentResolver.addPeriodicSync(account, GlobalConstant.AUTHORITY, new Bundle(), 2 * 60 * 60); 268 | } 269 | } 270 | 271 | private void sync(Account account) { 272 | Bundle params = new Bundle(); 273 | params.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true); 274 | params.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); 275 | ContentResolver.requestSync(account, GlobalConstant.AUTHORITY, params); 276 | } 277 | 278 | private void showCalendars(Account account, final ActionType actionType) { 279 | try { 280 | //get list of local calendar associated to the account 281 | final LocalCalendar[] localCalendars = 282 | (LocalCalendar[]) LocalCalendar.find(account, 283 | // get contentProviderClient for our authority 284 | getContentResolver().acquireContentProviderClient( 285 | GlobalConstant.AUTHORITY), 286 | LocalCalendar.Factory.INSTANCE, 287 | null, 288 | null); 289 | 290 | if (localCalendars.length == 0) { 291 | showMessage("No calendar with this account"); 292 | } else { 293 | String name[] = new String[localCalendars.length]; 294 | for (int i = 0; i < localCalendars.length; i++) { 295 | name[i] = localCalendars[i].getDisplayName(); 296 | } 297 | 298 | AlertDialog mAlertDialog = new AlertDialog.Builder(this).setTitle("Pick Calendar") 299 | .setAdapter( 300 | new ArrayAdapter(getBaseContext(), android.R.layout.simple_list_item_1, 301 | name), 302 | new DialogInterface.OnClickListener() { 303 | @Override 304 | public void onClick(DialogInterface dialog, int which) { 305 | switch (actionType) { 306 | case SHOW_EVENTS: 307 | showEvents(localCalendars[which]); 308 | break; 309 | case CREATE_EVENT: 310 | createTestEvent(localCalendars[which]); 311 | break; 312 | } 313 | 314 | } 315 | }) 316 | .create(); 317 | mAlertDialog.show(); 318 | } 319 | } catch (CalendarStorageException e) { 320 | e.printStackTrace(); 321 | showMessage(e.getMessage()); 322 | } 323 | } 324 | 325 | private void showEvents(LocalCalendar localCalendar) { 326 | try { 327 | // get list of local calendar associated with selected calendar 328 | LocalResource[] localResources = localCalendar.getAll(); 329 | if (localResources.length == 0) { 330 | showMessage("No event in this calendar"); 331 | } else { 332 | String name[] = new String[localResources.length]; 333 | for (int i = 0; i < localResources.length; i++) { 334 | name[i] = ((LocalEvent) localResources[i]).getEvent().toString(); 335 | } 336 | 337 | AlertDialog mAlertDialog = new AlertDialog.Builder(this).setTitle("See events") 338 | .setAdapter( 339 | new ArrayAdapter(getBaseContext(), android.R.layout.simple_list_item_1, 340 | name), 341 | null) 342 | .create(); 343 | mAlertDialog.show(); 344 | } 345 | } catch (CalendarStorageException | FileNotFoundException e) { 346 | e.printStackTrace(); 347 | showMessage(e.getMessage()); 348 | } 349 | } 350 | 351 | private void createTestEvent(LocalCalendar calendar) { 352 | try { 353 | TimeZone tzVienna = DateUtils.tzRegistry.getTimeZone("Europe/Vienna"); 354 | 355 | Event event = new Event(); 356 | event.uid = "sample1@testAddEvent"; 357 | event.summary = "Sample event"; 358 | event.description = "Sample event with date/time"; 359 | event.location = "Sample location"; 360 | event.dtStart = new DtStart("20150501T120000", tzVienna); 361 | event.dtEnd = new DtEnd("20150501T130000", tzVienna); 362 | event.organizer = new Organizer(new URI("mailto:organizer@example.com")); 363 | event.rRule = new RRule("FREQ=DAILY;COUNT=10"); 364 | event.forPublic = false; 365 | event.status = Status.VEVENT_CONFIRMED; 366 | 367 | // set an alarm one day, two hours, three minutes and four seconds before begin of event 368 | event.alarms.add(new VAlarm(new Dur(-1, -2, -3, -4))); 369 | 370 | // add two attendees 371 | event.attendees.add(new Attendee(new URI("mailto:user1@example.com"))); 372 | event.attendees.add(new Attendee(new URI("mailto:user2@example.com"))); 373 | 374 | // add exception with alarm and attendee 375 | Event exception = new Event(); 376 | exception.recurrenceId = new RecurrenceId("20150502T120000", tzVienna); 377 | exception.summary = "Exception for sample event"; 378 | exception.dtStart = new DtStart("20150502T140000", tzVienna); 379 | exception.dtEnd = new DtEnd("20150502T150000", tzVienna); 380 | exception.alarms.add(new VAlarm(new Dur(-2, -3, -4, -5))); 381 | exception.attendees.add(new Attendee(new URI("mailto:only.here@today"))); 382 | event.exceptions.add(exception); 383 | 384 | // add EXDATE 385 | event.exDates.add(new ExDate(new DateList("20150502T120000", Value.DATE_TIME, tzVienna))); 386 | // add to calendar 387 | Uri uri = new LocalEvent(calendar, event, null, null).add(); 388 | 389 | showMessage("Event created: " + uri); 390 | showEvents(calendar); 391 | } catch (Exception e) { 392 | e.printStackTrace(); 393 | showMessage(e.toString()); 394 | } 395 | } 396 | 397 | @Override 398 | protected void onDestroy() { 399 | super.onDestroy(); 400 | getContentResolver().unregisterContentObserver(contentObserver); 401 | } 402 | 403 | @Override 404 | public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, 405 | @NonNull int[] grantResults) { 406 | super.onRequestPermissionsResult(requestCode, permissions, grantResults); 407 | MainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults); 408 | } 409 | } 410 | 411 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_custom_login.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 15 | 16 | 23 | 24 | 31 | 32 |