├── .gitignore
├── README.md
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── library
├── .gitignore
├── build.gradle
└── src
│ └── main
│ ├── AndroidManifest.xml
│ └── java
│ └── com
│ └── quran
│ └── profiles
│ └── library
│ ├── QuranSync.java
│ ├── QuranSyncClient.java
│ ├── SyncResult.java
│ ├── api
│ ├── QuranSyncApi.java
│ ├── QuranSyncScribeApi.java
│ └── model
│ │ ├── Bookmark.java
│ │ ├── Pointer.java
│ │ └── Tag.java
│ └── util
│ └── ProxyHttpClient.java
├── sample
├── .gitignore
├── build.gradle
├── proguard-rules.txt
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── com
│ │ └── quran
│ │ └── profiles
│ │ └── sample
│ │ └── app
│ │ ├── Constants.java
│ │ ├── MainActivity.java
│ │ └── TagsFragment.java
│ └── res
│ ├── drawable-hdpi
│ └── ic_launcher.png
│ ├── drawable-mdpi
│ └── ic_launcher.png
│ ├── drawable-xhdpi
│ ├── ic_launcher.png
│ └── ic_tag.png
│ ├── drawable-xxhdpi
│ ├── ic_action_cancel.png
│ └── ic_launcher.png
│ ├── layout
│ ├── bookmark_item.xml
│ ├── main.xml
│ ├── tag_item.xml
│ └── tags_dialog.xml
│ └── values
│ └── strings.xml
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | .idea
4 | .DS_Store
5 | local.properties
6 | */build
7 | build
8 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## Quran Sync Android API Wrappers
2 | This is a work in progress, more information later insha'Allah.
3 |
4 | #### Open Source Projects Used
5 | * [scribe-java] (https://github.com/fernandezpablo85/scribe-java)
6 | * [retrofit] (http://square.github.io/retrofit)
7 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | mavenCentral()
6 | }
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:0.12.+'
9 | }
10 | }
11 |
12 | allprojects {
13 | repositories {
14 | mavenCentral()
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Settings specified in this file will override any Gradle settings
5 | # configured through the IDE.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/quran/qursync-android/40cbca8a91b6278f0ce203a30807355b194459c9/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Wed Apr 10 15:27:10 PDT 2013
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=http\://services.gradle.org/distributions/gradle-1.10-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # For Cygwin, ensure paths are in UNIX format before anything is touched.
46 | if $cygwin ; then
47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
48 | fi
49 |
50 | # Attempt to set APP_HOME
51 | # Resolve links: $0 may be a link
52 | PRG="$0"
53 | # Need this for relative symlinks.
54 | while [ -h "$PRG" ] ; do
55 | ls=`ls -ld "$PRG"`
56 | link=`expr "$ls" : '.*-> \(.*\)$'`
57 | if expr "$link" : '/.*' > /dev/null; then
58 | PRG="$link"
59 | else
60 | PRG=`dirname "$PRG"`"/$link"
61 | fi
62 | done
63 | SAVED="`pwd`"
64 | cd "`dirname \"$PRG\"`/" >&-
65 | APP_HOME="`pwd -P`"
66 | cd "$SAVED" >&-
67 |
68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
69 |
70 | # Determine the Java command to use to start the JVM.
71 | if [ -n "$JAVA_HOME" ] ; then
72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
73 | # IBM's JDK on AIX uses strange locations for the executables
74 | JAVACMD="$JAVA_HOME/jre/sh/java"
75 | else
76 | JAVACMD="$JAVA_HOME/bin/java"
77 | fi
78 | if [ ! -x "$JAVACMD" ] ; then
79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
80 |
81 | Please set the JAVA_HOME variable in your environment to match the
82 | location of your Java installation."
83 | fi
84 | else
85 | JAVACMD="java"
86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
87 |
88 | Please set the JAVA_HOME variable in your environment to match the
89 | location of your Java installation."
90 | fi
91 |
92 | # Increase the maximum file descriptors if we can.
93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
94 | MAX_FD_LIMIT=`ulimit -H -n`
95 | if [ $? -eq 0 ] ; then
96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
97 | MAX_FD="$MAX_FD_LIMIT"
98 | fi
99 | ulimit -n $MAX_FD
100 | if [ $? -ne 0 ] ; then
101 | warn "Could not set maximum file descriptor limit: $MAX_FD"
102 | fi
103 | else
104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
105 | fi
106 | fi
107 |
108 | # For Darwin, add options to specify how the application appears in the dock
109 | if $darwin; then
110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
111 | fi
112 |
113 | # For Cygwin, switch paths to Windows format before running java
114 | if $cygwin ; then
115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
158 | function splitJvmOpts() {
159 | JVM_OPTS=("$@")
160 | }
161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
163 |
164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
165 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/library/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/library/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'android-library'
2 |
3 | android {
4 | compileSdkVersion 19
5 | buildToolsVersion "19.1.0"
6 |
7 | defaultConfig {
8 | minSdkVersion 8
9 | targetSdkVersion 19
10 | versionCode 1
11 | versionName "1.0"
12 | }
13 |
14 | compileOptions {
15 | sourceCompatibility JavaVersion.VERSION_1_7
16 | targetCompatibility JavaVersion.VERSION_1_7
17 | }
18 | }
19 |
20 | dependencies {
21 | compile 'org.scribe:scribe:1.3.5'
22 | compile 'com.squareup.retrofit:retrofit:1.6.1'
23 | compile 'com.netflix.rxjava:rxjava-android:0.19.6'
24 | }
25 |
--------------------------------------------------------------------------------
/library/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/library/src/main/java/com/quran/profiles/library/QuranSync.java:
--------------------------------------------------------------------------------
1 | package com.quran.profiles.library;
2 |
3 | import com.google.gson.FieldNamingPolicy;
4 | import com.google.gson.Gson;
5 | import com.google.gson.GsonBuilder;
6 |
7 | import com.quran.profiles.library.api.QuranSyncApi;
8 | import com.quran.profiles.library.api.QuranSyncScribeApi;
9 | import com.quran.profiles.library.api.model.Bookmark;
10 | import com.quran.profiles.library.api.model.Pointer;
11 | import com.quran.profiles.library.api.model.Tag;
12 |
13 | import org.scribe.builder.ServiceBuilder;
14 | import org.scribe.model.OAuthConstants;
15 | import org.scribe.model.Token;
16 | import org.scribe.model.Verifier;
17 | import org.scribe.oauth.OAuthService;
18 |
19 | import android.os.Handler;
20 | import android.os.Message;
21 | import android.util.Log;
22 | import android.util.SparseArray;
23 |
24 | import java.util.HashSet;
25 | import java.util.List;
26 | import java.util.Set;
27 |
28 | import retrofit.RequestInterceptor;
29 | import retrofit.RestAdapter;
30 | import retrofit.converter.GsonConverter;
31 | import rx.Observable;
32 | import rx.android.schedulers.AndroidSchedulers;
33 | import rx.functions.Func1;
34 | import rx.functions.Func2;
35 | import rx.schedulers.Schedulers;
36 |
37 | /**
38 | * Api wrapper for QuranSync
39 | * Created by ahmedre on 5/18/14.
40 | */
41 | public class QuranSync {
42 |
43 | public static final String API_BASE = "http://profiles.quran.com/api/v1/";
44 | public static final int MSG_TOKEN_RECEIVED = 1;
45 |
46 | private static final String TAG = QuranSync.class.getName();
47 |
48 | private static QuranSync sInstance;
49 | private volatile Token mToken;
50 | private OAuthService mService;
51 | private QuranSyncApi mApi;
52 | private final Object mLock = new Object();
53 |
54 | public static synchronized QuranSync getInstance(
55 | String apiKey, String apiSecret, String callback) {
56 | if (sInstance == null) {
57 | sInstance = new QuranSync(apiKey, apiSecret, callback);
58 | }
59 | return sInstance;
60 | }
61 |
62 | private QuranSync(String apiKey, String apiSecret, String callback) {
63 | mService = new ServiceBuilder()
64 | .provider(QuranSyncScribeApi.class)
65 | .apiKey(apiKey)
66 | .apiSecret(apiSecret)
67 | .callback(callback)
68 | .build();
69 |
70 | Gson gson = new GsonBuilder()
71 | .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
72 | .create();
73 | RestAdapter restAdapter = new RestAdapter.Builder()
74 | .setEndpoint(API_BASE)
75 | .setConverter(new GsonConverter(gson))
76 | // uncomment this to test with a proxy
77 | // .setClient(new ProxyHttpClient())
78 | .setRequestInterceptor(new RequestInterceptor() {
79 | @Override
80 | public void intercept(RequestFacade request) {
81 | request.addQueryParam(
82 | OAuthConstants.ACCESS_TOKEN, mToken.getToken());
83 | }
84 | }).build();
85 | mApi = restAdapter.create(QuranSyncApi.class);
86 | }
87 |
88 | public void setToken(String token) {
89 | synchronized (mLock) {
90 | mToken = new Token(token, "");
91 | }
92 | }
93 |
94 | public void clearToken() {
95 | synchronized (mLock) {
96 | mToken = null;
97 | }
98 | }
99 |
100 | public boolean isAuthorized() {
101 | synchronized (mLock) {
102 | return mToken != null;
103 | }
104 | }
105 |
106 | public String getAuthorizationUrl() {
107 | return mService.getAuthorizationUrl(null);
108 | }
109 |
110 | public void getAccessToken(final String code, final Handler callback) {
111 | new Thread(new Runnable() {
112 | @Override
113 | public void run() {
114 | final Token token = mService.getAccessToken(null, new Verifier(code));
115 | synchronized (mLock) {
116 | mToken = token;
117 | }
118 |
119 | if (callback != null) {
120 | final Message message =
121 | callback.obtainMessage(MSG_TOKEN_RECEIVED, token.getToken());
122 | callback.sendMessage(message);
123 | }
124 | }
125 | }).start();
126 | }
127 |
128 | public Observable sync(final QuranSyncClient client) {
129 | Log.d(TAG, "sync");
130 |
131 | // setup a map of bookmark ids to bookmarks (for existing bookmarks)
132 | final List clientBookmarks = client.getBookmarks();
133 | final SparseArray localBookmarksMap = new SparseArray<>();
134 | for (Bookmark bookmark : clientBookmarks) {
135 | final Integer id = bookmark.getId();
136 | if (id != null) {
137 | localBookmarksMap.put(id, bookmark);
138 | }
139 | }
140 |
141 | // setup a map of tag ids to tags (for existing tags)
142 | final List clientTags = client.getTags();
143 | final SparseArray localTagsMap = new SparseArray<>();
144 | for (Tag tag : clientTags) {
145 | final Integer id = tag.getId();
146 | if (id != null) {
147 | localTagsMap.put(id, tag);
148 | }
149 | }
150 |
151 | // list of deleted tags
152 | final Set deletedTagIds = client.getDeletedTagIds();
153 | final Set deletedBookmarkIds = client.getDeletedBookmarkIds();
154 |
155 | // bookmarks related api requests
156 | final Observable> bookmarksObservable =
157 | mApi.getBookmarks()
158 | .flatMap(new Func1, Observable>() {
159 | @Override
160 | public Observable call(List bookmarkList) {
161 | Log.d(TAG, "got result back, processing...");
162 | final Set serverBookmarks = new HashSet<>();
163 | for (Bookmark b : bookmarkList) {
164 | serverBookmarks.add(b.getPointer());
165 | }
166 |
167 | final Observable additions =
168 | Observable.from(client.getBookmarks())
169 | .filter(new Func1() {
170 | @Override
171 | public Boolean call(Bookmark b) {
172 | return b.getId() == null &&
173 | !serverBookmarks.contains(b.getPointer());
174 | }
175 | });
176 |
177 | // we will return an observable of the server bookmarks
178 | // combined with any new client bookmarks
179 | return Observable.from(bookmarkList)
180 | .mergeWith(additions);
181 | }
182 | })
183 | .flatMap(new Func1>() {
184 | @Override
185 | public Observable call(Bookmark b) {
186 | Log.d(TAG, "considering: " + b.toString());
187 | final Integer id = b.getId();
188 | if (id == null) {
189 | // this is a new client bookmark, add it to server
190 | Log.d(TAG, "adding bookmark: " + b.toString());
191 | return mApi.addBookmark(b);
192 | } else if (deletedBookmarkIds.contains(id)) {
193 | // we explicitly deleted this on the client, so delete
194 | Log.d(TAG, "deleting bookmark: " + b.toString());
195 | return mApi.deleteBookmark(id);
196 | } else {
197 | // check if we had this bookmark already
198 | final Bookmark localBookmark = localBookmarksMap.get(id);
199 | if (localBookmark != null && localBookmark.isUpdateOf(b)) {
200 | // we had the bookmark, but it changed...
201 | Log.d(TAG, "updating bookmark: " + b.toString());
202 | return mApi.updateBookmark(id, localBookmark);
203 | } else {
204 | // bookmark is unchanged (or new on server)
205 | return Observable.from(b);
206 | }
207 | }
208 | }
209 | })
210 | // filter out the null bookmarks emitted by delete
211 | .filter(new Func1() {
212 | @Override
213 | public Boolean call(Bookmark bookmark) {
214 | return bookmark != null;
215 | }
216 | })
217 | .toList();
218 |
219 |
220 | // tags related api requests
221 | final Observable> tagsObservable =
222 | mApi.getTags()
223 | .flatMap(new Func1, Observable>() {
224 | @Override
225 | public Observable call(List tags) {
226 | // we will return an observable containing the server tags
227 | // combined with the new client tags
228 | return Observable.from(tags)
229 | .mergeWith(Observable.from(client.getTags())
230 | .filter(new Func1() {
231 | @Override
232 | public Boolean call(Tag tag) {
233 | return tag.getId() == null;
234 | }
235 | })
236 | );
237 | }
238 | })
239 | .flatMap(new Func1>() {
240 | @Override
241 | public Observable call(Tag tag) {
242 | final Integer id = tag.getId();
243 | if (id == null) {
244 | // this is a new tag
245 | return mApi.addTag(tag);
246 | } else if (deletedTagIds.contains(id)) {
247 | // we explicitly deleted this tag
248 | return mApi.deleteTag(id);
249 | } else {
250 | final Tag clientTag = localTagsMap.get(id);
251 | if (clientTag != null && clientTag.isUpdateOf(tag)) {
252 | // we have this tag, but we changed it
253 | return mApi.updateTag(id, clientTag);
254 | } else {
255 | // tag is unchanged (or new on server)
256 | return Observable.from(tag);
257 | }
258 | }
259 | }
260 | })
261 | // filter out the null tags emitted by delete
262 | .filter(new Func1() {
263 | @Override
264 | public Boolean call(Tag tag) {
265 | return tag != null;
266 | }
267 | }).toList();
268 |
269 | // run the bookmarks requests after tags is done
270 | return tagsObservable.flatMap(new Func1, Observable>() {
271 | @Override
272 | public Observable call(List tags) {
273 | return Observable.zip(bookmarksObservable, Observable.just(tags),
274 | new Func2, List, SyncResult>() {
275 | @Override
276 | public SyncResult call(List bookmarks, List tags) {
277 | final SyncResult result = new SyncResult();
278 | result.bookmarks = bookmarks;
279 | result.tags = tags;
280 | return result;
281 | }
282 | })
283 | .subscribeOn(Schedulers.io())
284 | .observeOn(AndroidSchedulers.mainThread());
285 | }
286 | });
287 | }
288 | }
289 |
--------------------------------------------------------------------------------
/library/src/main/java/com/quran/profiles/library/QuranSyncClient.java:
--------------------------------------------------------------------------------
1 | package com.quran.profiles.library;
2 |
3 | import com.quran.profiles.library.api.model.Bookmark;
4 | import com.quran.profiles.library.api.model.Tag;
5 |
6 | import java.util.List;
7 | import java.util.Set;
8 |
9 | public interface QuranSyncClient {
10 | public List getBookmarks();
11 | public Set getDeletedBookmarkIds();
12 | public List getTags();
13 | public Set getDeletedTagIds();
14 | }
15 |
--------------------------------------------------------------------------------
/library/src/main/java/com/quran/profiles/library/SyncResult.java:
--------------------------------------------------------------------------------
1 | package com.quran.profiles.library;
2 |
3 | import com.quran.profiles.library.api.model.Bookmark;
4 | import com.quran.profiles.library.api.model.Tag;
5 |
6 | import java.util.List;
7 |
8 | public class SyncResult {
9 | public List tags;
10 | public List bookmarks;
11 | }
12 |
--------------------------------------------------------------------------------
/library/src/main/java/com/quran/profiles/library/api/QuranSyncApi.java:
--------------------------------------------------------------------------------
1 | package com.quran.profiles.library.api;
2 |
3 | import com.quran.profiles.library.api.model.Bookmark;
4 | import com.quran.profiles.library.api.model.Tag;
5 |
6 | import java.util.List;
7 |
8 | import retrofit.http.Body;
9 | import retrofit.http.DELETE;
10 | import retrofit.http.GET;
11 | import retrofit.http.POST;
12 | import retrofit.http.PUT;
13 | import retrofit.http.Path;
14 | import rx.Observable;
15 |
16 | /**
17 | * QuranSync Retrofit Api
18 | * Created by ahmedre on 5/18/14.
19 | */
20 | public interface QuranSyncApi {
21 |
22 | @GET("/bookmarks")
23 | Observable> getBookmarks();
24 |
25 | @POST("/bookmarks")
26 | Observable addBookmark(@Body Bookmark params);
27 |
28 | @PUT("/bookmarks/{bookmarkId}")
29 | Observable updateBookmark(@Path("bookmarkId") int bookmarkId,
30 | @Body Bookmark params);
31 |
32 | @DELETE("/bookmarks/{bookmarkId}")
33 | Observable deleteBookmark(@Path("bookmarkId") int bookmarkId);
34 |
35 | @GET("/tags")
36 | Observable> getTags();
37 |
38 | @POST("/tags")
39 | Observable addTag(@Body Tag tag);
40 |
41 | @DELETE("/tags/{tagId}")
42 | Observable deleteTag(@Path("tagId") int tagId);
43 |
44 | @PUT("/tags/{tagId}")
45 | Observable updateTag(@Path("tagId") int tagId, @Body Tag params);
46 | }
47 |
--------------------------------------------------------------------------------
/library/src/main/java/com/quran/profiles/library/api/QuranSyncScribeApi.java:
--------------------------------------------------------------------------------
1 | package com.quran.profiles.library.api;
2 |
3 | import org.scribe.builder.api.DefaultApi20;
4 | import org.scribe.extractors.AccessTokenExtractor;
5 | import org.scribe.extractors.JsonTokenExtractor;
6 | import org.scribe.model.OAuthConfig;
7 | import org.scribe.model.Verb;
8 | import org.scribe.utils.OAuthEncoder;
9 |
10 | /**
11 | * Quran Sync OAuth 2.0 provider
12 | * Created by ahmedre on 5/18/14.
13 | */
14 | public class QuranSyncScribeApi extends DefaultApi20 {
15 | private static final String BASE_URL = "http://profiles.quran.com/oauth";
16 | private static final String AUTHORIZATION_URL = BASE_URL +
17 | "/authorize?client_id=%s&redirect_uri=%s&response_type=code";
18 |
19 | @Override
20 | public String getAccessTokenEndpoint() {
21 | return BASE_URL + "/token?grant_type=authorization_code";
22 | }
23 |
24 | @Override
25 | public String getAuthorizationUrl(OAuthConfig config) {
26 | return String.format(AUTHORIZATION_URL, config.getApiKey(),
27 | OAuthEncoder.encode(config.getCallback()));
28 | }
29 |
30 | @Override
31 | public Verb getAccessTokenVerb() {
32 | return Verb.POST;
33 | }
34 |
35 | @Override
36 | public AccessTokenExtractor getAccessTokenExtractor() {
37 | return new JsonTokenExtractor();
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/library/src/main/java/com/quran/profiles/library/api/model/Bookmark.java:
--------------------------------------------------------------------------------
1 | package com.quran.profiles.library.api.model;
2 |
3 | import java.util.Date;
4 | import java.util.List;
5 |
6 | /**
7 | * Bookmark object
8 | * Created by ahmedre on 5/18/14.
9 | */
10 | public class Bookmark {
11 | Integer id;
12 | String name;
13 | boolean isDefault;
14 | Date createdAt;
15 | Date updatedAt;
16 | String etag;
17 | Pointer pointer;
18 | Integer[] tagIds;
19 | List tags;
20 | Tag[] newTags;
21 | boolean overrideTags;
22 |
23 | public Bookmark() {
24 | }
25 |
26 | public Bookmark(String name, Pointer pointer) {
27 | this.name = name;
28 | this.pointer = pointer;
29 | }
30 |
31 | public Bookmark(Pointer pointer) {
32 | this.pointer = pointer;
33 | }
34 |
35 | public Integer getId() {
36 | return this.id;
37 | }
38 |
39 | public Pointer getPointer() {
40 | return this.pointer;
41 | }
42 |
43 | public String getName() {
44 | return this.name;
45 | }
46 |
47 | public void setName(String name) {
48 | this.name = name;
49 | }
50 |
51 | public String getEtag() {
52 | return this.etag;
53 | }
54 |
55 | public Date getCreatedDate() {
56 | return this.createdAt;
57 | }
58 |
59 | public Date getLastUpdatedDate() {
60 | return this.updatedAt;
61 | }
62 |
63 | public boolean isDefault() {
64 | return this.isDefault;
65 | }
66 |
67 | public void setDefault(boolean isDefault) {
68 | this.isDefault = isDefault;
69 | }
70 |
71 | public Integer[] getTagIds() {
72 | return this.tagIds;
73 | }
74 |
75 | public List getTags() {
76 | return this.tags;
77 | }
78 |
79 | public void setTags(List tags) {
80 | this.tags = tags;
81 | this.overrideTags = true;
82 | this.updatedAt = new Date();
83 | }
84 |
85 | public boolean isUpdateOf(Bookmark serverBookmark) {
86 | return this.updatedAt != null &&
87 | !this.updatedAt.equals(serverBookmark.getLastUpdatedDate());
88 | }
89 |
90 | @Override
91 | public String toString() {
92 | final StringBuilder builder = new StringBuilder("");
93 | if (name != null) {
94 | builder.append(name).append(" - ");
95 | }
96 | if (pointer != null) {
97 | builder.append(pointer.toString());
98 | }
99 | return builder.toString();
100 | }
101 | }
102 |
--------------------------------------------------------------------------------
/library/src/main/java/com/quran/profiles/library/api/model/Pointer.java:
--------------------------------------------------------------------------------
1 | package com.quran.profiles.library.api.model;
2 |
3 | /**
4 | * Pointer to a place in the Quran
5 | * Created by ahmedre on 5/18/14.
6 | */
7 | public class Pointer {
8 | Integer page;
9 | Integer chapter;
10 | Integer verse;
11 |
12 | public Pointer() {
13 | }
14 |
15 | public static Pointer fromPage(int page) {
16 | final Pointer p = new Pointer();
17 | p.page = page;
18 | return p;
19 | }
20 |
21 | public static Pointer fromAyah(int sura, int ayah) {
22 | final Pointer p = new Pointer();
23 | p.chapter = sura;
24 | p.verse = ayah;
25 | return p;
26 | }
27 |
28 | public Integer getPage() {
29 | return this.page;
30 | }
31 |
32 | public Integer getChapter() {
33 | return this.chapter;
34 | }
35 |
36 | public Integer getVerse() {
37 | return this.verse;
38 | }
39 |
40 |
41 | @Override
42 | public boolean equals(Object o) {
43 | if (this == o) {
44 | return true;
45 | }
46 |
47 | if (o == null || getClass() != o.getClass()) {
48 | return false;
49 | }
50 |
51 | Pointer pointer = (Pointer) o;
52 | return !(chapter != null ?
53 | !chapter.equals(pointer.chapter) : pointer.chapter != null) &&
54 | !(page != null ? !page.equals(pointer.page) : pointer.page != null) &&
55 | !(verse != null ? !verse.equals(pointer.verse) : pointer.verse != null);
56 |
57 | }
58 |
59 | @Override
60 | public int hashCode() {
61 | int result = page != null ? page.hashCode() : 0;
62 | result = 31 * result + (chapter != null ? chapter.hashCode() : 0);
63 | result = 31 * result + (verse != null ? verse.hashCode() : 0);
64 | return result;
65 | }
66 |
67 | @Override
68 | public String toString() {
69 | final StringBuilder builder = new StringBuilder("");
70 | if (page != null) {
71 | builder.append("Page: ").append(this.page);
72 | } else if (chapter != null && this.verse != null) {
73 | builder.append("Sura: ").append(this.chapter)
74 | .append(", Ayah: ").append(this.verse);
75 | }
76 | return builder.toString();
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/library/src/main/java/com/quran/profiles/library/api/model/Tag.java:
--------------------------------------------------------------------------------
1 | package com.quran.profiles.library.api.model;
2 |
3 | import java.util.Date;
4 |
5 | /**
6 | * Tag object
7 | * Created by ahmedre on 7/5/14.
8 | */
9 | public class Tag {
10 | Integer id;
11 | String name;
12 | Date updatedAt;
13 | String etag;
14 | String color;
15 | Integer[] bookmarkIds;
16 |
17 | public Tag() {
18 | }
19 |
20 | public Tag(String name) {
21 | this.name = name;
22 | }
23 |
24 | public Integer getId() {
25 | return this.id;
26 | }
27 |
28 | public String getName() {
29 | return this.name;
30 | }
31 |
32 | public String getEtag() {
33 | return this.etag;
34 | }
35 |
36 | public Date getLastUpdatedDate() {
37 | return this.updatedAt;
38 | }
39 |
40 | public boolean isUpdateOf(Tag serverTag) {
41 | return this.updatedAt != null &&
42 | !this.updatedAt.equals(serverTag.getLastUpdatedDate());
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/library/src/main/java/com/quran/profiles/library/util/ProxyHttpClient.java:
--------------------------------------------------------------------------------
1 | package com.quran.profiles.library.util;
2 |
3 | import org.apache.http.HttpHost;
4 | import org.apache.http.client.HttpClient;
5 | import org.apache.http.conn.params.ConnRoutePNames;
6 |
7 | import android.net.http.AndroidHttpClient;
8 |
9 | import java.io.IOException;
10 | import java.util.ArrayList;
11 | import java.util.List;
12 |
13 | import retrofit.client.ApacheClient;
14 | import retrofit.client.Header;
15 | import retrofit.client.Request;
16 | import retrofit.client.Response;
17 |
18 | public class ProxyHttpClient extends ApacheClient {
19 | private static HttpClient createDefaultClient() {
20 | final HttpClient client = AndroidHttpClient.newInstance("retrofit");
21 | final HttpHost proxy = new HttpHost("10.0.3.2", 8080, "http");
22 | client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
23 | return client;
24 | }
25 |
26 | public ProxyHttpClient() {
27 | super(createDefaultClient());
28 | }
29 |
30 | @Override
31 | public Response execute(Request request) throws IOException {
32 | List headers = request.getHeaders();
33 | List modified = new ArrayList<>();
34 | for (Header header : headers) {
35 | if (!header.getName().equals("Content-Length")) {
36 | modified.add(header);
37 | }
38 | }
39 | return super.execute(new Request(request.getMethod(),
40 | request.getUrl(), modified, request.getBody()));
41 | }
42 | }
--------------------------------------------------------------------------------
/sample/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/sample/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'android'
2 |
3 | android {
4 | compileSdkVersion 19
5 | buildToolsVersion "19.1.0"
6 |
7 | defaultConfig {
8 | minSdkVersion 8
9 | targetSdkVersion 19
10 | versionCode 1
11 | versionName "1.0"
12 | }
13 |
14 | buildTypes {
15 | release {
16 | runProguard false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
18 | }
19 | }
20 |
21 | compileOptions {
22 | sourceCompatibility JavaVersion.VERSION_1_7
23 | targetCompatibility JavaVersion.VERSION_1_7
24 | }
25 | }
26 |
27 | dependencies {
28 | compile project(':library')
29 | compile 'com.android.support:support-v4:19.1.0'
30 | }
31 |
--------------------------------------------------------------------------------
/sample/proguard-rules.txt:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /opt/android-sdk-macosx/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the ProGuard
5 | # include property in project.properties.
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 | #}
--------------------------------------------------------------------------------
/sample/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
9 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/quran/profiles/sample/app/Constants.java:
--------------------------------------------------------------------------------
1 | package com.quran.profiles.sample.app;
2 |
3 | /**
4 | * API Constants
5 | * Created by ahmedre on 5/18/14.
6 | */
7 | public class Constants {
8 | public static final String API_KEY = "";
9 | public static final String API_SECRET = "";
10 | public static final String CALLBACK = "";
11 | }
12 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/quran/profiles/sample/app/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.quran.profiles.sample.app;
2 |
3 | import com.quran.profiles.library.QuranSync;
4 | import com.quran.profiles.library.QuranSyncClient;
5 | import com.quran.profiles.library.SyncResult;
6 | import com.quran.profiles.library.api.model.Bookmark;
7 | import com.quran.profiles.library.api.model.Pointer;
8 | import com.quran.profiles.library.api.model.Tag;
9 |
10 | import android.content.Intent;
11 | import android.content.SharedPreferences;
12 | import android.net.Uri;
13 | import android.os.Bundle;
14 | import android.os.Handler;
15 | import android.os.Message;
16 | import android.preference.PreferenceManager;
17 | import android.support.v4.app.Fragment;
18 | import android.support.v4.app.FragmentActivity;
19 | import android.support.v4.app.FragmentManager;
20 | import android.support.v4.app.FragmentTransaction;
21 | import android.text.TextUtils;
22 | import android.util.Log;
23 | import android.view.LayoutInflater;
24 | import android.view.View;
25 | import android.view.ViewGroup;
26 | import android.widget.BaseAdapter;
27 | import android.widget.Button;
28 | import android.widget.ImageButton;
29 | import android.widget.ListView;
30 | import android.widget.TextView;
31 | import android.widget.Toast;
32 |
33 | import java.lang.ref.WeakReference;
34 | import java.util.ArrayList;
35 | import java.util.HashMap;
36 | import java.util.HashSet;
37 | import java.util.List;
38 | import java.util.Map;
39 | import java.util.Set;
40 |
41 | import rx.Subscription;
42 | import rx.android.observables.AndroidObservable;
43 | import rx.functions.Action1;
44 |
45 |
46 | public class MainActivity extends FragmentActivity {
47 | private static final String TAG =
48 | "com.quran.profiles.sample.app.MainActivity";
49 | private static final String TAG_TAGS_FRAGMENT = "TAG_TAGS_FRAGMENT";
50 |
51 | private static final String API_KEY = Constants.API_KEY;
52 | private static final String API_SECRET = Constants.API_SECRET;
53 | private static final String CALLBACK = Constants.CALLBACK;
54 |
55 | private static final String PREF_TOKEN = "pref_token";
56 | private static TokenHandler sHandler = new TokenHandler();
57 |
58 | private Button mButton;
59 | private Button mAddButton;
60 | private Button mSyncButton;
61 | private QuranSync mQuranSync;
62 | private SharedPreferences mPrefs;
63 | private List mBookmarks;
64 | private List mTags;
65 | private Bookmark mEditingBookmark;
66 | private BookmarksAdapter mAdapter;
67 | private Set mDeletions;
68 | private Set mTagDeletions;
69 | private Subscription mSubscription;
70 |
71 | static class TokenHandler extends Handler {
72 | private WeakReference mActivityReference;
73 |
74 | public void setActivity(MainActivity activity) {
75 | mActivityReference = new WeakReference<>(activity);
76 | }
77 |
78 | @Override
79 | public void handleMessage(Message msg) {
80 | if (mActivityReference != null) {
81 | final MainActivity activity = mActivityReference.get();
82 | if (activity != null) {
83 | activity.onAuthorized((String) msg.obj);
84 | }
85 | super.handleMessage(msg);
86 | }
87 | }
88 | }
89 |
90 | @Override
91 | protected void onCreate(Bundle savedInstanceState) {
92 | super.onCreate(savedInstanceState);
93 | mQuranSync = QuranSync.getInstance(API_KEY, API_SECRET, CALLBACK);
94 | mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
95 | final String tokenString = mPrefs.getString(PREF_TOKEN, null);
96 | if (tokenString != null) {
97 | mQuranSync.setToken(tokenString);
98 | }
99 |
100 | setContentView(R.layout.main);
101 | mButton = (Button) findViewById(R.id.authorize);
102 | mAddButton = (Button) findViewById(R.id.add_bookmark);
103 | mSyncButton = (Button) findViewById(R.id.sync);
104 | mButton.setOnClickListener(mOnClickListener);
105 | mAddButton.setOnClickListener(mOnClickListener);
106 | mSyncButton.setOnClickListener(mOnClickListener);
107 |
108 | final ListView listView = (ListView) findViewById(R.id.bookmarks);
109 | mAdapter = new BookmarksAdapter();
110 | listView.setAdapter(mAdapter);
111 |
112 | mBookmarks = new ArrayList<>();
113 | mDeletions = new HashSet<>();
114 | mTagDeletions = new HashSet<>();
115 | mTags = new ArrayList<>();
116 |
117 | final boolean loggedIn = mQuranSync.isAuthorized();
118 | mButton.setText(!loggedIn ?
119 | R.string.authorize : R.string.logout);
120 | mAddButton.setEnabled(loggedIn);
121 | mSyncButton.setEnabled(loggedIn);
122 | handleIntent(getIntent());
123 | }
124 |
125 | @Override
126 | protected void onDestroy() {
127 | if (mSubscription != null) {
128 | mSubscription.unsubscribe();
129 | }
130 | super.onDestroy();
131 | }
132 |
133 | @Override
134 | protected void onStart() {
135 | super.onStart();
136 | sHandler.setActivity(this);
137 | }
138 |
139 | @Override
140 | protected void onStop() {
141 | sHandler.setActivity(null);
142 | super.onStop();
143 | }
144 |
145 | @Override
146 | protected void onNewIntent(Intent intent) {
147 | super.onNewIntent(intent);
148 | Log.d(TAG, "onNewIntent()");
149 | handleIntent(intent);
150 | }
151 |
152 | private View.OnClickListener mOnClickListener = new View.OnClickListener() {
153 | @Override
154 | public void onClick(View v) {
155 | switch (v.getId()) {
156 | case R.id.authorize: {
157 | if (!mQuranSync.isAuthorized()) {
158 | authorize();
159 | } else {
160 | mQuranSync.clearToken();
161 | mButton.setText(R.string.authorize);
162 | mAddButton.setEnabled(false);
163 | mSyncButton.setEnabled(false);
164 | }
165 | break;
166 | }
167 | case R.id.add_bookmark: {
168 | final int page = 1 + (int)(Math.random() * 604);
169 | final Bookmark bookmark = new Bookmark(Pointer.fromPage(page));
170 | addBookmark(bookmark);
171 | break;
172 | }
173 | case R.id.sync: {
174 | syncBookmarks();
175 | break;
176 | }
177 | }
178 | }
179 | };
180 |
181 | private void handleIntent(Intent intent) {
182 | Log.d(TAG, "handleIntent()");
183 | final Uri uri = intent.getData();
184 | if (uri != null) {
185 | Log.d(TAG, "got uri: " + uri);
186 | final String code = uri.getQueryParameter("code");
187 | mQuranSync.getAccessToken(code, sHandler);
188 | }
189 |
190 | if (mQuranSync.isAuthorized()) {
191 | syncBookmarks();
192 | }
193 | }
194 |
195 | public List getTags() {
196 | return mTags;
197 | }
198 |
199 | public List getCurrentBookmarkTags() {
200 | if (mEditingBookmark == null) {
201 | return new ArrayList<>();
202 | }
203 | return getTagsFor(mEditingBookmark);
204 | }
205 |
206 | private List getTagsFor(Bookmark b) {
207 | List tags = b.getTags();
208 | if (tags != null) {
209 | return tags;
210 | }
211 | tags = new ArrayList<>();
212 |
213 | final Integer[] ids = b.getTagIds();
214 | if (ids != null) {
215 | final Map tagHash = new HashMap<>();
216 | for (Tag t : mTags) {
217 | tagHash.put(t.getId(), t);
218 | }
219 |
220 | for (Integer id : ids) {
221 | final Tag tag = tagHash.get(id);
222 | if (tag != null) {
223 | tags.add(tag.getName());
224 | }
225 | }
226 | }
227 | return tags;
228 | }
229 |
230 | public void saveTags(List tags,
231 | List bookmarkTags,
232 | List tagDeletions) {
233 | mTags = tags;
234 | if (mEditingBookmark != null) {
235 | mEditingBookmark.setTags(bookmarkTags);
236 | }
237 |
238 | for (Integer id : tagDeletions) {
239 | mTagDeletions.add(id);
240 | }
241 | closeTagDialog();
242 | mAdapter.notifyDataSetChanged();
243 | }
244 |
245 | public void showTagsFragment(Bookmark b) {
246 | mEditingBookmark = b;
247 | final FragmentManager fm = getSupportFragmentManager();
248 | final FragmentTransaction ft = fm.beginTransaction();
249 | final Fragment prev = fm.findFragmentByTag(TAG_TAGS_FRAGMENT);
250 | if (prev != null) {
251 | ft.remove(prev);
252 | }
253 |
254 | final TagsFragment fragment = new TagsFragment();
255 | fragment.show(ft, TAG_TAGS_FRAGMENT);
256 | }
257 |
258 | public void closeTagDialog() {
259 | mEditingBookmark = null;
260 |
261 | final FragmentManager fm = getSupportFragmentManager();
262 | final FragmentTransaction ft = fm.beginTransaction();
263 | final Fragment prev = fm.findFragmentByTag(TAG_TAGS_FRAGMENT);
264 | if (prev != null) {
265 | ft.remove(prev);
266 | }
267 | ft.commit();
268 | }
269 |
270 | private void authorize() {
271 | final String url = mQuranSync.getAuthorizationUrl();
272 | final Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
273 | startActivity(i);
274 | }
275 |
276 | private void onAuthorized(String token) {
277 | mButton.setText(R.string.logout);
278 | mPrefs.edit()
279 | .putString(PREF_TOKEN, token).commit();
280 | mAddButton.setEnabled(true);
281 | mSyncButton.setEnabled(true);
282 | syncBookmarks();
283 | }
284 |
285 | public static class SyncClient implements QuranSyncClient {
286 | private List mBookmarks;
287 | private Set mDeletions;
288 | private List mTags;
289 | private Set mDeletedTagIds;
290 |
291 | public SyncClient(List bookmarks, Set deletedIds,
292 | List tags, Set deletedTagIds) {
293 | mBookmarks = bookmarks;
294 | mDeletions = deletedIds;
295 | mTags = tags;
296 | mDeletedTagIds = deletedTagIds;
297 | }
298 |
299 | @Override
300 | public List getBookmarks() {
301 | return mBookmarks;
302 | }
303 |
304 | @Override
305 | public Set getDeletedBookmarkIds() {
306 | return mDeletions;
307 | }
308 |
309 | @Override
310 | public List getTags() {
311 | return mTags;
312 | }
313 |
314 | @Override
315 | public Set getDeletedTagIds() {
316 | return mDeletedTagIds;
317 | }
318 | }
319 |
320 | private void syncBookmarks() {
321 | mAddButton.setEnabled(false);
322 | mSyncButton.setEnabled(false);
323 |
324 | final SyncClient client = new SyncClient(
325 | mBookmarks, mDeletions, mTags, mTagDeletions);
326 | mSubscription = AndroidObservable.bindActivity(this,
327 | mQuranSync.sync(client))
328 | .subscribe(new Action1() {
329 | @Override
330 | public void call(SyncResult result) {
331 | mDeletions.clear();
332 | mBookmarks = result.bookmarks;
333 | mTags = result.tags;
334 | mAdapter.notifyDataSetChanged();
335 |
336 | mAddButton.setEnabled(true);
337 | mSyncButton.setEnabled(true);
338 | Toast.makeText(MainActivity.this,
339 | getString(R.string.sync_done), Toast.LENGTH_SHORT).show();
340 | mSubscription = null;
341 | }
342 | });
343 | }
344 |
345 | private void addBookmark(Bookmark bookmark) {
346 | mBookmarks.add(bookmark);
347 | mAdapter.notifyDataSetChanged();
348 | }
349 |
350 | private void deleteBookmark(Bookmark bookmark) {
351 | if (bookmark.getId() != null) {
352 | mDeletions.add(bookmark.getId());
353 | }
354 | mBookmarks.remove(bookmark);
355 | mAdapter.notifyDataSetChanged();
356 | }
357 |
358 | private class BookmarksAdapter extends BaseAdapter {
359 | private LayoutInflater mInflater;
360 |
361 | public BookmarksAdapter() {
362 | mInflater = LayoutInflater.from(MainActivity.this);
363 | }
364 |
365 | @Override
366 | public int getCount() {
367 | return mBookmarks == null ? 0 : mBookmarks.size();
368 | }
369 |
370 | @Override
371 | public Object getItem(int position) {
372 | return mBookmarks.get(position);
373 | }
374 |
375 | @Override
376 | public long getItemId(int position) {
377 | return position;
378 | }
379 |
380 | @Override
381 | public View getView(int position, View convertView, ViewGroup parent) {
382 | ViewHolder vh;
383 | if (convertView == null) {
384 | convertView = mInflater.inflate(R.layout.bookmark_item, parent, false);
385 | vh = new ViewHolder();
386 | vh.tags = (TextView) convertView.findViewById(R.id.tags);
387 | vh.title = (TextView) convertView.findViewById(R.id.title);
388 | vh.tag = (ImageButton) convertView.findViewById(R.id.tag);
389 | vh.delete = (ImageButton) convertView.findViewById(R.id.delete);
390 | convertView.setTag(vh);
391 | }
392 | vh = (ViewHolder) convertView.getTag();
393 |
394 | final Bookmark bookmark = (Bookmark) getItem(position);
395 | vh.title.setText(bookmark.toString());
396 | final List tags = getTagsFor(bookmark);
397 | vh.tags.setText(TextUtils.join(", ", tags));
398 |
399 | vh.tag.setOnClickListener(new View.OnClickListener() {
400 | @Override
401 | public void onClick(View v) {
402 | showTagsFragment(bookmark);
403 | }
404 | });
405 | vh.delete.setOnClickListener(new View.OnClickListener() {
406 | @Override
407 | public void onClick(View v) {
408 | deleteBookmark(bookmark);
409 | }
410 | });
411 | return convertView;
412 | }
413 | }
414 |
415 | public static class ViewHolder {
416 | public TextView tags;
417 | public TextView title;
418 | public ImageButton tag;
419 | public ImageButton delete;
420 | }
421 | }
422 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/quran/profiles/sample/app/TagsFragment.java:
--------------------------------------------------------------------------------
1 | package com.quran.profiles.sample.app;
2 |
3 | import com.quran.profiles.library.api.model.Tag;
4 |
5 | import android.app.Activity;
6 | import android.content.Context;
7 | import android.os.Bundle;
8 | import android.support.v4.app.DialogFragment;
9 | import android.view.LayoutInflater;
10 | import android.view.View;
11 | import android.view.ViewGroup;
12 | import android.widget.BaseAdapter;
13 | import android.widget.Button;
14 | import android.widget.CheckBox;
15 | import android.widget.CompoundButton;
16 | import android.widget.EditText;
17 | import android.widget.ImageButton;
18 | import android.widget.ListView;
19 |
20 | import java.util.ArrayList;
21 | import java.util.HashSet;
22 | import java.util.List;
23 | import java.util.Set;
24 |
25 | public class TagsFragment extends DialogFragment {
26 | private EditText mTagEntry;
27 | private TagsAdapter mAdapter;
28 |
29 | @Override
30 | public View onCreateView(LayoutInflater inflater, ViewGroup container,
31 | Bundle savedInstanceState) {
32 | final View view = inflater.inflate(R.layout.tags_dialog, container, false);
33 | final ListView list = (ListView) view.findViewById(R.id.list_view);
34 | mAdapter = new TagsAdapter(getActivity());
35 | list.setAdapter(mAdapter);
36 |
37 | mTagEntry = (EditText) view.findViewById(R.id.text);
38 | final Button addTag = (Button) view.findViewById(R.id.add_tag);
39 | addTag.setOnClickListener(mOnClickListener);
40 |
41 | final Button doneButton = (Button) view.findViewById(R.id.done);
42 | doneButton.setOnClickListener(mOnClickListener);
43 | return view;
44 | }
45 |
46 | private View.OnClickListener mOnClickListener = new View.OnClickListener() {
47 | @Override
48 | public void onClick(View v) {
49 | switch (v.getId()) {
50 | case R.id.add_tag: {
51 | mAdapter.addTag(mTagEntry.getText().toString());
52 | mTagEntry.setText("");
53 | break;
54 | }
55 | case R.id.done: {
56 | mAdapter.done();
57 | }
58 | }
59 | }
60 | };
61 |
62 | private class TagsAdapter extends BaseAdapter {
63 | private List mTags;
64 | private List mSelectedStates;
65 | private List mDeletedTagIds;
66 | private LayoutInflater mInflater;
67 |
68 | public TagsAdapter(Context context) {
69 | mInflater = LayoutInflater.from(context);
70 | if (context instanceof MainActivity) {
71 | final MainActivity activity = (MainActivity) context;
72 | mTags = activity.getTags();
73 | List selectedTags = activity.getCurrentBookmarkTags();
74 |
75 | final Set selectedMap = new HashSet<>();
76 | for (String tagName : selectedTags) {
77 | selectedMap.add(tagName);
78 | }
79 |
80 | mSelectedStates = new ArrayList<>();
81 | for (Tag tag : mTags) {
82 | mSelectedStates.add(selectedMap.contains(tag.getName()));
83 | }
84 | mDeletedTagIds = new ArrayList<>();
85 | }
86 | }
87 |
88 | @Override
89 | public int getCount() {
90 | return mTags == null ? 0 : mTags.size();
91 | }
92 |
93 | @Override
94 | public Object getItem(int position) {
95 | return mTags.get(position);
96 | }
97 |
98 | @Override
99 | public long getItemId(int position) {
100 | return position;
101 | }
102 |
103 | @Override
104 | public View getView(final int position,
105 | View convertView, ViewGroup parent) {
106 | ViewHolder vh;
107 | if (convertView == null) {
108 | convertView = mInflater.inflate(R.layout.tag_item, parent, false);
109 | vh = new ViewHolder();
110 | vh.title = (CheckBox) convertView.findViewById(R.id.title);
111 | vh.delete = (ImageButton) convertView.findViewById(R.id.delete);
112 | convertView.setTag(vh);
113 | }
114 | vh = (ViewHolder) convertView.getTag();
115 | vh.title.setChecked(mSelectedStates.get(position));
116 |
117 | final Tag tag = mTags.get(position);
118 | vh.title.setText(tag.getName());
119 | vh.title.setOnCheckedChangeListener(
120 | new CompoundButton.OnCheckedChangeListener() {
121 | @Override
122 | public void onCheckedChanged(
123 | CompoundButton buttonView, boolean isChecked) {
124 | mSelectedStates.remove(position);
125 | mSelectedStates.add(position, isChecked);
126 | }
127 | });
128 | vh.delete.setOnClickListener(new View.OnClickListener() {
129 | @Override
130 | public void onClick(View v) {
131 | final Integer id = tag.getId();
132 | if (id != null) {
133 | mDeletedTagIds.add(id);
134 | }
135 | mTags.remove(position);
136 | mSelectedStates.remove(position);
137 | notifyDataSetChanged();
138 | }
139 | });
140 | return convertView;
141 | }
142 |
143 | public void addTag(String text) {
144 | final Tag t = new Tag(text);
145 | mTags.add(t);
146 | mSelectedStates.add(true);
147 | notifyDataSetChanged();
148 | }
149 |
150 | public void done() {
151 | final Activity activity = getActivity();
152 | if (activity instanceof MainActivity) {
153 | final List bookmarkTags = new ArrayList<>();
154 | final int size = mSelectedStates.size();
155 | for (int i=0; i
2 |
3 |
6 |
13 |
16 |
19 |
20 |
27 |
34 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/main.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
8 |
12 |
13 |
17 |
18 |
22 |
23 |
26 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/tag_item.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
6 |
12 |
19 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/tags_dialog.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
14 |
24 |
29 |
34 |
--------------------------------------------------------------------------------
/sample/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | QurSyncExample
4 | Authorize
5 | Log Out
6 | Add Bookmark
7 | Sync
8 | Sync Done
9 | Add a Tag
10 | Tag
11 | Done
12 |
13 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':library', ':sample'
2 |
--------------------------------------------------------------------------------