diff --git a/build.gradle b/build.gradle index 8ecb9860cbe5a1642bd6cc0b796544282ceb6608..12d1b6462e312e7dab0fa919ebc4043f72a8fd21 100644 --- a/build.gradle +++ b/build.gradle @@ -20,9 +20,9 @@ buildscript { } dependencies { - classpath 'com.android.tools.build:gradle:4.2.0'//升级gradle版本,兼容主界面获取资源文件方式 + classpath 'com.android.tools.build:gradle:7.1.2'//升级gradle版本,兼容主界面获取资源文件方式 - // A gradle plugin for getting java lambda support in java 6, 7 and android + // A gradle plugin for getting java lambda support in java 6, 7 and android // https://github.com/evant/gradle-retrolambda classpath 'me.tatarka:gradle-retrolambda:3.7.0' @@ -37,7 +37,7 @@ buildscript { // https://github.com/realm/realm-java classpath "io.realm:realm-gradle-plugin:3.5.0" - classpath 'com.google.gms:google-services:4.0.2' + classpath 'com.google.gms:google-services:4.3.10' // 添加agcp插件配置。 classpath 'com.huawei.agconnect:agcp:1.6.0.300' @@ -84,10 +84,10 @@ subprojects { } ext { - minSdkVersion = 18 - targetSdkVersion = 28 - compileSdkVersion = 32 - buildToolsVersion = '28.0.2'//30.0.2正常 + minSdkVersion = 24 + targetSdkVersion = 30 + compileSdkVersion = 34 + buildToolsVersion = '30.0.2'//30.0.2正常 libOkHttp3 = "com.squareup.okhttp3:okhttp:${okhttpVersion}" diff --git a/qftplib b/qftplib index c4ecfbcdbce945a7885ab426e8c6923b31c80186..1ee969909fc790d9e7382246afbb6c96be4fc9c7 160000 --- a/qftplib +++ b/qftplib @@ -1 +1 @@ -Subproject commit c4ecfbcdbce945a7885ab426e8c6923b31c80186 +Subproject commit 1ee969909fc790d9e7382246afbb6c96be4fc9c7 diff --git a/qpysdk/build.gradle b/qpysdk/build.gradle index 9e50b479fb3f7e6b19d1a21852439f86c748bafa..a69a9615bace73eabe7c96f14732a099b90a3cbb 100644 --- a/qpysdk/build.gradle +++ b/qpysdk/build.gradle @@ -11,7 +11,7 @@ android { versionName "1.0" ndk { - abiFilters 'armeabi-v7a',"arm64-v8a" + abiFilters "arm64-v8a"//,'armeabi-v7a' } } buildTypes { diff --git a/qpysdk/src/main/java/org/qpython/qpysdk/QPyConstants.java b/qpysdk/src/main/java/org/qpython/qpysdk/QPyConstants.java index a78709067bc8b54b723a0a172c3a933fd82e4a61..18d9114229632d3d6ea8e4ac8a6149300f0789bd 100644 --- a/qpysdk/src/main/java/org/qpython/qpysdk/QPyConstants.java +++ b/qpysdk/src/main/java/org/qpython/qpysdk/QPyConstants.java @@ -1,18 +1,15 @@ package org.qpython.qpysdk; -import android.os.Environment; - import com.quseit.config.BASE_CONF; -import com.quseit.util.FileUtils; public interface QPyConstants extends BASE_CONF { - final String WEB_PROJECT = "web"; - final String CONSOLE_PROJECT = "console"; - final String KIVY_PROJECT = "kivy"; - final String PYGAME_PROJECT = "pygame"; - final String QUIET_PROJECT = "quiet"; - final String QSL4A_PROJECT = "qsl4a"; + String WEB_PROJECT = "web"; + String CONSOLE_PROJECT = "console"; + String KIVY_PROJECT = "kivy"; + String PYGAME_PROJECT = "pygame"; + String QUIET_PROJECT = "quiet"; + String QSL4A_PROJECT = "qsl4a"; String BASE_PATH = "qpython"; String AD_URL = "https://apu2.quseit.com/ad/"; @@ -29,12 +26,11 @@ public interface QPyConstants extends BASE_CONF { String DFROM_PRJ2 = "projects"; String DFROM_PRJ3 = "projects3"; - final String KEY_PY3_RES = "setting.py3resource.path"; - final String KEY_NOTEBOOK_RES = "setting.notebook3sresource.path"; - final String KEY_NOTEBOOK2_RES = "setting.notebook2resource.path"; - + String KEY_PY3_RES = "setting.py3resource.path"; + String KEY_NOTEBOOK_RES = "setting.notebook3sresource.path"; + String KEY_NOTEBOOK2_RES = "setting.notebook2resource.path"; - String ABSOLUTE_PATH = Environment.getExternalStorageDirectory().getPath() + "/" + BASE_PATH; +// String ABSOLUTE_PATH = Environment.getExternalStorageDirectory().getPath() + "/" + BASE_PATH; // String ABSOLUTE_PATH = FileUtils.getPath().getPath() + "/" + BASE_PATH; // String PY_CACHE_PATH = ABSOLUTE_PATH+"/"+PY_CACHE; // String ABSOLUTE_LOG = ABSOLUTE_PATH + "/log/last.log"; diff --git a/qpysdk/src/main/java/org/qpython/qpysdk/utils/FileUtils.java b/qpysdk/src/main/java/org/qpython/qpysdk/utils/FileUtils.java index 5387e26bf8f62d99b554907f8443a8f14093d211..104644f9279a30277b8a0e8534c8c8d3686f32b5 100644 --- a/qpysdk/src/main/java/org/qpython/qpysdk/utils/FileUtils.java +++ b/qpysdk/src/main/java/org/qpython/qpysdk/utils/FileUtils.java @@ -3,6 +3,7 @@ package org.qpython.qpysdk.utils; import android.content.Context; import android.content.Intent; import android.net.Uri; +import android.support.v4.content.FileProvider; import android.util.Log; import java.io.File; @@ -79,7 +80,10 @@ public class FileUtils { //获取文件file的MIME类型 String type = getMIMEType(file); //设置intent的data和Type属性。 - intent.setDataAndType(/*uri*/Uri.fromFile(file), type); + Uri uri; + uri = FileProvider.getUriForFile(context,context.getPackageName() + ".provider",file); + intent.setDataAndType(uri, type); + //intent.setDataAndType(/*uri*/Uri.fromFile(file), type); //跳转 context.startActivity(intent); } diff --git a/qpysdk/src/main/libs/arm64-v8a/libSDL2.so b/qpysdk/src/main/libs/arm64-v8a/libSDL2.so deleted file mode 100755 index 479428c88bc73f00287da66fe7ff912095ae1812..0000000000000000000000000000000000000000 Binary files a/qpysdk/src/main/libs/arm64-v8a/libSDL2.so and /dev/null differ diff --git a/qpysdk/src/main/libs/arm64-v8a/libSDL2_gfx.so b/qpysdk/src/main/libs/arm64-v8a/libSDL2_gfx.so deleted file mode 100755 index 04a7d33ede212aa84fc729f5d75cca6e8a092e7c..0000000000000000000000000000000000000000 Binary files a/qpysdk/src/main/libs/arm64-v8a/libSDL2_gfx.so and /dev/null differ diff --git a/qpysdk/src/main/libs/arm64-v8a/libSDL2_image.so b/qpysdk/src/main/libs/arm64-v8a/libSDL2_image.so deleted file mode 100755 index d7c20bbbd83214078aec88903f2461f1e764442c..0000000000000000000000000000000000000000 Binary files a/qpysdk/src/main/libs/arm64-v8a/libSDL2_image.so and /dev/null differ diff --git a/qpysdk/src/main/libs/arm64-v8a/libSDL2_mixer.so b/qpysdk/src/main/libs/arm64-v8a/libSDL2_mixer.so deleted file mode 100755 index 72742e96a9874ff8bffa3da63c5d49301897585c..0000000000000000000000000000000000000000 Binary files a/qpysdk/src/main/libs/arm64-v8a/libSDL2_mixer.so and /dev/null differ diff --git a/qpysdk/src/main/libs/arm64-v8a/libSDL2_ttf.so b/qpysdk/src/main/libs/arm64-v8a/libSDL2_ttf.so deleted file mode 100755 index 1b1ac8e065cf5c1e01a5ae6addda626a1e12d310..0000000000000000000000000000000000000000 Binary files a/qpysdk/src/main/libs/arm64-v8a/libSDL2_ttf.so and /dev/null differ diff --git a/qpysdk/src/main/libs/arm64-v8a/libandroid-support.so b/qpysdk/src/main/libs/arm64-v8a/libandroid-support.so deleted file mode 100644 index aee30ce65c5419c5936450543bac51949cb259d6..0000000000000000000000000000000000000000 Binary files a/qpysdk/src/main/libs/arm64-v8a/libandroid-support.so and /dev/null differ diff --git a/qpysdk/src/main/libs/arm64-v8a/libmain.so b/qpysdk/src/main/libs/arm64-v8a/libmain.so deleted file mode 100755 index c635de54915cad18161f16886998819dd2bec57c..0000000000000000000000000000000000000000 Binary files a/qpysdk/src/main/libs/arm64-v8a/libmain.so and /dev/null differ diff --git a/qpysdk/src/main/libs/arm64-v8a/libpng16.so b/qpysdk/src/main/libs/arm64-v8a/libpng16.so deleted file mode 100755 index 76a0ef33946557abf5614aaa45ccdc1fd141fa92..0000000000000000000000000000000000000000 Binary files a/qpysdk/src/main/libs/arm64-v8a/libpng16.so and /dev/null differ diff --git a/qpysdk/src/main/libs/arm64-v8a/libpython2.7.so b/qpysdk/src/main/libs/arm64-v8a/libpython2.7.so deleted file mode 100644 index 4af0affd68294c6cd9b17c22dc33ad51ed123c79..0000000000000000000000000000000000000000 Binary files a/qpysdk/src/main/libs/arm64-v8a/libpython2.7.so and /dev/null differ diff --git a/qpysdk/src/main/libs/armeabi-v7a/libSDL2.so b/qpysdk/src/main/libs/armeabi-v7a/libSDL2.so deleted file mode 100755 index 5338e91eb7c895c5490d8ebb4df107bb74a7e1da..0000000000000000000000000000000000000000 Binary files a/qpysdk/src/main/libs/armeabi-v7a/libSDL2.so and /dev/null differ diff --git a/qpysdk/src/main/libs/armeabi-v7a/libSDL2_gfx.so b/qpysdk/src/main/libs/armeabi-v7a/libSDL2_gfx.so deleted file mode 100755 index 80d01e32a6192259d28d33dac2adb2865a53e225..0000000000000000000000000000000000000000 Binary files a/qpysdk/src/main/libs/armeabi-v7a/libSDL2_gfx.so and /dev/null differ diff --git a/qpysdk/src/main/libs/armeabi-v7a/libSDL2_image.so b/qpysdk/src/main/libs/armeabi-v7a/libSDL2_image.so deleted file mode 100755 index 03484635a939d1aad62acf8ca9f4de9826b3cab8..0000000000000000000000000000000000000000 Binary files a/qpysdk/src/main/libs/armeabi-v7a/libSDL2_image.so and /dev/null differ diff --git a/qpysdk/src/main/libs/armeabi-v7a/libSDL2_mixer.so b/qpysdk/src/main/libs/armeabi-v7a/libSDL2_mixer.so deleted file mode 100755 index c48ebb56e2fecf94b3043236e70cc57843dc14f7..0000000000000000000000000000000000000000 Binary files a/qpysdk/src/main/libs/armeabi-v7a/libSDL2_mixer.so and /dev/null differ diff --git a/qpysdk/src/main/libs/armeabi-v7a/libSDL2_ttf.so b/qpysdk/src/main/libs/armeabi-v7a/libSDL2_ttf.so deleted file mode 100755 index 98aeea150c4fb1561d9b97ea3aa154d37bbd5175..0000000000000000000000000000000000000000 Binary files a/qpysdk/src/main/libs/armeabi-v7a/libSDL2_ttf.so and /dev/null differ diff --git a/qpysdk/src/main/libs/armeabi-v7a/libmain.so b/qpysdk/src/main/libs/armeabi-v7a/libmain.so deleted file mode 100755 index 44643b21c6e73c42d6b88c56248cd91600663ad8..0000000000000000000000000000000000000000 Binary files a/qpysdk/src/main/libs/armeabi-v7a/libmain.so and /dev/null differ diff --git a/qpysdk/src/main/libs/armeabi-v7a/libpng16.so b/qpysdk/src/main/libs/armeabi-v7a/libpng16.so deleted file mode 100755 index a16e35123b39fe31f6b1256560617af7c2409194..0000000000000000000000000000000000000000 Binary files a/qpysdk/src/main/libs/armeabi-v7a/libpng16.so and /dev/null differ diff --git a/qpysdk/src/main/libs/armeabi-v7a/libpython2.7.so b/qpysdk/src/main/libs/armeabi-v7a/libpython2.7.so deleted file mode 100755 index 4b3fbaa56ef24f8e7c95dcb8b1b708cc79f9d129..0000000000000000000000000000000000000000 Binary files a/qpysdk/src/main/libs/armeabi-v7a/libpython2.7.so and /dev/null differ diff --git a/qpysdk/src/main/libs/armeabi-v7a/libqpysdk.so b/qpysdk/src/main/libs/armeabi-v7a/libqpysdk.so deleted file mode 100755 index 1b189d7977bb298a127f7366c512310266f2f7f0..0000000000000000000000000000000000000000 Binary files a/qpysdk/src/main/libs/armeabi-v7a/libqpysdk.so and /dev/null differ diff --git a/qpysl4a b/qpysl4a index faa0536122b1154b210e0ccebeec8faea4511ac8..b73a58468334023ccd6f7825dc13dd1d2db82be8 160000 --- a/qpysl4a +++ b/qpysl4a @@ -1 +1 @@ -Subproject commit faa0536122b1154b210e0ccebeec8faea4511ac8 +Subproject commit b73a58468334023ccd6f7825dc13dd1d2db82be8 diff --git a/qpython/build.gradle b/qpython/build.gradle index c78d86e18e74362e30d8f073ac549abf8a97d3b4..dd70c5724a8d1f8c575194cce21280809a460b4e 100644 --- a/qpython/build.gradle +++ b/qpython/build.gradle @@ -15,13 +15,13 @@ android { defaultConfig { minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion - versionCode 323 - versionName "3.2.3" + versionCode 324 + versionName "3.2.4" multiDexEnabled true vectorDrawables.useSupportLibrary = true ndk { - abiFilters 'armeabi-v7a',"arm64-v8a" + abiFilters "arm64-v8a"//,'armeabi-v7a' } @@ -37,10 +37,10 @@ android { release { keyAlias 'zuowuxuxi' keyPassword 'myxiake1q' - storeFile file('qpython.key') + //storeFile file('qpython.key') storePassword 'myxiake1q' - v1SigningEnabled true - v2SigningEnabled false + v1SigningEnabled false + v2SigningEnabled true } debug { @@ -97,6 +97,9 @@ android { packagingOptions { exclude 'META-INF/LICENSE.txt' exclude 'META-INF/NOTICE.txt' + jniLibs { + useLegacyPackaging true + } } //设置渠道 @@ -107,10 +110,6 @@ android { applicationId "org.qpython.qpy" } os { -// resValue "string", "app_name", "Qpython" - applicationId "org.qpython.qpy" - } - od { // resValue "string", "app_name", "Qpython" applicationId "org.qpython.qpy" } @@ -126,9 +125,9 @@ android { } repositories { - flatDir { + /*flatDir { dirs 'libs' - } + }*/ } @@ -169,7 +168,7 @@ dependencies { api 'com.daimajia.numberprogressbar:library:1.2@aar' api 'org.litepal.android:core:1.3.1' api 'me.dm7.barcodescanner:zxing:1.9' - api 'com.android.support:multidex:1.0.1' + api 'com.android.support:multidex:1.0.3' implementation ('com.gyf.cactus:cactus-support:1.1.3-beta09'){ exclude group: 'com.google.guava' } @@ -177,8 +176,8 @@ dependencies { api rootProject.ext.libOkHttp3 api rootProject.ext.libOkHttp3Log - api 'com.squareup.okio:okio:1.9.0' - api 'com.google.code.gson:gson:2.7' + api 'com.squareup.okio:okio:1.14.0' + api 'com.google.code.gson:gson:2.8.9' api 'com.yanzhenjie:recyclerview-swipe:1.1.3' api rootProject.ext.libRxAndroid @@ -218,7 +217,7 @@ dependencies { api rootProject.ext.retrofitCoverterGson api rootProject.ext.retrofitAdapterRxjava - api 'com.android.support.constraint:constraint-layout:1.1.3' + api 'com.android.support.constraint:constraint-layout:2.0.4' // 微信 // opApi('com.tencent.mm.opensdk:wechat-sdk-android-with-mta:1.4.0') { @@ -243,4 +242,4 @@ dependencies { implementation rootProject.ext.huaweiAnlytics } -//apply plugin: 'com.google.gms.google-services' \ No newline at end of file +//apply plugin: 'com.google.gms.google-services' diff --git a/qpython/libs/arm64-v8a/lib-7z-elf.so b/qpython/libs/arm64-v8a/lib-7z-elf.so new file mode 100644 index 0000000000000000000000000000000000000000..d8943b67f9f991c56d22b2abbbc237671fa459fd Binary files /dev/null and b/qpython/libs/arm64-v8a/lib-7z-elf.so differ diff --git a/qpython/libs/arm64-v8a/lib-7z-txt.so b/qpython/libs/arm64-v8a/lib-7z-txt.so new file mode 100644 index 0000000000000000000000000000000000000000..605d0d58f24febf50cbe8d6ecbd7409c708e1f97 --- /dev/null +++ b/qpython/libs/arm64-v8a/lib-7z-txt.so @@ -0,0 +1 @@ +"$HOME/lib/p7zip/7z" "$@" \ No newline at end of file diff --git a/qpython/libs/arm64-v8a/lib-busybox.so b/qpython/libs/arm64-v8a/lib-busybox.so new file mode 100644 index 0000000000000000000000000000000000000000..032c9f90d56e6acc8802b61db66b2639a024a77c Binary files /dev/null and b/qpython/libs/arm64-v8a/lib-busybox.so differ diff --git a/qpython/libs/arm64-v8a/lib-python.so b/qpython/libs/arm64-v8a/lib-python.so new file mode 100644 index 0000000000000000000000000000000000000000..031a6be30a254fcee59b0dc7d0b28cd0abef028f Binary files /dev/null and b/qpython/libs/arm64-v8a/lib-python.so differ diff --git a/qpython/libs/arm64-v8a/lib-qpython3-setup.so b/qpython/libs/arm64-v8a/lib-qpython3-setup.so new file mode 100644 index 0000000000000000000000000000000000000000..ff4f7a4e08e4a5ada3481e5e0149e01d9562fb0f --- /dev/null +++ b/qpython/libs/arm64-v8a/lib-qpython3-setup.so @@ -0,0 +1,48 @@ +#!/system/bin/sh + +BIN=$HOME/bin + +if [ "$1" == "Setup" ]; then +ln -s -f $ANDROID_NATIVE_LIBRARY/lib-qpython3-setup.so $BIN/qpython3.sh +$BIN/qpython3.sh setup +exit +fi + +if [ "$1" != "setup" ]; then +exit +fi + +for i in python python3 python3.11 +do +ln -s $ANDROID_NATIVE_LIBRARY/lib-python.so $BIN/$i +done + +for i in busybox bash sh +do +ln -s $ANDROID_NATIVE_LIBRARY/lib-busybox.so $BIN/$i +done + +i=$ANDROID_NATIVE_LIBRARY/lib-7z +ln -s $i-elf.so $HOME/lib/p7zip/7z +ln -s $i-txt.so $BIN/7z + +for i in 1 2 +do +i=$HOME/private$i.7z +. 7z x $i -aoa -o$HOME +rm $i +done + +i=$HOME/public.7z +. 7z x $i -aoa -o$ANDROID_PUBLIC +rm $i + +for i in $(ls $BIN) +do +chmod 777 $BIN/$i +done + +python $HOME/setup.py + +sleep 3 +exit diff --git a/qpython/src/main/AndroidManifest.xml b/qpython/src/main/AndroidManifest.xml index 2d97480baf66112b8a1850826ad1479a7175c72a..7903d63eb2c78e0a2f358bdbd5c97c60362721aa 100644 --- a/qpython/src/main/AndroidManifest.xml +++ b/qpython/src/main/AndroidManifest.xml @@ -63,7 +63,7 @@ - + @@ -71,6 +71,8 @@ @@ -136,6 +139,7 @@ @@ -148,6 +152,7 @@ android:theme="@android:style/Theme.NoDisplay" android:launchMode="singleTask" android:documentLaunchMode="intoExisting" + android:exported="true" android:maxRecents="1"> @@ -166,6 +171,7 @@ @@ -252,6 +258,7 @@ @@ -290,6 +297,7 @@ @@ -305,9 +313,10 @@ @@ -319,6 +328,7 @@ @@ -329,6 +339,7 @@ @@ -348,6 +359,7 @@ android:configChanges="orientation|keyboard|keyboardHidden" android:label="@string/activity_shortcut_create" android:launchMode="singleTop" + android:exported="true" android:theme="@style/Theme.AppCompat"> @@ -399,6 +411,7 @@ android:configChanges="orientation"/> diff --git a/qpython/src/main/assets/resource3.mp3 b/qpython/src/main/assets/resource3.mp3 index 25061f0039c3a7aebf33fb05406d3228885af3f3..73aad3dd6aa69127bca7941447c91c4503e0e7d8 100644 Binary files a/qpython/src/main/assets/resource3.mp3 and b/qpython/src/main/assets/resource3.mp3 differ diff --git a/qpython/src/main/java/org/qpython/qpy/console/ScriptExec.java b/qpython/src/main/java/org/qpython/qpy/console/ScriptExec.java index ef6639b91f9ddc4df8d0c6160f1a125db73eb3a2..d9ca1b48ffa2936a23c5ad43fa42fd87ae4402b1 100644 --- a/qpython/src/main/java/org/qpython/qpy/console/ScriptExec.java +++ b/qpython/src/main/java/org/qpython/qpy/console/ScriptExec.java @@ -1,16 +1,12 @@ package org.qpython.qpy.console; import android.app.Activity; -import android.app.Notification; -import android.app.NotificationManager; -import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; -import android.os.Environment; import android.os.Message; import android.preference.PreferenceManager; import android.support.v4.app.ActivityCompat; @@ -21,6 +17,7 @@ import android.text.TextUtils; import android.util.Log; import org.qpython.qpy.main.app.App; +import org.qpython.qpy.main.app.CONF; import org.qpython.qpysdk.Exec; import com.quseit.util.FileUtils; import com.quseit.util.NAction; @@ -28,9 +25,7 @@ import com.quseit.util.NAction; import org.greenrobot.eventbus.EventBus; import org.qpython.qpy.R; import org.qpython.qpysdk.QPyConstants; -import org.qpython.qpysdk.utils.AndroidCompat; import org.qpython.qpy.console.util.TermSettings; -import org.qpython.qpy.main.activity.LogActivity; import org.qpython.qpy.main.utils.Utils; import org.qpython.qpysdk.utils.FileHelper; import org.qpython.qpysdk.utils.StreamGobbler; @@ -67,7 +62,7 @@ public class ScriptExec { return ScriptExecHolder.INSTANCE; } - public void playScript(Context context, String script, String arg, boolean notify) { + public void playScript(Context context, String script, String arg) { // confirm the SL4A Service is started context.startService(new Intent(context, QPyScriptService.class)); @@ -84,13 +79,13 @@ public class ScriptExec { if (isWeb) { playWebApp(context, script, arg); } else if (isKivy) { - playKScript(context, script, arg, notify); + playKScript(context, script, arg); } else if (isQApp) { - playQScript(context, script, arg, notify); + playQScript(context, script, arg); } else if (isGame) { - playGScript(context, script, arg, notify); + playGScript(context, script, arg); } else if (isDaemon) { - playDScript(context, script, arg, notify); + playDScript(context, script, arg); } else { playCScript(context, script, arg); } @@ -114,7 +109,7 @@ public class ScriptExec { File sf = new File(script); if (sf.exists()) { - playScript(context, script, args, notify); + playScript(context, script, args); } else { @@ -154,7 +149,7 @@ public class ScriptExec { env[0] = "TERM=" + term; env[1] = "PATH=" + context.getFilesDir()+"/bin"+":"+path; - if (!isQPy3) { + /*if (!isQPy3) { File py27so = new File(filesDir+"/lib/libpython2.7.so.1.0"); File py27soorg = new File(filesDir.getParentFile()+"/lib/libpython2.7.so"); @@ -169,7 +164,7 @@ public class ScriptExec { } } - } + }*/ env[2] = "LD_LIBRARY_PATH=.:" + filesDir + "/lib/" + ":" + filesDir + "/:" + filesDir.getParentFile() + "/lib/"; env[3] = "PYTHONHOME="+filesDir; @@ -213,7 +208,7 @@ public class ScriptExec { env[14] = "PYTHONSTARTUP="+filesDir+"/lib/python2.7/site-packages/qpy.py"; } - env[6] = "PYTHONOPTIMIZE=1"; //乘着船:修复__doc__为None + env[6] = "PYTHONOPTIMIZE=0"; //乘着船:修复__doc__为None File td = new File(externalStorage+"/cache"); if (!td.exists()) { @@ -227,7 +222,7 @@ public class ScriptExec { env[10] = "AP_HANDSHAKE="+SPFUtils.getSP(context, "sl4a.secue"); env[11] = "ANDROID_PUBLIC="+externalStorage; - env[12] = "ANDROID_PRIVATE="+context.getFilesDir().getAbsolutePath(); + env[12] = "ANDROID_NATIVE_LIBRARY="+ CONF.NATIVE_LIBRARY; env[13] = "ANDROID_ARGUMENT=\""+pyPath+"\""; env[15] = "QPY_USERNO="+ NAction.getUserNoId(context); @@ -320,7 +315,7 @@ public class ScriptExec { srv = "http://" + matcher1.group(1); } - playDScript(context, script, argv, false); + playDScript(context, script, argv); Utils.startWebActivityWithUrl(context, title, srv, script, isNoHead, isDrawer); // QWebViewActivity.start(context, "main", title, srv, script); } @@ -329,7 +324,7 @@ public class ScriptExec { /* Run KIVY Script */ - public void playKScript(Context context, final String script, String argv, boolean notify) { + public void playKScript(Context context, final String script, String argv) { if (Utils.isOpenGL2supported(context)) { File scriptParent = new File(script).getParentFile(); String proj, log; @@ -361,8 +356,8 @@ public class ScriptExec { /* Run Game Script */ - public void playGScript(Context context, final String script, String argv, boolean notify) { - playKScript(context,script,argv,notify); + public void playGScript(Context context, final String script, String argv) { + playKScript(context,script,argv); } @@ -385,7 +380,7 @@ public class ScriptExec { Run Daemon Script */ - public void playDScript(Context context, final String scriptPath, String argv1, boolean notify) { + public void playDScript(Context context, final String scriptPath, String argv1) { String logFile = getLastLog(); String[] mArgs = {scriptPath, " " + (argv1 != null ? argv1 : ""), logFile}; @@ -398,7 +393,7 @@ public class ScriptExec { Run Quiet Script */ FileDescriptor mFd; - public int playQScript(Context context, final String script, String argv, boolean notify) { + public int playQScript(Context context, final String script, String argv) { ArrayList mArguments = new ArrayList<>(); String binaryPath = getPyBin(context, true); diff --git a/qpython/src/main/java/org/qpython/qpy/console/ShellTermSession.java b/qpython/src/main/java/org/qpython/qpy/console/ShellTermSession.java index 94c31a836d2173bd27fec570635c673f86007b34..0d5ba05b36864e79b441c3da45f4ba994f5ecb42 100644 --- a/qpython/src/main/java/org/qpython/qpy/console/ShellTermSession.java +++ b/qpython/src/main/java/org/qpython/qpy/console/ShellTermSession.java @@ -19,11 +19,13 @@ import android.content.Context; import android.os.Handler; import android.os.Message; import android.os.ParcelFileDescriptor; +import android.preference.PreferenceManager; import android.util.Log; import com.quseit.util.FileHelper; import com.quseit.util.FileUtils; +import org.qpython.qpy.R; import org.qpython.qpy.console.compont.FileCompat; import org.qpython.qpy.console.util.TermSettings; @@ -113,11 +115,13 @@ public class ShellTermSession extends GenericTermSession { File enf = new File(context.getFilesDir()+"/bin/init.sh"); //if (! enf.exists()) { - String content = "#!/system/bin/sh"; - for (int i=0;i= 20) { - if (isRootEnable) { - scmd = getApplicationContext().getFilesDir() + "/bin/qpython" + (NAction.isQPy3(this) ? "3" : "") + "-android5-root.sh"; - } else { - scmd = getApplicationContext().getFilesDir() + "/bin/qpython" + (NAction.isQPy3(this) ? "3" : "") + "-android5.sh"; - } - } else {*/ + if (isRootEnable) { scmd = getApplicationContext().getFilesDir() + "/bin/qpython" + (NAction.isQPy3(this) ? "3" : "") + "-root.sh"; } else { @@ -1219,6 +1217,17 @@ public class TermActivity extends AppCompatActivity implements UpdateCallback, S return scmd; } + private TermSession setup(TermSettings settings) throws IOException { + SharedPreferences.Editor pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit(); + pref.putString("shell",getString(R.string.pref_shell_default)).apply(); + String filesDir = this.getFilesDir().getAbsolutePath(); + TermSession session = createTermSession(this, settings, + this.getApplicationInfo().nativeLibraryDir + "/lib-qpython3-setup.so Setup", + filesDir); + pref.putString("shell",filesDir+"/bin/bash").apply(); + return session; + } + private String checkPath(String path) { String[] dirs = path.split(":"); StringBuilder checkedPath = new StringBuilder(path.length()); diff --git a/qpython/src/main/java/org/qpython/qpy/console/TermService.java b/qpython/src/main/java/org/qpython/qpy/console/TermService.java index 9674b508a0b3c59936a8126fc82045cc9bf6422f..cefd8f66eaa67cb0fc10ba48a417ba25a3b6ed1c 100644 --- a/qpython/src/main/java/org/qpython/qpy/console/TermService.java +++ b/qpython/src/main/java/org/qpython/qpy/console/TermService.java @@ -79,7 +79,7 @@ public class TermService extends Service implements TermSession.FinishCallback { public int onStartCommand(Intent intent, int flags, int startId) { Intent resultIntent = new Intent(this, TermActivity.class); resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); - PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_ONE_SHOT); + PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_IMMUTABLE); Notification.Builder builder; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { @@ -189,7 +189,7 @@ public class TermService extends Service implements TermSession.FinishCallback { .putExtra(RemoteInterface.PRIVEXTRA_TARGET_WINDOW, sessionHandle); final PendingIntent result = PendingIntent.getActivity(getApplicationContext(), sessionHandle.hashCode(), - switchIntent, 0); + switchIntent, PendingIntent.FLAG_IMMUTABLE); final PackageManager pm = getPackageManager(); final String[] pkgs = pm.getPackagesForUid(getCallingUid()); diff --git a/qpython/src/main/java/org/qpython/qpy/console/util/TermSettings.java b/qpython/src/main/java/org/qpython/qpy/console/util/TermSettings.java index f466ca4ad5da5f1600540a2d833a501747eec711..ca46dcc0cb9ac0619caf4caa5b7e3801d14dfe20 100644 --- a/qpython/src/main/java/org/qpython/qpy/console/util/TermSettings.java +++ b/qpython/src/main/java/org/qpython/qpy/console/util/TermSettings.java @@ -17,6 +17,7 @@ package org.qpython.qpy.console.util;/* import android.content.SharedPreferences; import android.content.res.Resources; +import android.preference.PreferenceManager; import android.view.KeyEvent; import org.qpython.qpy.R; diff --git a/qpython/src/main/java/org/qpython/qpy/main/activity/AppListActivity.java b/qpython/src/main/java/org/qpython/qpy/main/activity/AppListActivity.java index a1252ea54882a31b3f86e72a701ec951f3d5c204..7cb36555e9f41572a814dbb15d8425a0fcac8132 100644 --- a/qpython/src/main/java/org/qpython/qpy/main/activity/AppListActivity.java +++ b/qpython/src/main/java/org/qpython/qpy/main/activity/AppListActivity.java @@ -1,7 +1,5 @@ package org.qpython.qpy.main.activity; -import android.Manifest; -import android.app.ActivityManager; import android.app.AlertDialog; import android.app.LoaderManager; import android.app.PendingIntent; @@ -9,19 +7,14 @@ import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.Loader; -import android.content.pm.PackageManager; -import android.content.pm.ResolveInfo; import android.content.pm.ShortcutInfo; import android.content.pm.ShortcutManager; import android.graphics.drawable.Icon; import android.os.Build; import android.os.Bundle; import android.os.Handler; -import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; -import android.support.v4.app.ActivityCompat; -import android.support.v4.content.ContextCompat; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; @@ -123,7 +116,7 @@ public class AppListActivity extends BaseActivity implements LoaderManager.Loade if (isProj) { ScriptExec.getInstance().playProject(this, path, false); } else { - ScriptExec.getInstance().playScript(this, path, null, false); + ScriptExec.getInstance().playScript(this, path, null); } finish(); } @@ -136,7 +129,7 @@ public class AppListActivity extends BaseActivity implements LoaderManager.Loade adapter.setCallback(new AppListAdapter.Callback() { @Override public void runScript(QPyScriptModel item) { - ScriptExec.getInstance().playScript(AppListActivity.this, item.getPath(), null, false); + ScriptExec.getInstance().playScript(AppListActivity.this, item.getPath(), null); } @Override @@ -228,13 +221,13 @@ public class AppListActivity extends BaseActivity implements LoaderManager.Loade Intent pinnedShortcutCallbackIntent = mShortcutManager.createShortcutResultIntent(pinShortcutInfo); PendingIntent successCallback = PendingIntent.getBroadcast(this, 0, - pinnedShortcutCallbackIntent, 0); - LogUtil.e("createShortcut: " + "111111111111"); + pinnedShortcutCallbackIntent, PendingIntent.FLAG_IMMUTABLE); + //LogUtil.e("createShortcut: " + "111111111111"); mShortcutManager.requestPinShortcut(pinShortcutInfo, successCallback.getIntentSender()); - LogUtil.e("createShortcut: " + mBean.getLabel()); + //LogUtil.e("createShortcut: " + mBean.getLabel()); new Handler().postDelayed(() -> { - judgeShortcutNameV2("org.qpython.qpy"); + judgeShortcutNameV2(this.getPackageName()); // judgeShortcutName(mBean.getLabel()); },200); } diff --git a/qpython/src/od/java/org/qpython/qpy/main/activity/BaseActivity.java b/qpython/src/main/java/org/qpython/qpy/main/activity/BaseActivity.java similarity index 49% rename from qpython/src/od/java/org/qpython/qpy/main/activity/BaseActivity.java rename to qpython/src/main/java/org/qpython/qpy/main/activity/BaseActivity.java index 20c1e0e5e1a7cb35f76b4c0b172d851dc4ddfa5d..237e524ea80a7d6df65e60ddeae816a5b04e47e7 100644 --- a/qpython/src/od/java/org/qpython/qpy/main/activity/BaseActivity.java +++ b/qpython/src/main/java/org/qpython/qpy/main/activity/BaseActivity.java @@ -4,65 +4,47 @@ import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; -import android.content.pm.ResolveInfo; -import android.content.res.Configuration; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; +import android.provider.Settings; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v4.util.ArrayMap; -import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; -import android.widget.ArrayAdapter; import android.widget.Toast; -import android.text.TextUtils; -import com.quseit.util.FileUtils; -import com.quseit.util.NAction; import com.quseit.util.NUtil; import org.qpython.qpy.R; import org.qpython.qpy.console.ShellTermSession; import org.qpython.qpy.console.util.TermSettings; -import org.renpy.android.ResourceManager; import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.List; import java.util.Map; -import org.qpython.qpy.main.server.gist.TokenManager; +//import com.umeng.analytics.MobclickAgent; + public class BaseActivity extends AppCompatActivity { // QPython interfaces - private static final int SCRIPT_CONSOLE_CODE = 1237; - private static final int PID_INIT_VALUE = -1; - private static final int DEFAULT_BUFFER_SIZE = 8192; - private static final int LOG_NOTIFICATION_ID = (int) System.currentTimeMillis(); - - - //private FirebaseAnalytics mFirebaseAnalytics; - private ArrayList mArguments = new ArrayList<>(); - private InputStream mIn; - private OutputStream mOut; + //private static final int SCRIPT_CONSOLE_CODE = 1237; + //private static final int PID_INIT_VALUE = -1; + //private static final int DEFAULT_BUFFER_SIZE = 8192; + // private static final int LOG_NOTIFICATION_ID = (int) System.currentTimeMillis(); + //private ArrayList mArguments = new ArrayList<>(); + //private InputStream mIn; + //private OutputStream mOut; private Map mActionMap = new ArrayMap<>(); - private TermSettings mSettings; + //private TermSettings mSettings; private ShellTermSession session; - private boolean permissionGrant = true; + //private boolean permissionGrant = true; protected static ShellTermSession createTermSession(Context context, TermSettings settings, String initialCommand, String path) { ShellTermSession session = null; @@ -77,24 +59,30 @@ public class BaseActivity extends AppCompatActivity { return session; } - protected void toast(String content) { + /*protected void toast(String content) { Toast.makeText(this, content, Toast.LENGTH_SHORT).show(); - } + }*/ @Override protected void onResume() { super.onResume(); + //MobclickAgent.onPageStart(this.getLocalClassName()); + //MobclickAgent.onResume(this); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); - //mFirebaseAnalytics = FirebaseAnalytics.getInstance(this); + //MobclickAgent.setDebugMode(true); + //MobclickAgent.openActivityDurationTrack(false); + //MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType.E_UM_NORMAL); } @Override protected void onPause() { super.onPause(); + //MobclickAgent.onPageEnd(this.getLocalClassName()); + //MobclickAgent.onPause(this); } @Override @@ -111,6 +99,8 @@ public class BaseActivity extends AppCompatActivity { mActionMap.remove(action); } + + public final void checkPermissionDo(String[] permissions, PermissionAction action) { if (Build.VERSION.SDK_INT >= 23) { boolean granted = true; @@ -133,43 +123,21 @@ public class BaseActivity extends AppCompatActivity { // feedback public void onFeedback(String feedback) { + String app = getString(R.string.app_name); - int ver = NUtil.getVersinoCode(getApplicationContext()); + int ver = NUtil.getVersionCode(getApplicationContext()); String subject = MessageFormat.format(getString(com.quseit.android.R.string.feeback_email_title), app, ver, Build.PRODUCT); String lastError = ""; - String code = NAction.getCode(getApplicationContext()); - File log = new File(FileUtils.getPath(getApplicationContext()) + "/" + code + "_last_err.log"); + //String code = NAction.getCode(getApplicationContext()); + File log = new File(this.getExternalFilesDir("log") + "/qpython_last_error.log"); if (log.exists()) { lastError = com.quseit.util.FileHelper.getFileContents(log.getAbsolutePath()); } - String body = feedback.isEmpty() ? feedback : MessageFormat.format(getString(R.string.feedback_email_body), Build.PRODUCT, + String body = MessageFormat.format(getString(R.string.feedback_email_body), Build.PRODUCT, Build.VERSION.RELEASE, Build.VERSION.SDK, lastError, feedback); - - Intent twitterIntent = getPackageManager().getLaunchIntentForPackage("com.twitter.android"); - if (twitterIntent != null) { - List list = new ArrayList<>(); - list.add("Feedback with Twitter"); - list.add("Feedback with Email"); - new AlertDialog.Builder(this) - .setTitle(R.string.feedback) - .setNegativeButton(R.string.close, (dialog, which) -> dialog.dismiss()) - .setAdapter(new ArrayAdapter<>(this, R.layout.dialog_feedback, list), (dialog, which) -> { - if (which == 0) { - twitter(body); - } else { - email(subject, body); - } - }) - .show(); - } else { - email(subject, body); - } - } - - private void email(String subject, String body) { Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:" + getString(R.string.ui_feedback_mail))); intent.putExtra(Intent.EXTRA_SUBJECT, subject); @@ -185,103 +153,45 @@ public class BaseActivity extends AppCompatActivity { } } - private void twitter(String message) { - Intent tweetIntent = new Intent(Intent.ACTION_SEND); - if (message.isEmpty()){ - tweetIntent.putExtra(Intent.EXTRA_TEXT, "@qpython,"); - }else { - tweetIntent.putExtra(Intent.EXTRA_TEXT, "@qpython\n" + message); - } - tweetIntent.setType("text/plain"); - - PackageManager packManager = getPackageManager(); - List resolvedInfoList = packManager.queryIntentActivities(tweetIntent, PackageManager.MATCH_DEFAULT_ONLY); - - boolean resolved = false; - for (ResolveInfo resolveInfo : resolvedInfoList) { - if (resolveInfo.activityInfo.packageName.startsWith("com.twitter.android")) { - tweetIntent.setClassName( - resolveInfo.activityInfo.packageName, - resolveInfo.activityInfo.name); - resolved = true; - break; - } - } - if (resolved) { - startActivity(tweetIntent); - } else { - Intent i = new Intent(); - i.putExtra(Intent.EXTRA_TEXT, message); - i.setAction(Intent.ACTION_VIEW); - i.setData(Uri.parse("https://twitter.com/intent/tweet?text=" + urlEncode(message))); - startActivity(i); - Toast.makeText(this, "Twitter app isn't found", Toast.LENGTH_LONG).show(); - } - } - - private String urlEncode(String s) { - try { - return URLEncoder.encode(s, "UTF-8"); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - return ""; - } - } - - protected boolean checkExpired(final String resource, String filesDir, String tag) { + /*protected boolean checkExpired(final String resource, String filesDir, String tag) { ResourceManager resourceManager = new ResourceManager(this); + QPySDK qpysdk = new QPySDK(getBaseContext(),this); - String data_version = resourceManager.getString(resource + "_version"); - String disk_version = "0"; + String data_version = qpysdk.getVersion(); + /*String disk_version = "0"; // If no version, no unpacking is necessary. if (data_version == null) { return false; - } + }* / // Check the current disk version, if any. - String disk_version_fn = filesDir + "/" + tag + "_" + resource + ".version"; - - try { - byte buf[] = new byte[64]; - InputStream is = new FileInputStream(disk_version_fn); - int len = is.read(buf); - disk_version = new String(buf, 0, len); - is.close(); - } catch (Exception e) { - - disk_version = "0"; - - } - - if (!NUtil.isNumeric(disk_version)) { - disk_version = "0"; + String disk_version_fn = filesDir + "/lib/" + tag + "_" + resource + ".version"; - } + String disk_version = qpysdk.readDiskVersion(disk_version_fn); - if ((int) (Double.parseDouble(data_version) - Double.parseDouble(disk_version)) > 0 || disk_version.equals("0")) { + //LogUtil.d(TAG, "data_version:"+Math.round(Double.parseDouble(data_version))+"-disk_version:"+Math.round(Double.parseDouble(disk_version))+"-RET:"+(int)(Double.parseDouble(data_version)-Double.parseDouble(disk_version))); + if ( !disk_version.equals(data_version) || disk_version.equals("0")) { try { - FileOutputStream os = new FileOutputStream(disk_version_fn); + /*FileOutputStream os = new FileOutputStream(disk_version_fn); try { os.write(data_version.getBytes()); - os.close(); + os.close();* / + qpysdk.writeDataVersion(disk_version_fn,data_version); - } catch (IOException e) { + } catch (Exception e) { e.printStackTrace(); - //Mint.logException(e); - - } - - } catch (FileNotFoundException e) { + //Mint.logException(e) + } /*catch (FileNotFoundException e) { e.printStackTrace(); //Mint.logException(e); - } + }* / return true; } else { return false; } - } + }*/ public interface PermissionAction { void onGrant(); @@ -289,14 +199,16 @@ public class BaseActivity extends AppCompatActivity { void onDeny(); } - public void ifLogin(Login afterLogin) { + /*public void ifLogin(Login afterLogin) { if (!TextUtils.isEmpty(TokenManager.getToken())) { afterLogin.process(); } else { Toast.makeText(this, R.string.login_first, Toast.LENGTH_SHORT).show(); } } + public interface Login { void process(); - } -} \ No newline at end of file + }*/ + +} diff --git a/qpython/src/main/java/org/qpython/qpy/main/activity/FloatViewActivity.java b/qpython/src/main/java/org/qpython/qpy/main/activity/FloatViewActivity.java index ffee11a5a0117dd6f16f9fd819d300434d141b64..6f675912a5752bdb1e6228edee42124fdb26f40e 100644 --- a/qpython/src/main/java/org/qpython/qpy/main/activity/FloatViewActivity.java +++ b/qpython/src/main/java/org/qpython/qpy/main/activity/FloatViewActivity.java @@ -2,7 +2,6 @@ package org.qpython.qpy.main.activity; import android.annotation.SuppressLint; import android.app.Activity; -import android.content.Intent; import android.graphics.PixelFormat; import android.os.Build; import android.os.Bundle; @@ -16,6 +15,8 @@ import android.view.WindowManager; import android.widget.Button; import android.widget.Toast; +import org.json.JSONException; +import org.json.JSONObject; import org.qpython.qpy.R; import org.qpython.qpy.console.ScriptExec; import org.qpython.qsl4a.qsl4a.facade.FloatViewFacade; @@ -58,62 +59,63 @@ public class FloatViewActivity extends Activity @Override public void handleMessage(Message msg){ super.handleMessage(msg); - floatView((Intent) msg.obj); + floatView((JSONObject) msg.obj); } }; - floatView(getIntent()); + try { + floatView(new JSONObject(getIntent().getStringExtra("args"))); + } catch (JSONException ignored) {} } @SuppressLint("ClickableViewAccessibility") - public void floatView(final Intent intent){ - //Intent intent = getIntent(); - //if (intent==null) intent = new Intent(); + public void floatView(final JSONObject args){ WindowManager.LayoutParams layoutParams = null; int index; //悬浮按钮 Button floatButton = null; //悬浮窗文本 - String text=intent.getStringExtra("text"); + String text = getArg(args,"text"); //是否彩色文本 boolean isHtml = false; if (text == null) { - text = intent.getStringExtra("html"); + text = getArg(args,"html"); if (text == null) text = "drag move\nlong click close"; else isHtml = true; } //悬浮窗背景色 格式:aarrggbb或rrggbb - int backColor=colorToInt(intent.getStringExtra("backColor"),"7f7f7f7f"); + final Integer backColor = colorToInt(args,"backColor","7f7f7f7f"); //悬浮窗文字颜色 格式:aarrggbb或rrggbb - int textColor=colorToInt(intent.getStringExtra("textColor"),"ff000000"); + final Integer textColor = colorToInt(args,"textColor","ff000000"); //字体大小 - final int textSize=intent.getIntExtra("textSize",10); + final int textSize = getArgLast(args,"textSize",10); + //字体对齐 + final int textAlign = getArgLast(args,"textAlign",View.TEXT_ALIGNMENT_INHERIT); //单击移除 - final boolean clickRemove = intent.getBooleanExtra("clickRemove",true); + final boolean clickRemove = getArg(args,"clickRemove",true); //脚本路径 - final String script = intent.getStringExtra("script"); + final String script = getArg(args,"script"); //索引参数 - index = intent.getIntExtra("index",-1); + index = getArg(args,"index",buttons.size()); - boolean reinit = false; - if (index>=0) { - try { - floatButton = buttons.get(index); - if(floatButton==null){ - floatButton = new Button(this); - layoutParams = new WindowManager.LayoutParams(); - reinit = true; - } else layoutParams = params.get(index); - } catch (Exception e){ - index=-1; - } - } - if(index<0){ + byte reinit = 0; + if (index=buttons.size() */ { floatButton = new Button(this); layoutParams = new WindowManager.LayoutParams(); - index = buttons.size(); + floatButton.setTag(index); + buttons.add(floatButton); + params.add(layoutParams); + times.add(System.currentTimeMillis()); + operations.add("initial"); + reinit = -1; } - //WindowManager.LayoutParams finalLayoutParams = layoutParams; floatButton.setOnTouchListener(new View.OnTouchListener() { private int x; private int y; @@ -150,9 +152,9 @@ public class FloatViewActivity extends Activity if (operations.get(index).equals("click")) { if(script!=null){ //脚本参数 - //final String arg = intent.getStringExtra("arg"); + //final String arg = getArg(args,"arg"); ScriptExec.getInstance().playScript(FloatViewActivity.this, - script, intent.getStringExtra("arg"),false); + script, getArg(args,"arg")); } if (clickRemove) FloatViewFacade.removeButton(index); @@ -168,40 +170,39 @@ public class FloatViewActivity extends Activity floatButton.setText(HtmlUtil.textToHtml(text)); else floatButton.setText(text); - floatButton.setBackgroundColor(backColor); - floatButton.setTextColor(textColor); + if(backColor!=null) + floatButton.setBackgroundColor(backColor); + if(textColor!=null) + floatButton.setTextColor(textColor); floatButton.setTextSize(textSize); + if(textAlign != Integer.MIN_VALUE) + floatButton.setTextAlignment(textAlign); layoutParams.type=WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;//下拉通知栏不可见 // 设置Window flag,锁定悬浮窗 ,若不设置,悬浮窗会占用整个屏幕的点击事件,FLAG_NOT_FOCUSABLE不设置会导致菜单键和返回键失效 - layoutParams.flags = intent.getIntExtra("flag",DEFAULT_FLAG); + layoutParams.flags = getArg(args,"flag",DEFAULT_FLAG); layoutParams.format = PixelFormat.RGBA_8888; // 设置图片格式,效果为背景透明 //悬浮窗宽度 - int width = intent.getIntExtra("width",300); + int width = getArgLast(args,"width",300); if(width!=Integer.MIN_VALUE) layoutParams.width = width; //悬浮窗高度 - int height = intent.getIntExtra("height",150); + int height = getArgLast(args,"height",150); if (height!=Integer.MIN_VALUE) layoutParams.height = height; //起始横坐标,原点为屏幕中心 - int x = intent.getIntExtra("x",0); + int x = getArgLast(args,"x",0); if (x!=Integer.MIN_VALUE) layoutParams.x=x; //起始纵坐标,原点为屏幕中心 - int y = intent.getIntExtra("y",0); + int y = getArgLast(args,"y",0); if (y!=Integer.MIN_VALUE) layoutParams.y=y; //记录结果 try { - if(index>=buttons.size()){ + if(reinit<0){ windowManager.addView(floatButton, layoutParams); - floatButton.setTag(buttons.size()); - buttons.add(floatButton); - params.add(layoutParams); - times.add(System.currentTimeMillis()); - operations.add("initial"); } else { - if(reinit) { + if(reinit==1) { windowManager.addView(floatButton, layoutParams); buttons.set(index,floatButton); operations.set(index,"reinitial"); @@ -220,12 +221,54 @@ public class FloatViewActivity extends Activity finish(); } - private int colorToInt(String color,String defaultColor){ - if (color == null) { - color = defaultColor; - } else { - int len = color.length(); - if (len <= 6) { + private String getArg(JSONObject args,String flag){ + try { + return args.getString(flag); + } catch (JSONException e) { + return null; + } + } + + private int getArgLast(JSONObject args,String flag,int defaultValue){ + try { + return args.getInt(flag); + } catch (JSONException e) { + try { + if(args.getString(flag).equalsIgnoreCase("last")) + return Integer.MIN_VALUE; + } catch (Exception ignored) {} + } + return defaultValue; + } + + private int getArg(JSONObject args,String flag,int defaultValue){ + try { + return args.getInt(flag); + } catch (JSONException e) { + return defaultValue; + } + } + + private boolean getArg(JSONObject args,String flag,boolean defaultValue){ + try { + return args.getBoolean(flag); + } catch (JSONException e) { + return defaultValue; + } + } + + private Integer colorToInt(JSONObject args,String colorFlag,String defaultColor) { + String color = null; + try { + color = args.getString(colorFlag); + } catch (JSONException ignored) {} + if (color == null){ + color = defaultColor; + } else if (color.equalsIgnoreCase("last")){ + return null; + } else { + int len = color.length(); + if (len <= 6) { color = defaultColor.substring(0,2) + "000000".substring(len) + color; } } diff --git a/qpython/src/main/java/org/qpython/qpy/main/activity/GistDetailActivity.java b/qpython/src/main/java/org/qpython/qpy/main/activity/GistDetailActivity.java index 01651226b3ca7023bdf971121b7179b4af26b447..22206414c757d4f37d211c6731cf0b9fde9abf23 100644 --- a/qpython/src/main/java/org/qpython/qpy/main/activity/GistDetailActivity.java +++ b/qpython/src/main/java/org/qpython/qpy/main/activity/GistDetailActivity.java @@ -171,7 +171,7 @@ public class GistDetailActivity extends BaseActivity implements DetailView { // setTitle(title); } - @Subscribe + /*@Subscribe public void onEvent(GistEvent event) { switch (event.name) { case FORK: @@ -220,7 +220,7 @@ public class GistDetailActivity extends BaseActivity implements DetailView { } - } + }*/ /** * 发送评论 diff --git a/qpython/src/main/java/org/qpython/qpy/main/activity/HomeMainActivity.java b/qpython/src/main/java/org/qpython/qpy/main/activity/HomeMainActivity.java index 8fb7ad699129fcc1ea66e0fc82c2946f99a19b54..33e53577154c93dbbb3b3aeb91e6b140b21046e9 100644 --- a/qpython/src/main/java/org/qpython/qpy/main/activity/HomeMainActivity.java +++ b/qpython/src/main/java/org/qpython/qpy/main/activity/HomeMainActivity.java @@ -1,5 +1,7 @@ package org.qpython.qpy.main.activity; +import static org.qpython.qpysdk.QPyConstants.PYTHON_2; + import android.Manifest; import android.annotation.SuppressLint; import android.content.Context; @@ -7,7 +9,6 @@ import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; -import android.content.res.Resources; import android.databinding.DataBindingUtil; import android.net.Uri; import android.os.Bundle; @@ -25,7 +26,6 @@ import android.widget.Toast; import com.gyf.cactus.Cactus; import com.quseit.util.FileUtils; import com.quseit.util.NAction; -import com.quseit.util.Utils; import com.xiaomi.mipush.sdk.MiPushMessage; import com.xiaomi.mipush.sdk.PushMessageHelper; @@ -55,8 +55,6 @@ import java.util.Map; import java.util.Timer; import java.util.TimerTask; -import static org.qpython.qpysdk.QPyConstants.PYTHON_2; - /*** * Qpython主页 */ @@ -140,16 +138,16 @@ public class HomeMainActivity extends BaseActivity { } private void initIcon() { - switch (NAction.getQPyInterpreter(this)) { - case "3.x": + //switch (NAction.getQPyInterpreter(this)) { + // case "3.x": binding.icon.setImageResource(R.drawable.img_home_logo_3); - break; + /* break; case "2.x": binding.icon.setImageResource(R.drawable.img_home_logo); break; default: break; - } + }*/ } private void initUser() { @@ -165,7 +163,7 @@ public class HomeMainActivity extends BaseActivity { setHandler(); // startPyService(); Bus.getDefault().register(this); -// init();//20230302限制初始化 + openQpySDK(); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { UpdateHelper.checkConfUpdate(this, QPyConstants.BASE_PATH); } @@ -189,23 +187,19 @@ public class HomeMainActivity extends BaseActivity { private void initListener() { binding.ivScan.setOnClickListener(v -> Bus.getDefault().post(new StartQrCodeActivityEvent())); binding.login.setOnClickListener(v -> { - if (App.getUser() == null) { + /*if (App.getUser() == null) { sendEvent(getString(R.string.event_login)); startActivityForResult(new Intent(this, SignInActivity.class), LOGIN_REQUEST_CODE); } else { sendEvent(getString(R.string.event_me)); UserActivity.start(this); - } + }*/ }); binding.llTerminal.setOnClickListener(v -> { //openQpySDK(view -> { - if (NAction.isQPyInterpreterSet(HomeMainActivity.this)) { TermActivity.startActivity(HomeMainActivity.this); sendEvent(getString(R.string.event_term)); - } else { - init(); - } //}); }); @@ -224,7 +218,7 @@ public class HomeMainActivity extends BaseActivity { NotebookActivity.start(HomeMainActivity.this, null, false); break; case 2: - TermActivity.startShell(HomeMainActivity.this); + TermActivity.startShell(HomeMainActivity.this,"shell"); break; } }).setNegativeButton(getString(R.string.close), new DialogInterface.OnClickListener() { @@ -262,13 +256,9 @@ public class HomeMainActivity extends BaseActivity { }); binding.llQpyApp.setOnClickListener(v -> { //openQpySDK(view -> { - if (NAction.isQPyInterpreterSet(HomeMainActivity.this)) { AppListActivity.start(HomeMainActivity.this, AppListActivity.TYPE_SCRIPT); overridePendingTransition(R.anim.fade_in, R.anim.fade_out); sendEvent(getString(R.string.event_top)); - } else { - init(); - } //}); }); @@ -423,9 +413,8 @@ public class HomeMainActivity extends BaseActivity { .create() .show();*/ initQpySDK3(); - } else { - //clickListener.onClick(null); - } + } //clickListener.onClick(null); + } @Override @@ -433,6 +422,12 @@ public class HomeMainActivity extends BaseActivity { Toast.makeText(HomeMainActivity.this, getString(R.string.grant_storage_hint), Toast.LENGTH_SHORT).show(); } }); + try { + CONF.NATIVE_LIBRARY = this.getPackageManager().getApplicationInfo( + this.getPackageName(),PackageManager.GET_UNINSTALLED_PACKAGES).nativeLibraryDir; + } catch (PackageManager.NameNotFoundException e) { + e.printStackTrace(); + } } /** @@ -444,45 +439,24 @@ public class HomeMainActivity extends BaseActivity { initQPy(); initIcon(); } - private void initQpySDK() { + /*private void initQpySDK() { Log.d(TAG, "initQpySDK"); initQPy(); NAction.setQPyInterpreter(HomeMainActivity.this, "2.x"); initIcon(); - } + }*/ private void initQPy() { new Thread(() -> { QPySDK qpysdk = new QPySDK(HomeMainActivity.this, HomeMainActivity.this); - //这里会在切换qpy3的时候再次释放相关资源 - //qpysdk.extractRes(py3?"private33":"private3", HomeMainActivity.this.getFilesDir(),true); - File externalStorage = new File(FileUtils.getPath(App.getContext()), "qpython"); - //if (py3) { + File externalStorage = FileUtils.getPath(App.getContext()); qpysdk.extractRes("resource3", HomeMainActivity.this.getFilesDir(),true); - ScriptExec.getInstance().playScript(this, - "setup", null,false); - /*} else { - qpysdk.extractRes("private1", HomeMainActivity.this.getFilesDir()); - qpysdk.extractRes("private2", HomeMainActivity.this.getFilesDir()); - qpysdk.extractRes("private3", HomeMainActivity.this.getFilesDir()); - qpysdk.extractRes("public", new File(externalStorage + "/lib")); - }*/ + TermActivity.startShell(HomeMainActivity.this,"setup"); FileHelper.createDirIfNExists(externalStorage + "/cache"); FileHelper.createDirIfNExists(externalStorage + "/log"); - //FileHelper.createDirIfNExists(externalStorage + "/notebooks"); - //qpysdk.extractRes("ipynb", new File(externalStorage + "/notebooks")); - //clickListener.onClick(null); }).start(); } - /** - * 初始化QpySdk - */ - private void init() { - //启动时就申请权限,加载资源方法 - openQpySDK(); - } - @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); @@ -529,8 +503,8 @@ public class HomeMainActivity extends BaseActivity { String[] string = (String[]) msg.obj; ScriptExec.getInstance().playScript( HomeMainActivity.this, - string[0],string[1], - false); + string[0],string[1] + ); } }; AndroidFacade.handler = QPyInterfaceFacade.handler; diff --git a/qpython/src/main/java/org/qpython/qpy/main/activity/NotebookActivity.java b/qpython/src/main/java/org/qpython/qpy/main/activity/NotebookActivity.java index cbfaa6a3fb05bf16c8dd5b43fc35f2f614c8af48..8fbf16079cebd6050c919843a806413ad0a23247 100644 --- a/qpython/src/main/java/org/qpython/qpy/main/activity/NotebookActivity.java +++ b/qpython/src/main/java/org/qpython/qpy/main/activity/NotebookActivity.java @@ -436,7 +436,7 @@ public class NotebookActivity extends BaseActivity implements View.OnClickListen } } - @Override + //@Override public void toast(String msg) { Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); } diff --git a/qpython/src/main/java/org/qpython/qpy/main/activity/NotebookListActivity.java b/qpython/src/main/java/org/qpython/qpy/main/activity/NotebookListActivity.java index 28f2ec2bd720b0ef023f7bd1f527661343263f31..13dff868a1de49cde5f6f48a92daacecf725280d 100644 --- a/qpython/src/main/java/org/qpython/qpy/main/activity/NotebookListActivity.java +++ b/qpython/src/main/java/org/qpython/qpy/main/activity/NotebookListActivity.java @@ -5,7 +5,6 @@ import android.content.Intent; import android.content.res.Configuration; import android.databinding.DataBindingUtil; import android.os.Bundle; -import android.os.Environment; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; @@ -14,8 +13,6 @@ import com.quseit.util.FileUtils; import org.qpython.qpy.R; import org.qpython.qpy.databinding.ActivityNotebooklistBinding; import org.qpython.qpy.main.adapter.NotebookAdapter; -import org.qpython.qpy.main.app.App; -import org.qpython.qpysdk.QPyConstants; import java.io.File; @@ -32,7 +29,7 @@ public class NotebookListActivity extends BaseActivity { private ActivityNotebooklistBinding mBinding; private NotebookAdapter mNotebookAdapter; private File mRootFile; - private static final String sdcard = FileUtils.getQyPath(App.getContext()); + private static final String sdcard = FileUtils.getQyPath(); public static void start(Context context){ Intent intent = new Intent(context,NotebookListActivity.class); diff --git a/qpython/src/main/java/org/qpython/qpy/main/activity/QrCodeActivity.java b/qpython/src/main/java/org/qpython/qpy/main/activity/QrCodeActivity.java index 6106e4e88559a0a4662e4170a1718ddcae93bede..ac7862849840660ca516439d33ee8362e7676902 100644 --- a/qpython/src/main/java/org/qpython/qpy/main/activity/QrCodeActivity.java +++ b/qpython/src/main/java/org/qpython/qpy/main/activity/QrCodeActivity.java @@ -92,7 +92,7 @@ public class QrCodeActivity extends AppCompatActivity implements ZXingScannerVie if (ps.get("token") != null) { token = ps.get("token").get(0); } - ScriptExec.getInstance().playScript(this,getApplicationContext().getFilesDir() + "/bin/qedit4web.py", token, false); + ScriptExec.getInstance().playScript(this,getApplicationContext().getFilesDir() + "/bin/qedit4web.py", token); QBaseApp.getInstance().getAsyncHttpClient().get(this, qweLink, null, new AsyncHttpResponseHandler() { @Override diff --git a/qpython/src/main/java/org/qpython/qpy/main/activity/SettingActivity.java b/qpython/src/main/java/org/qpython/qpy/main/activity/SettingActivity.java index 62a109cc55b65c1dc838812b5574f9cb26512406..6b07602c649fd6a1db2b68c7943212fa5fb80c3e 100644 --- a/qpython/src/main/java/org/qpython/qpy/main/activity/SettingActivity.java +++ b/qpython/src/main/java/org/qpython/qpy/main/activity/SettingActivity.java @@ -41,7 +41,7 @@ public class SettingActivity extends AppCompatActivity { public static void restartApp(Context context) { Intent mStartActivity = new Intent(context, HomeMainActivity.class); //Replace StartActivity with the name of the first activity in your app int mPendingIntentId = 123456; - PendingIntent mPendingIntent = PendingIntent.getActivity(context, mPendingIntentId, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT); + PendingIntent mPendingIntent = PendingIntent.getActivity(context, mPendingIntentId, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE); AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent); System.exit(0); diff --git a/qpython/src/main/java/org/qpython/qpy/main/adapter/AppListAdapter.java b/qpython/src/main/java/org/qpython/qpy/main/adapter/AppListAdapter.java index a5cb6aa30d9a17bb795cf690ec0e02b49c4a96b4..e983bc5714d57363ae192d5a9c28a9ad2b95e59a 100644 --- a/qpython/src/main/java/org/qpython/qpy/main/adapter/AppListAdapter.java +++ b/qpython/src/main/java/org/qpython/qpy/main/adapter/AppListAdapter.java @@ -1,17 +1,10 @@ package org.qpython.qpy.main.adapter; -import android.app.Activity; -import android.app.PendingIntent; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; -import android.content.pm.ShortcutInfo; -import android.content.pm.ShortcutManager; import android.databinding.DataBindingUtil; -import android.graphics.drawable.Icon; import android.net.Uri; -import android.os.Build; -import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.util.Log; @@ -22,13 +15,11 @@ import android.widget.Toast; import org.qpython.qpy.R; import org.qpython.qpy.console.ScriptExec; import org.qpython.qpy.databinding.ItemAppListBinding; -import org.qpython.qpy.main.activity.AppListActivity; import org.qpython.qpy.main.model.AppModel; import org.qpython.qpy.main.model.LocalAppModel; import org.qpython.qpy.main.model.QPyScriptModel; import org.qpython.qpy.texteditor.EditorActivity; import org.qpython.qpy.texteditor.ui.view.EnterDialog; -import org.qpython.qsl4a.qsl4a.LogUtil; import android.support.v7.app.AlertDialog; @@ -232,7 +223,7 @@ public class AppListAdapter extends RecyclerView.Adapter movieDirs = null; - - //GoogleAnalyticsTracker tracker; - - @Override - public void onCreate() { - super.onCreate(); - CrashHandler crashHandler = CrashHandler.getInstance(); - //注册crashHandler类 - crashHandler.init(getApplicationContext()); - //tracker = GoogleAnalyticsTracker.getInstance(); -// String x = NAction.getExtP(getApplicationContext(), "ga_gap"); -// int xq = 30; -// if (!x.equals("")) { -// xq = Integer.valueOf(x); -// } -// String gtid = CONF.GOOGLE_TRACKER_ID; -// String gtid2 = NAction.getExtP(getApplicationContext(), "ga_gtid"); -// if (!gtid2.equals("")) { -// gtid = gtid2; -// } - //tracker.startNewSession(gtid, xq, getApplicationContext()); - } - - public void logout(Context context) { - } - - -} diff --git a/qpython/src/main/java/org/qpython/qpy/texteditor/TedAppWidgetProvider.java b/qpython/src/main/java/org/qpython/qpy/texteditor/TedAppWidgetProvider.java index 7e78751f9bb3b22c2ca09c04ae2c5866d7b3f592..7774f9174e7a907d3a5e863f40ae7c9b3762eddf 100644 --- a/qpython/src/main/java/org/qpython/qpy/texteditor/TedAppWidgetProvider.java +++ b/qpython/src/main/java/org/qpython/qpy/texteditor/TedAppWidgetProvider.java @@ -39,7 +39,7 @@ public class TedAppWidgetProvider extends AppWidgetProvider implements Constants intent.setData(Uri.fromFile(targetFile)); intent.putExtra(EXTRA_FORCE_READ_ONLY, pref.mReadOnly); - pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); + pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE); views = new RemoteViews(context.getPackageName(), R.layout.widget); diff --git a/qpython/src/main/java/org/qpython/qpy/texteditor/TedFragment.java b/qpython/src/main/java/org/qpython/qpy/texteditor/TedFragment.java index 5437225d2ebc3d0b7082e5f383815acf38dc4830..815334883f0e4fb678c7688725b67995378d2652 100644 --- a/qpython/src/main/java/org/qpython/qpy/texteditor/TedFragment.java +++ b/qpython/src/main/java/org/qpython/qpy/texteditor/TedFragment.java @@ -5,11 +5,9 @@ import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.databinding.DataBindingUtil; -import android.net.Uri; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.os.Bundle; -import android.os.Environment; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import android.support.v4.app.Fragment; @@ -277,7 +275,7 @@ public class TedFragment extends Fragment implements Constants, TextWatcher, Ind if (activity.mCurrentFilePath.contains("/projects")) { ScriptExec.getInstance().playProject(getActivity(), activity.mCurrentFilePath.replace("/main.py", ""), false); } else { - ScriptExec.getInstance().playScript(getActivity(), activity.mCurrentFilePath, null, false); + ScriptExec.getInstance().playScript(getActivity(), activity.mCurrentFilePath, null); } } } else { @@ -331,7 +329,7 @@ public class TedFragment extends Fragment implements Constants, TextWatcher, Ind public void SnippetsList() { boolean isQpy3 = NAction.isQPy3(getContext()); List listItems = new ArrayList<>(); - String baseDir = FileUtils.getQyPath(App.getContext()) + String baseDir = FileUtils.getQyPath() + "/" + QPyConstants.BASE_PATH; String path = baseDir + (isQpy3 ? "/snippets3/" : "/snippets/"); String files; @@ -368,7 +366,7 @@ public class TedFragment extends Fragment implements Constants, TextWatcher, Ind */ public void insertSnippet(String snippetName) throws IOException { boolean isQPy3 = NAction.isQPy3(getContext()); - String baseDir = FileUtils.getQyPath(App.getContext()) + String baseDir = FileUtils.getQyPath() + "/" + QPyConstants.BASE_PATH; String path = baseDir + (isQPy3 ? "/snippets3/" : "/snippets/"); String s; @@ -402,7 +400,7 @@ public class TedFragment extends Fragment implements Constants, TextWatcher, Ind public void saveCodeSnippet(String selectText) { boolean isQPy3 = NAction.isQPy3(getContext()); - String baseDir = FileUtils.getQyPath(App.getContext()) + String baseDir = FileUtils.getQyPath() + "/" + QPyConstants.BASE_PATH; String path = baseDir + (isQPy3 ? "/snippets3/" : "/snippets/"); diff --git a/qpython/src/main/java/org/qpython/qpy/utils/NotebookUtil.java b/qpython/src/main/java/org/qpython/qpy/utils/NotebookUtil.java index 9f8b6062256c7d3dcf01911464ca81dd3e06d6eb..f933ba76d2a7d486d20854b0c55c4a3536011b93 100644 --- a/qpython/src/main/java/org/qpython/qpy/utils/NotebookUtil.java +++ b/qpython/src/main/java/org/qpython/qpy/utils/NotebookUtil.java @@ -1,6 +1,5 @@ package org.qpython.qpy.utils; -import android.app.Activity; import android.content.Context; import android.os.Environment; import android.os.Handler; @@ -15,11 +14,9 @@ import com.quseit.util.NStorage; import com.quseit.util.NUtil; import org.apache.http.Header; -import org.qpython.qpy.R; import org.qpython.qpy.console.ScriptExec; import org.qpython.qpy.main.app.App; import org.qpython.qpysdk.QPyConstants; -import org.qpython.qpysdk.QPySDK; import java.io.File; import java.io.FileOutputStream; @@ -257,10 +254,10 @@ public class NotebookUtil { public static void startNotebookService2(Context context) { int notebookPid; if (NAction.isQPy3(context)) { - notebookPid = ScriptExec.getInstance().playQScript(context, context.getFilesDir().getAbsolutePath() + "/bin/nb_man.py", null,false); + notebookPid = ScriptExec.getInstance().playQScript(context, context.getFilesDir().getAbsolutePath() + "/bin/nb_man.py", null); } else { - notebookPid = ScriptExec.getInstance().playQScript(context, context.getFilesDir().getAbsolutePath() + "/bin/nb_man.py", null,false); + notebookPid = ScriptExec.getInstance().playQScript(context, context.getFilesDir().getAbsolutePath() + "/bin/nb_man.py", null); } Log.d("NotebookUtil", "startNotebookService2:"+notebookPid); NStorage.setSP(context, "notebook.pid", ""+notebookPid); @@ -268,9 +265,9 @@ public class NotebookUtil { public static void startNotebookService(Context context) { if (NAction.isQPy3(context)) { - ScriptExec.getInstance().playDScript(context, context.getFilesDir().getAbsolutePath() + "/bin/nb_man.py", null,false); + ScriptExec.getInstance().playDScript(context, context.getFilesDir().getAbsolutePath() + "/bin/nb_man.py", null); } else { - ScriptExec.getInstance().playDScript(context, context.getFilesDir().getAbsolutePath() + "/bin/nb2_man.py", null,false); + ScriptExec.getInstance().playDScript(context, context.getFilesDir().getAbsolutePath() + "/bin/nb2_man.py", null); } } diff --git a/qpython/src/main/java/org/qpython/qpy/utils/UpdateHelper.java b/qpython/src/main/java/org/qpython/qpy/utils/UpdateHelper.java index b6a22862370c37d1498e59c9962e49d78438bd17..e3dd0e6dbe0d52955c0455cacfce81a8e9bd2b1d 100644 --- a/qpython/src/main/java/org/qpython/qpy/utils/UpdateHelper.java +++ b/qpython/src/main/java/org/qpython/qpy/utils/UpdateHelper.java @@ -129,16 +129,16 @@ public class UpdateHelper { private static String confGetUpdateURL(Context context, int flag) { if (flag == 2) { - return QPyConstants.LOG_URL + context.getPackageName() + "/" + NUtil.getVersinoCode(context); + return QPyConstants.LOG_URL + context.getPackageName() + "/" + NUtil.getVersionCode(context); } else if (flag == 3) { - return QPyConstants.AD_URL + context.getPackageName() + "/" + NUtil.getVersinoCode(context) + "?" + return QPyConstants.AD_URL + context.getPackageName() + "/" + NUtil.getVersionCode(context) + "?" + NAction.getUserUrl(context.getApplicationContext()); } else if (flag == 5) { - return QPyConstants.IAP_LOG_URL + context.getPackageName() + "/" + NUtil.getVersinoCode(context) + "?" + return QPyConstants.IAP_LOG_URL + context.getPackageName() + "/" + NUtil.getVersionCode(context) + "?" + NAction.getUserUrl(context.getApplicationContext()); } else { - return QPyConstants.UPDATE_URL + context.getPackageName() + "/" + NUtil.getVersinoCode(context); + return QPyConstants.UPDATE_URL + context.getPackageName() + "/" + NUtil.getVersionCode(context); } } @@ -282,7 +282,7 @@ public class UpdateHelper { } catch (JSONException e) { e.printStackTrace(); } - if (lastPluginVer < currentPluginVer || NUtil.getVersinoCode(context.getApplicationContext()) < ver) { + if (lastPluginVer < currentPluginVer || NUtil.getVersionCode(context.getApplicationContext()) < ver) { //弹出提示更新 AlertDialog.Builder alert = new AlertDialog.Builder(context); final String finalDownloadUrl = downloadUrl; @@ -293,7 +293,7 @@ public class UpdateHelper { .setMessage(verName + "\n" + desc) .setPositiveButton(context.getString(com.quseit.android.R.string.up_soft), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { - if (NUtil.getVersinoCode(context.getApplicationContext()) < finalVer) { + if (NUtil.getVersionCode(context.getApplicationContext()) < finalVer) { //app更新 Intent intent = new Intent(); intent.setAction("android.intent.action.VIEW"); diff --git a/qpython/src/main/java/org/qpython/qpylib/MPyApi.java b/qpython/src/main/java/org/qpython/qpylib/MPyApi.java index daa779fe6e2c61bfb9074fbc3a3115445884767b..bad5eb4f75abac09876e7e9af8000fc22fbd9cbe 100644 --- a/qpython/src/main/java/org/qpython/qpylib/MPyApi.java +++ b/qpython/src/main/java/org/qpython/qpylib/MPyApi.java @@ -11,7 +11,6 @@ import android.content.IntentFilter; import android.content.ServiceConnection; import android.net.Uri; import android.os.Bundle; -import android.os.Environment; import android.os.Handler; import android.os.IBinder; import android.os.Message; @@ -119,7 +118,7 @@ public class MPyApi extends BaseActivity { String type = intent.getStringExtra(QPyConstants.EXTRA_CONTENT_URL1); String path = intent.getStringExtra(QPyConstants.EXTRA_CONTENT_URL2); if (type.equals("script")) { - ScriptExec.getInstance().playScript(this,path, null, true); + ScriptExec.getInstance().playScript(this,path, null); } else if (type.equals("project")) { ScriptExec.getInstance().playProject(this,path, false); } @@ -133,7 +132,7 @@ public class MPyApi extends BaseActivity { param = bundle.getString("param"); if (param != null && param.equals("fileapi")) { runMode = 2; - ScriptExec.getInstance().playScript(this,pyfile, null, false); + ScriptExec.getInstance().playScript(this,pyfile, null); } else { // Compatibility Mode if (pycode.contains("#qpy:console\n") || NAction.isQPy3(getApplicationContext())) { @@ -143,7 +142,7 @@ public class MPyApi extends BaseActivity { } String script = FileUtils.getAbsolutePath(App.getContext()) + "/cache/last.py"; FileHelper.putFileContents(this, script, pycode); - ScriptExec.getInstance().playScript(this,script, null, false); + ScriptExec.getInstance().playScript(this,script, null); } } } @@ -158,7 +157,7 @@ public class MPyApi extends BaseActivity { if (myURI != null) { String script = getApplicationContext().getFilesDir() + "/bin/share.py"; String param = myURI.toString(); - ScriptExec.getInstance().playQScript(this,script, param, false); + ScriptExec.getInstance().playQScript(this,script, param); } } @@ -170,7 +169,7 @@ public class MPyApi extends BaseActivity { String script = getApplicationContext().getFilesDir() + "/bin/share.py"; String param = sharedText; //new QPyTask().execute(script, param); - ScriptExec.getInstance().playQScript(this,script, param, false); + ScriptExec.getInstance().playQScript(this,script, param); // Update UI to reflect text being shared } @@ -180,7 +179,7 @@ public class MPyApi extends BaseActivity { Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM); if (imageUri != null) { //onMenu(); - ScriptExec.getInstance().playQScript(this, getApplicationContext().getFilesDir() + "/bin/share.py", imageUri.toString(), false); + ScriptExec.getInstance().playQScript(this, getApplicationContext().getFilesDir() + "/bin/share.py", imageUri.toString()); // Update UI to reflect image being shared } diff --git a/qpython/src/main/java/org/qpython/qpylib/MPyService.java b/qpython/src/main/java/org/qpython/qpylib/MPyService.java index f64633aba673d98cc9825d143bf0460c68f6dad9..b019f65aa71afb27c4e2a24e0a4c45c060c4f858 100644 --- a/qpython/src/main/java/org/qpython/qpylib/MPyService.java +++ b/qpython/src/main/java/org/qpython/qpylib/MPyService.java @@ -54,7 +54,7 @@ public class MPyService extends Service { String type = intent.getStringExtra(QPyConstants.EXTRA_CONTENT_URL1); String path = intent.getStringExtra(QPyConstants.EXTRA_CONTENT_URL2); if (type.equals("script")) { - ScriptExec.getInstance().playScript(MPyService.this, path, null, true); + ScriptExec.getInstance().playScript(MPyService.this, path, null); } else if (type.equals("project")) { ScriptExec.getInstance().playProject(MPyService.this, path, false); @@ -71,7 +71,7 @@ public class MPyService extends Service { if (param != null && param.equals("fileapi")) { runMode = 2; - ScriptExec.getInstance().playScript(MPyService.this, pyfile, null, false); + ScriptExec.getInstance().playScript(MPyService.this, pyfile, null); } else { // Compatibility Mode @@ -82,7 +82,7 @@ public class MPyService extends Service { } String script = FileUtils.getAbsolutePath(App.getContext()) + "/cache/last.py"; FileHelper.putFileContents(this, script, pycode); - ScriptExec.getInstance().playScript(MPyService.this, script, null, false); + ScriptExec.getInstance().playScript(MPyService.this, script, null); } } } @@ -95,7 +95,7 @@ public class MPyService extends Service { if (myURI != null) { String script = getApplicationContext().getFilesDir() + "/bin/share.py"; String param = myURI.toString(); - ScriptExec.getInstance().playScript(MPyService.this, script, param, false); + ScriptExec.getInstance().playScript(MPyService.this, script, param); } } @@ -103,14 +103,14 @@ public class MPyService extends Service { String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT); if (sharedText != null) { String script = getApplicationContext().getFilesDir() + "/bin/share.py"; - ScriptExec.getInstance().playScript(MPyService.this, script, sharedText, false); + ScriptExec.getInstance().playScript(MPyService.this, script, sharedText); } } void handleSendImage(Intent intent) { Uri imageUri = intent.getParcelableExtra(Intent.EXTRA_STREAM); if (imageUri != null) { - ScriptExec.getInstance().playQScript(MPyService.this, getApplicationContext().getFilesDir() + "/bin/share.py", imageUri.toString(), false); + ScriptExec.getInstance().playQScript(MPyService.this, getApplicationContext().getFilesDir() + "/bin/share.py", imageUri.toString()); } } diff --git a/qpython/src/main/res/raw/projects2.zip b/qpython/src/main/res/raw/projects2.zip deleted file mode 100644 index 1ae44ac1a18fb9d492a5cb4c85f92eedb56f8061..0000000000000000000000000000000000000000 Binary files a/qpython/src/main/res/raw/projects2.zip and /dev/null differ diff --git a/qpython/src/main/res/raw/scripts2.zip b/qpython/src/main/res/raw/scripts2.zip deleted file mode 100644 index 0a99086e1c8dd25a3cd542472c83a1b7b6dcc393..0000000000000000000000000000000000000000 Binary files a/qpython/src/main/res/raw/scripts2.zip and /dev/null differ diff --git a/qpython/src/od/AndroidManifest.xml b/qpython/src/od/AndroidManifest.xml deleted file mode 100644 index 608431c92777f5bc07c8816d735351e689b90336..0000000000000000000000000000000000000000 --- a/qpython/src/od/AndroidManifest.xml +++ /dev/null @@ -1,388 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/qpython/src/od/java/org/qpython/qpy/codeshare/ShareCodeUtil.java b/qpython/src/od/java/org/qpython/qpy/codeshare/ShareCodeUtil.java deleted file mode 100644 index 2c1982e328df718b0f7476b629a105ce91f27744..0000000000000000000000000000000000000000 --- a/qpython/src/od/java/org/qpython/qpy/codeshare/ShareCodeUtil.java +++ /dev/null @@ -1,643 +0,0 @@ -package org.qpython.qpy.codeshare; - -import android.app.Activity; -import android.content.SharedPreferences; -import android.preference.PreferenceManager; -import android.support.annotation.NonNull; -import android.util.Log; -import android.widget.Toast; - -import com.google.common.reflect.TypeToken; -import com.google.firebase.database.DataSnapshot; -import com.google.firebase.database.DatabaseError; -import com.google.firebase.database.DatabaseReference; -import com.google.firebase.database.FirebaseDatabase; -import com.google.firebase.database.ValueEventListener; -import com.quseit.util.ACache; -import com.quseit.util.FileHelper; -import com.quseit.util.FileUtils; -import com.quseit.util.NetStateUtil; - -import org.json.JSONObject; -import org.qpython.qpy.R; -import org.qpython.qpy.codeshare.pojo.BookmarkerList; -import org.qpython.qpy.codeshare.pojo.CloudFile; -import org.qpython.qpy.codeshare.pojo.Gist; -import org.qpython.qpy.codeshare.pojo.GistBase; -import org.qpython.qpy.main.app.App; -import org.qpython.qpy.texteditor.common.TextFileUtils; -import org.qpython.qpysdk.utils.DateTimeHelper; - -import java.io.File; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import rx.Observable; -import rx.functions.Action1; - -import static org.qpython.qpy.codeshare.CONSTANT.DOT_REPLACE; -import static org.qpython.qpy.codeshare.CONSTANT.SLASH_REPLACE; -import static org.qpython.qpy.main.server.CacheKey.CLOUD_FILE; - -/** - * FireBase database util - * Created by Hmei on 2017-08-10. - */ - -public class ShareCodeUtil { - private static final boolean CLEAR = false; - - private static final String CLOUD = "cloud"; - private static final String GIST = "gist"; - private static final String USER = "user"; - private static final String BASE = "base"; - private static final String GIST_LIST = "gist_list"; - private static final String HISTORY = "history"; - private static final String COMMENT = "comment"; - private static final String BOOKMARK = "bookmark"; - private static final String COMMIT = "commit"; - private static final String INDEX = "index"; - private static final String USAGE = "usage"; - private static final String PROJECT = "project"; - private static final String SCRIPT = "script"; - private static final String OTHER = "other"; - private static final String PROJECT_PATH = "/projects/"; - private static final String SCRIPTS_PATH = "/scripts/"; - - private static final int MAX_FILE = 100; - - private DatabaseReference reference; - private String email; - private String userName; - private String avatarUrl; - - private SharedPreferences sharedPreferences; - private int currentFileCount = -1; - - private ShareCodeUtil() { - reference = FirebaseDatabase.getInstance().getReference(); - if (App.getUser() != null) { - email = App.getUser().getEmail().replace(".", "_"); - userName = App.getUser().getUserName(); - avatarUrl = App.getUser().getAvatarUrl(); - sharedPreferences = PreferenceManager.getDefaultSharedPreferences(App.getContext()); - initUsage(null); - } else { - email = ""; - userName = ""; - avatarUrl = ""; - } - //LogUtil.d("ShareCodeUtil", "ShareCodeUtil:"+App.getUser().getEmail()); - - Log.d("ShareCodeUtil", "ShareCodeUtil:"+email); - } - - public static ShareCodeUtil getInstance() { - return ShareCodeHolder.INSTANCE; - } - - @SuppressWarnings({"DEBUG_ONLY"}) - public void clearAll() { - if (CLEAR) { - reference.child(CLOUD).child(email).removeValue( - (databaseError, databaseReference) -> - Toast.makeText(App.getContext(), "Clear", Toast.LENGTH_SHORT).show()); - } - } - - public void createScriptGist(String title, String desc, String msg, String content, DatabaseReference.CompletionListener listener) { - String date = DateTimeHelper.getDate(); - // Add to all gist repo - Gist gist = new Gist(); - gist.setTitle(title); - gist.setAuthor(userName); - gist.setAvatar(avatarUrl); - gist.setDescribe(desc); - gist.setDate(date); - DatabaseReference path = reference.child(GIST).child(SCRIPT).push();// gist/script/ - String gistId = path.getKey(); - path.setValue(gist, listener); - commitGist(gistId, msg, content, null, null); - - // Add to user repo - GistBase baseGist = new GistBase(); - baseGist.setAuthor(userName); - baseGist.setAvatar(avatarUrl); - baseGist.setDate(date); - baseGist.setTitle(title); - reference.child(USER).child(email).child(GIST_LIST).child(SCRIPT).child(gistId).setValue(baseGist);// user//gist_list/script/ - - // Add to base repo - reference.child(BASE).child(SCRIPT).child(gistId).setValue(baseGist); // base/script/ - } - - public void createProjectGist(String projectName, String desc, String msg, List paths, DatabaseReference.CompletionListener completionListener) { - for (String path : paths) { - File file = new File(path); - String code = TextFileUtils.readTextFile(file); - String fileName = file.getName().replace(".", DOT_REPLACE); - - String date = DateTimeHelper.getDate(); - // Add to all gist repo - Gist gist = new Gist(); - gist.setTitle(fileName); - gist.setAuthor(userName); - gist.setAvatar(avatarUrl); - gist.setDescribe(desc); - gist.setDate(date); - DatabaseReference subReference = reference.child(GIST).child(PROJECT);// gist/script/ - String gistId = subReference.getKey(); - subReference.child(gistId).child(projectName).child(fileName).setValue(gist, completionListener);// gist/project/// - commitGist(gistId, msg, code, projectName, fileName); - - // Add to user repo - GistBase baseGist = new GistBase(); - baseGist.setAuthor(userName); - baseGist.setAuthor(avatarUrl); - baseGist.setDate(date); - baseGist.setTitle(fileName); - // user//gist_list/project/// - reference.child(USER).child(email).child(GIST_LIST).child(PROJECT).child(gistId).child(projectName).child(fileName).setValue(baseGist); - - // Add to base repo - // base/project/// - reference.child(BASE).child(PROJECT).child(gistId).child(projectName).child(fileName).setValue(baseGist); - } - } - - public void commitGist(String gistId, String msg, String content, String projName, String fileName) { - Gist.HistoryBean historyBean = new Gist.HistoryBean(); - historyBean.setData(DateTimeHelper.getDate()); - historyBean.setMassage(msg); - historyBean.setContent(content); - if (projName != null) { - DatabaseReference subRe = reference.child(GIST).child(PROJECT).child(gistId).child(projName).child(fileName).child(HISTORY).push(); - String historyId = subRe.getKey(); - subRe.child(historyId).setValue(historyBean); // gist//history/} - } else { - DatabaseReference subRe = reference.child(GIST).child(SCRIPT).child(gistId).child(HISTORY).push(); - String historyId = subRe.getKey(); - subRe.child(historyId).setValue(historyBean); // gist//history/} - reference.child(GIST).child(SCRIPT).child(gistId).child("lastCommitCode").setValue(content); - } - } - - public void sendComment(String gistId, String comment, boolean isProj, CommentCallback callback) { - sendComment(gistId, "", comment, "", isProj, callback); - } - - /** - * @param comment 评论 - * @param reComment 被回复的评论 - */ - public void sendComment(String gistId, String to, String comment, String reComment, boolean isProj, CommentCallback callback) { - Gist.CommentBean commentBean = new Gist.CommentBean(); - commentBean.setFrom_content(comment); - commentBean.setData(DateTimeHelper.getDate()); - commentBean.setFrom(userName); - commentBean.setAvatar(avatarUrl); - commentBean.setRe(to); - commentBean.setRe_content(reComment); - callback.commentBean(commentBean); - DatabaseReference subRe = reference.child(GIST).child(isProj ? PROJECT : SCRIPT).child(gistId).child(COMMENT).push(); - String commentId = subRe.getKey(); - subRe.child(commentId).setValue(commentBean); - } - - public void bookmark(String gistId) { - reference.child(GIST).child(gistId).child(BOOKMARK).child(email).setValue(userName); - reference.child(USER).child(email).child(BOOKMARK).child(gistId).setValue(true); - } - - public void cancelBookmark(String gistId) { - reference.child(GIST).child(gistId).child(BOOKMARK).child(email).removeValue(); - reference.child(USER).child(email).child(BOOKMARK).child(gistId).removeValue(); - } - - public void getBaseScriptGistList(Action1> callback) { - reference.child(BASE).child(SCRIPT).addListenerForSingleValueEvent(new SimpleValueEventListener() { - @Override - public void onDataGet(HashMap value) { - handleKey(value,callback); - } - }); - } - - private void handleKey(HashMap value,Action1> callback){ - List dataList = new ArrayList<>(); - for (Object key : value.keySet()) { - GistBase gistBase = App.getGson().fromJson(new JSONObject((Map) value.get(key)).toString(), GistBase.class); - gistBase.setId((String) key); - dataList.add(gistBase); - } - Observable.just(dataList) - .subscribe(callback); - } - - public void getBaseProjectGistList(Action1> callback) { - reference.child(BASE).child(PROJECT).addListenerForSingleValueEvent(new SimpleValueEventListener() { - @Override - public void onDataGet(HashMap value) { -// List dataList = new ArrayList<>(); -// for (Object key : value.keySet()) { -// GistBase gistBase = App.getGson().fromJson(new JSONObject((Map) value.get(key)).toString(), GistBase.class); -// gistBase.setId((String) key); -// dataList.add(gistBase); -// } -// Observable.just(dataList) -// .subscribe(callback); - handleKey(value,callback); - } - }); - } - - public void getGistDetail(String gistId, boolean isProj, Action1 callback) { - reference.child(GIST).child(isProj ? PROJECT : SCRIPT).child(gistId).addListenerForSingleValueEvent(new SimpleValueEventListener() { - @Override - public void onDataGet(HashMap value) { - JSONObject jsonObject = new JSONObject(value); - Gist gist = App.getGson().fromJson(String.valueOf(jsonObject), Gist.class); - - HashMap historyMap = (HashMap) value.get(HISTORY); - if (historyMap != null) { - List historyList = new ArrayList<>(); - for (Object historyKey : historyMap.keySet()) { - Gist.HistoryBean historyBean = App.getGson().fromJson(String.valueOf(new JSONObject((Map) historyMap.get(historyKey))), Gist.HistoryBean.class); - historyBean.setHistoryId((String) historyKey); - historyList.add(historyBean); - } - gist.setHistory(historyList); - } - - HashMap commentMap = (HashMap) value.get(COMMENT); - if (commentMap != null) { - List commentList = new ArrayList<>(); - for (Object commentKey : commentMap.keySet()) { - Gist.CommentBean commentBean = App.getGson().fromJson(String.valueOf(new JSONObject((Map) commentMap.get(commentKey))), Gist.CommentBean.class); - commentBean.setId((String) commentKey); - commentList.add(commentBean); - } - gist.setComment(commentList); - } - - HashMap bookmarkMap = (HashMap) value.get(BOOKMARK); - if (bookmarkMap != null) { - List bookmarkerList = new ArrayList<>(); - for (Object bookmarkKey : bookmarkMap.keySet()) { - Gist.BookmarkerBean bookmarkerBean = App.getGson().fromJson(String.valueOf(new JSONObject((Map) bookmarkMap.get(bookmarkKey))), Gist.BookmarkerBean.class); - bookmarkerBean.setId((String) bookmarkKey); - bookmarkerList.add(bookmarkerBean); - } - gist.setBookmarker(bookmarkerList); - } - Observable.just(gist) - .subscribe(callback); - } - }); - } - - // TODO: 2017-08-14 Need to fix - public void getMyGistList(Action1> callback) { - reference.child(USER).child(GIST_LIST).addListenerForSingleValueEvent(new ValueEventListener() { - @Override - public void onDataChange(DataSnapshot dataSnapshot) { - HashMap object = (HashMap) dataSnapshot.getValue(); - List userGist = new ArrayList<>(); - if (object == null) { - return; - } - for (Object key : object.keySet()) { - userGist.add(App.getGson().fromJson(new JSONObject((Map) object.get(key)).toString(), GistBase.class)); - } - Observable.just(userGist) - .subscribe(callback); - } - - @Override - public void onCancelled(DatabaseError databaseError) { - - } - }); - } - - public void getMyBookmarkList(Action1> callback) { - reference.child(USER).child(BOOKMARK).addListenerForSingleValueEvent(new ValueEventListener() { - @Override - public void onDataChange(DataSnapshot dataSnapshot) { - HashMap object = (HashMap) dataSnapshot.getValue(); - List userGist = new ArrayList<>(); - if (object == null) { - return; - } - for (Object key : object.keySet()) { - userGist.add(App.getGson().fromJson(new JSONObject((Map) object.get(key)).toString(), BookmarkerList.class)); - } - Observable.just(userGist) - .subscribe(callback); - } - - @Override - public void onCancelled(DatabaseError databaseError) { - - } - }); - } - - public void getGistCommentList(String gistId, Action1> callback) { - reference.child(GIST).child(gistId).child(COMMENT).addListenerForSingleValueEvent(new ValueEventListener() { - @Override - public void onDataChange(DataSnapshot dataSnapshot) { - HashMap object = (HashMap) dataSnapshot.getValue(); - List commentList = new ArrayList<>(); - if (object == null) { - return; - } - for (Object key : object.keySet()) { - commentList.add(App.getGson().fromJson(new JSONObject((Map) object.get(key)).toString(), Gist.CommentBean.class)); - } - Observable.just(commentList) - .subscribe(callback); - } - - @Override - public void onCancelled(DatabaseError databaseError) { - - } - }); - } - - public boolean uploadFolder(String path, DatabaseReference.CompletionListener completionListener, int[] size) { - File folder = new File(path); - // 获取该文件夹下符合后缀文件及非隐藏文件 - - if (!folder.isDirectory()) { - return false; - } - List files = FileHelper.filterExt(folder, App.getContext().getResources().getStringArray(R.array.support_file_ext), size[0]); - if (files.size() == 0) { - Toast.makeText(App.getContext(), R.string.no_file, Toast.LENGTH_SHORT).show(); - return false; - } - - if (!hasSpace(files.size())) { - return false; - } - - for (File file : files) { - uploadFile(file.getAbsolutePath(), completionListener); - } - -// // 如果在project目录下 -// if ("projects".equals(folder.getName())) { -// DatabaseReference projNode = reference.child(CLOUD).child(email).child(PROJECT).child(folder.getName().replace(".", DOT_REPLACE)); -// for (int i = 0; i < files.size(); i++) { -// String date = DateTimeHelper.AGO_FULL_DATE_FORMATTER.format(new Date(files.get(i).lastModified())); -// String subPath = files.get(i).getAbsolutePath(); -// String subKey = subPath.substring(subPath.indexOf(folder.getName()) + folder.getName().length(), subPath.length()).replace(".", DOT_REPLACE).replace("/", SLASH_REPLACE); -// if (i == files.size() - 1) { -// projNode.child(subKey) -// .child(date) -// .setValue(TextFileUtils.readTextFile(files.get(i)), completionListener); -// } else { -// projNode.child(subKey) -// .child(date) -// .setValue(TextFileUtils.readTextFile(files.get(i))); -// } -// reference.child(CLOUD) -// .child(email) -// .child(INDEX) -// .child(PROJECT) -// .child(folder.getName().replace(".", DOT_REPLACE) + subKey) -// .setValue(date); -// } -// } else if ("scripts".equals(folder.getName())) { -// // 上传整个scripts文件夹 -// for (int i = 0; i < files.size(); i++) { -// String abs_path = files.get(i).getAbsolutePath(); -// String key = abs_path -// .substring(abs_path.indexOf(SCRIPTS_PATH) + SCRIPTS_PATH.length()) -// .replace(".", DOT_REPLACE) -// .replace("/", SLASH_REPLACE); -// DatabaseReference content = reference.child(CLOUD) -// .child(email) -// .child(SCRIPT) -// .child(key) -// .child(DateTimeHelper.AGO_FULL_DATE_FORMATTER.format(new Date(files.get(i).lastModified()))); -// if (i == files.size() - 1) { -// content.setValue(TextFileUtils.readTextFile(files.get(i)), completionListener); -// } else { -// content.setValue(TextFileUtils.readTextFile(files.get(i))); -// } -// -// reference.child(CLOUD) -// .child(email) -// .child(INDEX) -// .child(SCRIPT) -// .child(key) -// .setValue(DateTimeHelper.AGO_FULL_DATE_FORMATTER.format(new Date(files.get(i).lastModified()))); -// } -// } else { -// // 普通文件夹 -// int fileListSize = files.size(); -// for (File file : files) { -// fileListSize--; -// final String rootNode = "/qpython/"; -// String node = file.getAbsolutePath().substring(path.indexOf(rootNode) + rootNode.length()); -// DatabaseReference child = -// reference -// .child(CLOUD) -// .child(email)/*.child(folder.getName().replace(".", DOT_REPLACE))*/ -// .child(OTHER) -// .child(node.replace(".", DOT_REPLACE).replace("/", SLASH_REPLACE)) -// .child(DateTimeHelper.getDate()); -// if (fileListSize == 0) { -// child.setValue(TextFileUtils.readTextFile(file), completionListener); -// } else { -// child.setValue(TextFileUtils.readTextFile(file)); -// } -// -// reference.child(CLOUD) -// .child(email) -// .child(INDEX) -// .child(OTHER) -// .child(node.replace(".", DOT_REPLACE).replace("/", SLASH_REPLACE)) -// .setValue(DateTimeHelper.getDate()); -// } -// } - return true; - } - - public boolean uploadFile(String path, DatabaseReference.CompletionListener completionListener) { - File file = new File(path); - - if (!hasSpace(1)) { - return false; - } - - if (path.contains(PROJECT_PATH)) { - String subPath = path.substring(path.indexOf(PROJECT_PATH) + PROJECT_PATH.length()); - String projName = subPath.split("/")[0]; - reference.child(CLOUD) - .child(email) - .child(PROJECT) - .child(projName) - .child(subPath.replace(".", DOT_REPLACE).replace("/", SLASH_REPLACE).replace(projName, "")) - .child(DateTimeHelper.AGO_FULL_DATE_FORMATTER.format(new Date(file.lastModified()))) - .setValue(TextFileUtils.readTextFile(file), completionListener); - - reference.child(CLOUD) - .child(email) - .child(INDEX) - .child(PROJECT) - .child(subPath.replace(".", DOT_REPLACE).replace("/", SLASH_REPLACE)) - .setValue(DateTimeHelper.AGO_FULL_DATE_FORMATTER.format(new Date(file.lastModified()))); - } else if (path.contains(SCRIPTS_PATH)) { - reference.child(CLOUD) - .child(email) - .child(SCRIPT) - .child(file.getName().replace(".", DOT_REPLACE)) - .child(DateTimeHelper.AGO_FULL_DATE_FORMATTER.format(new Date(file.lastModified()))) - .setValue(TextFileUtils.readTextFile(file), completionListener); - - reference.child(CLOUD) - .child(email) - .child(INDEX) - .child(SCRIPT) - .child(file.getName().replace(".", DOT_REPLACE)) - .setValue(DateTimeHelper.AGO_FULL_DATE_FORMATTER.format(new Date(file.lastModified()))); - } else { - final String rootNode = "/qpython/"; - String uploadKey = path.substring(path.indexOf(rootNode) + rootNode.length()); - reference.child(CLOUD) - .child(email) - .child(OTHER) - .child(uploadKey.replace(".", DOT_REPLACE).replace("/", SLASH_REPLACE)) - .child(DateTimeHelper.getDate()) - .setValue(TextFileUtils.readTextFile(file), completionListener); - - reference.child(CLOUD) - .child(email) - .child(INDEX) - .child(OTHER) - .child(uploadKey.replace(".", DOT_REPLACE).replace("/", SLASH_REPLACE)) - .setValue(DateTimeHelper.getDate()); - } - return true; - } - - public void getFileContent(String path, Action1 callback) { - reference.child(CLOUD) - .child(email) - .child(path) - .addListenerForSingleValueEvent(new ValueEventListener() { - @Override - public void onDataChange(DataSnapshot dataSnapshot) { - HashMap dateContent = (HashMap) dataSnapshot.getValue(); - String latest = ""; - for (String s : dateContent.keySet()) { - latest = DateTimeHelper.isLater(s, latest) ? s : latest; - } - - Observable.just(dateContent.get(latest)) - .subscribe(callback); - } - - @Override - public void onCancelled(DatabaseError databaseError) { - - } - }); - } - - public void initUsage(Action1 callback) { - if (CLEAR) { - return; - } - if (currentFileCount == -1) { - if (NetStateUtil.isConnected(App.getContext())) { - reference.child(CLOUD) - .child(email) - .child(USAGE) - .addListenerForSingleValueEvent(new ValueEventListener() { - @Override - public void onDataChange(DataSnapshot dataSnapshot) { - if (dataSnapshot.getValue() != null) { - currentFileCount = ((Long) dataSnapshot.getValue()).intValue(); - } else { - currentFileCount = 0; - } - if (callback != null) { - Observable.just(currentFileCount) - .subscribe(callback); - } - } - - @Override - public void onCancelled(DatabaseError databaseError) { - - } - }); - } - } else { - callback.call(currentFileCount); - } - } - - public int changeUsage(int change) { - currentFileCount += change; - reference.child(CLOUD) - .child(email) - .child(USAGE) - .setValue(currentFileCount); - return currentFileCount; - } - - public void resetUsage(int value) { - currentFileCount = value; - reference.child(CLOUD) - .child(email) - .child(USAGE) - .setValue(currentFileCount); - } - - private boolean hasSpace(int waiting) { - if (currentFileCount < 0) { - Toast.makeText(App.getContext(), R.string.usage_not_init, Toast.LENGTH_SHORT).show(); - return false; - } else if (currentFileCount + waiting > MAX_FILE) { - Toast.makeText(App.getContext(), R.string.no_space, Toast.LENGTH_SHORT).show(); - return false; - } else { - return true; - } - } - - public interface CommentCallback { - void commentBean(Gist.CommentBean comment); - } - - private static class ShareCodeHolder { - private static final ShareCodeUtil INSTANCE = new ShareCodeUtil(); - } - - abstract class SimpleValueEventListener implements ValueEventListener { - @Override - public void onDataChange(DataSnapshot dataSnapshot) { - HashMap object = (HashMap) dataSnapshot.getValue(); - if (object == null) { - return; - } - onDataGet(object); - } - - @Override - public void onCancelled(DatabaseError databaseError) { - - } - - public abstract void onDataGet(HashMap value); - } -} \ No newline at end of file diff --git a/qpython/src/od/java/org/qpython/qpy/codeshare/pojo/CloudFile.java b/qpython/src/od/java/org/qpython/qpy/codeshare/pojo/CloudFile.java deleted file mode 100644 index 1231486b9fd094e236b4e40055bd31014ace99b5..0000000000000000000000000000000000000000 --- a/qpython/src/od/java/org/qpython/qpy/codeshare/pojo/CloudFile.java +++ /dev/null @@ -1,100 +0,0 @@ -package org.qpython.qpy.codeshare.pojo; - - -import com.quseit.util.FileUtils; - -import org.qpython.qpy.codeshare.CONSTANT; -import org.qpython.qpy.main.app.App; -import org.qpython.qpysdk.QPyConstants; - -import java.io.Serializable; - -public class CloudFile implements Serializable { - private String projectName; - private String path; - private String uploadTime; - private String name; - private String content; - private String key; - private boolean uploading; - - public String getPath() { - if (projectName == null) { - if (path.contains("scripts3")) { - return "/" + path.replace(CONSTANT.SLASH_REPLACE, "/").replace(CONSTANT.DOT_REPLACE, "."); - } else if (path.contains("scripts")) { - return path.replace(CONSTANT.SLASH_REPLACE, "/") + getName(); - } else { - return "/" + path.replace(CONSTANT.SLASH_REPLACE, "/").replace(CONSTANT.DOT_REPLACE, "."); - } - } else { - String projNode = path.contains("projects3") ? "projects3/" : "projects/"; - return "/" + projNode + getProjectName() + path - .replace(CONSTANT.SLASH_REPLACE, "/") - .replace(CONSTANT.DOT_REPLACE, ".") - .replace(projNode, "") - .replace(getProjectName(), ""); - } - } - - public void setPath(String path) { - this.path = path; - } - - public String getUploadTime() { - return uploadTime; - } - - public void setUploadTime(String uploadTime) { - this.uploadTime = uploadTime; - } - - public String getName() { - return name.replace(CONSTANT.DOT_REPLACE, "."); - } - - public void setName(String name) { - this.name = name; - } - - public String getContent() { - return content; - } - - public void setContent(String content) { - this.content = content; - } - - public long getContentSize() { - return content == null ? 0 : content.length(); - } - - public String getProjectName() { - return projectName == null ? null : projectName. - replace(CONSTANT.SLASH_REPLACE, "/").replace(CONSTANT.DOT_REPLACE, "."); - } - - public void setProjectName(String projectName) { - this.projectName = projectName; - } - - public boolean isUploading() { - return uploading; - } - - public void setUploading(boolean uploading) { - this.uploading = uploading; - } - - public String getKey() { - return key == null ? getName().replace(".", CONSTANT.DOT_REPLACE) : key; - } - - public void setKey(String key) { - this.key = key; - } - - public String getAbsolutePath() { - return FileUtils.getAbsolutePath(App.getContext()) + getPath(); - } -} diff --git a/qpython/src/od/java/org/qpython/qpy/main/PayActivity.java b/qpython/src/od/java/org/qpython/qpy/main/PayActivity.java deleted file mode 100644 index c1a7b8d283b4deedd988951e1a3aea2867e22fbe..0000000000000000000000000000000000000000 --- a/qpython/src/od/java/org/qpython/qpy/main/PayActivity.java +++ /dev/null @@ -1,188 +0,0 @@ -package org.qpython.qpy.main; - -import android.app.PendingIntent; -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.content.IntentSender; -import android.content.ServiceConnection; -import android.os.Bundle; -import android.os.IBinder; -import android.os.RemoteException; -import android.support.annotation.Nullable; -import android.support.v7.app.AppCompatActivity; -import android.support.v7.widget.GridLayoutManager; -import android.view.MenuItem; -import android.view.View; -import android.widget.Toast; - -import com.android.vending.billing.IInAppBillingService; -import com.quseit.util.ImageUtil; - -import org.json.JSONException; -import org.json.JSONObject; -import org.qpython.qpy.R; -import org.qpython.qpy.main.activity.PurchaseActivity; -import org.qpython.qpy.main.server.MySubscriber; -import org.qpython.qpy.main.widget.GridSpace; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import rx.Observable; -import rx.android.schedulers.AndroidSchedulers; -import rx.schedulers.Schedulers; - -/** - * Created by Hmei - * 1/30/18. - */ - -public class PayActivity extends AppCompatActivity { - public static final int BUY_REQUEST_CODE = 2333; - private IInAppBillingService mService; - private ServiceConnection mServiceConn; - private ArrayList skuList; - private MySubscriber callback; - - @Override - protected void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - } - - void initIAB(ArrayList skuList, MySubscriber callback) { - this.skuList = skuList; - this.callback = callback; - mServiceConn = new ServiceConnection() { - @Override - public void onServiceDisconnected(ComponentName name) { - mService = null; - } - - @Override - public void onServiceConnected(ComponentName name, - IBinder service) { - mService = IInAppBillingService.Stub.asInterface(service); - getPrices(skuList, callback); - } - }; - - Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND"); - serviceIntent.setPackage("com.android.vending"); - bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE); - } - - /** - * 从Google服务器获取不同国家价格表并显示 - */ - private void getPrices(ArrayList skuList, MySubscriber callback) { - if (mService == null) { - Toast.makeText(this, R.string.lose_google_server, Toast.LENGTH_SHORT).show(); - if (findViewById(R.id.pb) != null) findViewById(R.id.pb).setVisibility(View.GONE); - return; - } -// ArrayList skuList; -// if (!isCrowdFunding) { -// skuList = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.sku))); -// } else { -// skuList = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.crowdfunding))); -// int index = (int) (getIntent().getIntExtra(PERCENT, 0) / 100.00 * 4); -// String sku = skuList.get(index); -// skuList.clear(); -// skuList.add(sku); -// } - Bundle querySkus = new Bundle(); - querySkus.putStringArrayList("ITEM_ID_LIST", skuList); - try { - Observable.just(mService.getSkuDetails(3, getPackageName(), "inapp", querySkus)) - .map(bundle -> { - ArrayList responseList = bundle.getStringArrayList("DETAILS_LIST"); - if (responseList == null) { - return null; - } - String[] prices = new String[responseList.size()]; - for (int i = 0; i < responseList.size(); i++) { - JSONObject object; - try { - object = new JSONObject(responseList.get(i)); - String price = object.getString("price"); - prices[i] = price; - } catch (JSONException e) { - e.printStackTrace(); - } - } - Arrays.sort(prices, (o1, o2) -> Integer.parseInt(o1.replaceAll("[^0-9]", "")) - Integer.parseInt(o2.replaceAll("[^0-9]", ""))); - return prices; - } - ) - .subscribeOn(Schedulers.newThread()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(callback -// new MySubscriber() { -// @Override -// public void onNext(String[] o) { -// super.onNext(o); -// if (o == null) { -// return; -// } -// invalidateData(); -// GridSpace gridSpace = new GridSpace(2, (int) ImageUtil.dp2px(16), false); -// binding.list.setLayoutManager(new GridLayoutManager(PurchaseActivity.this, 2)); -// binding.list.addItemDecoration(gridSpace); -// binding.list.setAdapter(new PurchaseActivity.ListAdapter(o)); -// } -// } - ); - } catch (RemoteException e) { - e.printStackTrace(); - } - } - - private void purchase(String sku) { -// String[] skus; -// if (isCrowdFunding) { -// skus = getResources().getStringArray(R.array.crowdfunding); -// } else { -// skus = getResources().getStringArray(R.array.sku); -// } - try { - if (mService == null) { - Toast.makeText(this, R.string.lose_google_server, Toast.LENGTH_SHORT).show(); - return; - } - Bundle buyIntentBundle = mService.getBuyIntent(3, getPackageName(), - sku, "inapp", "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ"); - switch (buyIntentBundle.getInt("RESPONSE_CODE")) { - case 0: - //BILLING_RESPONSE_RESULT_OK - PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT"); - startIntentSenderForResult(pendingIntent.getIntentSender(), - BUY_REQUEST_CODE, new Intent(), 0, 0, 0); - break; - - } - } catch (RemoteException | IntentSender.SendIntentException | NullPointerException e) { - e.printStackTrace(); - } - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - if (item.getItemId() == R.id.refresh_menu) { - if (findViewById(R.id.pb) != null) findViewById(R.id.pb).setVisibility(View.VISIBLE); - getPrices(skuList, callback); - return true; - } - return super.onOptionsItemSelected(item); - } - - @Override - public void onDestroy() { - super.onDestroy(); - if (mService != null) { - unbindService(mServiceConn); - } - } - -} diff --git a/qpython/src/od/java/org/qpython/qpy/main/activity/FundingPurchaseActivity.java b/qpython/src/od/java/org/qpython/qpy/main/activity/FundingPurchaseActivity.java deleted file mode 100644 index 6e6cf10a9cd296ec4ed027a1cb1f15b97584e93d..0000000000000000000000000000000000000000 --- a/qpython/src/od/java/org/qpython/qpy/main/activity/FundingPurchaseActivity.java +++ /dev/null @@ -1,143 +0,0 @@ -package org.qpython.qpy.main.activity; - -import android.content.Context; -import android.content.Intent; -import android.databinding.DataBindingUtil; -import android.os.Bundle; -import android.support.annotation.Nullable; -import android.view.Menu; -import android.view.View; -import android.widget.Toast; - -import com.quseit.util.VeDate; - -import org.json.JSONException; -import org.json.JSONObject; -import org.qpython.qpy.R; -import org.qpython.qpy.databinding.ActivityFundingPurchaseBinding; -import org.qpython.qpy.main.app.App; -import org.qpython.qpy.main.server.MySubscriber; -import org.qpython.qpy.main.server.model.GooglePurchaseModel; -import org.qpython.qpy.utils.UpdateHelper; - -import java.util.ArrayList; -import java.util.Arrays; - -/** - * Created by Hmei - * 1/30/18. - */ - -public class FundingPurchaseActivity extends PayActivity { - private static final String ARTICLE_ID = "article_id"; - private static final String FUNDING_COUNT = "fundingCount"; - // private final String[] prices = get - private ActivityFundingPurchaseBinding binding; - private String sku; - - public static void startSupport(Context context, String articleId, int fundingPercent) { - Intent starter = new Intent(context, FundingPurchaseActivity.class); - starter.putExtra(ARTICLE_ID, articleId); - starter.putExtra(FUNDING_COUNT, fundingPercent); - context.startActivity(starter); - } - - @Override - protected void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - binding = DataBindingUtil.setContentView(this, R.layout.activity_funding_purchase); - binding.pb.setVisibility(View.VISIBLE); - initView(); - initPrice(); - initListener(); - } - - private void initView() { - setSupportActionBar(binding.lt.toolbar); - binding.lt.toolbar.setNavigationIcon(R.drawable.ic_back); - binding.lt.toolbar.setNavigationOnClickListener(v -> finish()); - setTitle(R.string.reward); - } - - private void initPrice() { - String[] skus = getResources().getStringArray(R.array.crowdfunding); - int fundingCount = getIntent().getIntExtra(FUNDING_COUNT, 0); - if (fundingCount < 100) { - sku = skus[0]; - } else if (fundingCount < 500) { - sku = skus[1]; - } else if (fundingCount < 2000) { - sku = skus[2]; - } else { - sku = skus[3]; - } - ArrayList skuList = new ArrayList<>(); - skuList.add(sku); - initIAB(skuList, new MySubscriber() { - @Override - public void onNext(String[] o) { - super.onNext(o); - if (o == null) { - return; - } - invalidateData(true); - binding.price.setText(o[0]); - } - }); - } - - private void initListener() { - binding.price.setOnClickListener(v -> payUtil.purchase(sku)); - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - getMenuInflater().inflate(R.menu.refresh_menu, menu); - return true; - } - - private void invalidateData(boolean showData) { - binding.price.setVisibility(showData ? View.VISIBLE : View.GONE); - binding.tvThanks.setVisibility(showData ? View.VISIBLE : View.GONE); - binding.noData.llRoot.setVisibility(showData ? View.GONE : View.VISIBLE); - binding.pb.setVisibility(View.GONE); - } - - @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) { - super.onActivityResult(requestCode, resultCode, data); - if (requestCode == BUY_REQUEST_CODE) { - if (resultCode == RESULT_OK) { - GooglePurchaseModel model = App.getGson().fromJson(data.getStringExtra("INAPP_PURCHASE_DATA"), GooglePurchaseModel.class); - if (model == null) { - return; - } - switch (model.getProductId()) { - default: - Toast.makeText(this, R.string.thanks_your_support, Toast.LENGTH_SHORT).show(); - break; - } - // 统计赞赏数据 - JSONObject jsonObject = new JSONObject(); - try { - jsonObject.put("type", model.getProductId()); - jsonObject.put("time", VeDate.getStringDateHourAsInt()); - int percent = getIntent().getIntExtra(FUNDING_COUNT, 0); - String[] fundingCount = getResources().getStringArray(R.array.funding_count_divider); - jsonObject.put("crowdfunding", - percent > (Integer.parseInt(fundingCount[1]) / Integer.parseInt(fundingCount[2])) ? 3 : - percent > (Integer.parseInt(fundingCount[0]) / Integer.parseInt(fundingCount[1])) ? 2 : 1);//0 非众筹/ 1: 0-100 /2: 100-500/3 500-2000 - jsonObject.put("articleId", getIntent().getStringExtra(ARTICLE_ID)); - if (App.getUser() != null) { - jsonObject.put("account", App.getUser().getEmail()); - } - } catch (JSONException e) { - e.printStackTrace(); - } - UpdateHelper.submitIAPLog(this, model.getOrderId(), App.getGson().toJson(jsonObject)); - payUtil.digestPurchase(model.getPurchaseToken()); - finish(); - } - } - } -} diff --git a/qpython/src/od/java/org/qpython/qpy/main/activity/PayActivity.java b/qpython/src/od/java/org/qpython/qpy/main/activity/PayActivity.java deleted file mode 100644 index c637254e36d2ddeafd8cd346e0d9fac2dfead1e1..0000000000000000000000000000000000000000 --- a/qpython/src/od/java/org/qpython/qpy/main/activity/PayActivity.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.qpython.qpy.main.activity; - -import android.os.Bundle; -import android.support.annotation.Nullable; -import android.support.v7.app.AppCompatActivity; -import android.view.MenuItem; -import android.view.View; - -import org.qpython.qpy.R; -import org.qpython.qpy.main.server.MySubscriber; -import org.qpython.qpy.main.service.PayUtil; - -import java.util.ArrayList; - -/** - * Created by Hmei - * 1/30/18. - */ - -public class PayActivity extends AppCompatActivity { - public static final int BUY_REQUEST_CODE = 2333; - private ArrayList skuList; - private MySubscriber callback; - protected PayUtil payUtil; - - @Override - protected void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - payUtil = new PayUtil(this); - } - - protected void initIAB(ArrayList skuList, MySubscriber callback) { - this.skuList = skuList; - this.callback = callback; - payUtil.initIAP(() -> payUtil.getPrices(skuList,callback)); - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - if (item.getItemId() == R.id.refresh_menu) { - if (findViewById(R.id.pb) != null) findViewById(R.id.pb).setVisibility(View.VISIBLE); - payUtil.getPrices(skuList, callback); - return true; - } - return super.onOptionsItemSelected(item); - } - - @Override - public void onDestroy() { - super.onDestroy(); - payUtil.unbindPayService(); - } - -} diff --git a/qpython/src/od/java/org/qpython/qpy/main/activity/PurchaseActivity.java b/qpython/src/od/java/org/qpython/qpy/main/activity/PurchaseActivity.java deleted file mode 100644 index 74335cc20a2d632a3ac6179ebc3bdd7cb45a8f10..0000000000000000000000000000000000000000 --- a/qpython/src/od/java/org/qpython/qpy/main/activity/PurchaseActivity.java +++ /dev/null @@ -1,158 +0,0 @@ -package org.qpython.qpy.main.activity; - -import android.content.Context; -import android.content.Intent; -import android.databinding.DataBindingUtil; -import android.os.Bundle; -import android.support.annotation.Nullable; -import android.support.v7.widget.GridLayoutManager; -import android.support.v7.widget.RecyclerView; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.View; -import android.view.ViewGroup; -import android.widget.Toast; - -import com.quseit.util.ImageUtil; -import com.quseit.util.VeDate; - -import org.json.JSONException; -import org.json.JSONObject; -import org.qpython.qpy.R; -import org.qpython.qpy.databinding.ActivityPurchaseBinding; -import org.qpython.qpy.databinding.ItemPriceBinding; -import org.qpython.qpy.main.adapter.MyViewHolder; -import org.qpython.qpy.main.app.App; -import org.qpython.qpy.main.server.MySubscriber; -import org.qpython.qpy.main.server.model.GooglePurchaseModel; -import org.qpython.qpy.main.widget.GridSpace; -import org.qpython.qpy.utils.UpdateHelper; - -import java.util.ArrayList; -import java.util.Arrays; - -/** - * Google purchase activity - * Created by Hmei on 2017-07-19. - */ - -public class PurchaseActivity extends PayActivity { - - private static final String ARTICLE_ID = "article_id"; - - private ActivityPurchaseBinding binding; - private ArrayList skus; - - public static void start(Context context, String articleId) { - Intent starter = new Intent(context, PurchaseActivity.class); - starter.putExtra(ARTICLE_ID, articleId); - context.startActivity(starter); - } - - - @Override - protected void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - binding = DataBindingUtil.setContentView(this, R.layout.activity_purchase); - skus = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.sku))); - - initIAB(skus, new MySubscriber() { - @Override - public void onNext(String[] o) { - super.onNext(o); - if (o == null) { - return; - } - invalidateData(); - GridSpace gridSpace = new GridSpace(2, (int) ImageUtil.dp2px(16), false); - binding.list.setLayoutManager(new GridLayoutManager(PurchaseActivity.this, 2)); - binding.list.addItemDecoration(gridSpace); - binding.list.setAdapter(new PurchaseActivity.ListAdapter(o)); - } - }); - - initView(); - } - - private void initView() { - setSupportActionBar(binding.lt.toolbar); - binding.lt.toolbar.setNavigationIcon(R.drawable.ic_back); - binding.lt.toolbar.setNavigationOnClickListener(v -> finish()); - setTitle(R.string.reward); - } - - private void invalidateData() { - binding.tvThanks.setVisibility(View.VISIBLE); - binding.list.setVisibility(View.VISIBLE); - binding.noData.llRoot.setVisibility(View.GONE); - } - - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - getMenuInflater().inflate(R.menu.refresh_menu, menu); - return true; - } - - @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) { - super.onActivityResult(requestCode, resultCode, data); - if (requestCode == BUY_REQUEST_CODE) { - if (resultCode == RESULT_OK) { - GooglePurchaseModel model = App.getGson().fromJson(data.getStringExtra("INAPP_PURCHASE_DATA"), GooglePurchaseModel.class); - if (model == null) { - return; - } - switch (model.getProductId()) { - default: - Toast.makeText(this, R.string.thanks_your_support, Toast.LENGTH_SHORT).show(); - break; - } - // 统计赞赏数据 - JSONObject jsonObject = new JSONObject(); - try { - jsonObject.put("type", model.getProductId()); - jsonObject.put("time", VeDate.getStringDateHourAsInt()); - jsonObject.put("crowdfunding", 0);//0 非众筹/ 1: 0-100 /2: 100-500/3 500-2000 - jsonObject.put("articleId", getIntent().getStringExtra(ARTICLE_ID)); - if (App.getUser() != null) { - jsonObject.put("account", App.getUser().getEmail()); - } - } catch (JSONException e) { - e.printStackTrace(); - } - UpdateHelper.submitIAPLog(this, model.getOrderId(), App.getGson().toJson(jsonObject)); - payUtil.digestPurchase(model.getPurchaseToken()); - finish(); - } - } - } - - private class ListAdapter extends RecyclerView.Adapter> { - String[] dataList; - - ListAdapter(String[] dataList) { - this.dataList = dataList; - } - - @Override - public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - ItemPriceBinding binding = DataBindingUtil.inflate(LayoutInflater.from(PurchaseActivity.this), R.layout.item_price, parent, false); - MyViewHolder holder = new MyViewHolder<>(binding.getRoot()); - holder.setBinding(binding); - return holder; - } - - @Override - public void onBindViewHolder(MyViewHolder holder, int position) { - ItemPriceBinding binding = holder.getBinding(); - binding.tvPrices.setText(dataList[position]); - binding.tvPrices.setOnClickListener(v -> payUtil.purchase(skus.get(position))); - } - - @Override - public int getItemCount() { - return dataList.length; - } - } -} diff --git a/qpython/src/od/java/org/qpython/qpy/main/activity/SignInActivity.java b/qpython/src/od/java/org/qpython/qpy/main/activity/SignInActivity.java deleted file mode 100644 index b5fc5d2c96a42034e9b9a65454092e6bd5583620..0000000000000000000000000000000000000000 --- a/qpython/src/od/java/org/qpython/qpy/main/activity/SignInActivity.java +++ /dev/null @@ -1,184 +0,0 @@ -package org.qpython.qpy.main.activity; - -import android.content.Intent; -import android.databinding.DataBindingUtil; -import android.net.Uri; -import android.os.Bundle; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.support.v7.app.AppCompatActivity; -import android.text.Html; -import android.util.Log; -import android.view.View; -import android.widget.Toast; - -import com.google.android.gms.auth.api.Auth; -import com.google.android.gms.auth.api.signin.GoogleSignInAccount; -import com.google.android.gms.auth.api.signin.GoogleSignInOptions; -import com.google.android.gms.auth.api.signin.GoogleSignInResult; -import com.google.android.gms.common.ConnectionResult; -import com.google.android.gms.common.api.GoogleApiClient; -import com.google.firebase.auth.AuthCredential; -import com.google.firebase.auth.FirebaseAuth; -import com.google.firebase.auth.FirebaseUser; -import com.google.firebase.auth.GoogleAuthProvider; - -import org.qpython.qpy.R; -import org.qpython.qpy.databinding.ActivitySignInBinding; -import org.qpython.qpy.main.app.App; -import org.qpython.qpy.main.app.CONF; -import org.qpython.qpy.main.app.User; -import org.qpython.qpy.main.server.gist.loginScreen.LoginControler; -import org.qpython.qpy.main.server.gist.loginScreen.LoginView; - -/** - * SignIn - * Created by Hmei on 2017-08-04. - */ - -public class SignInActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener ,LoginView{ - private static final int RC_SIGN_IN = 54503; - - private GoogleApiClient mGoogleApiClient; - private ActivitySignInBinding binding; - private FirebaseAuth mAuth; - - private LoginControler mLoginControler; - - { - mAuth = FirebaseAuth.getInstance(); - FirebaseUser currentUser = mAuth.getCurrentUser(); - initUserInfo(currentUser); - } - - @Override - protected void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - binding = DataBindingUtil.setContentView(this, R.layout.activity_sign_in); - binding.textView3.setText(Html.fromHtml(getString(R.string.by_signing_in_you_agree_to_out_privacy_policy_term_of_service))); - GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) - .requestIdToken(CONF.GOOGLE_ID_TOKEN) - .requestEmail() - .build(); - - mGoogleApiClient = new GoogleApiClient.Builder(this) - .enableAutoManage(this, this) - .addApi(Auth.GOOGLE_SIGN_IN_API, gso) - .addOnConnectionFailedListener(connectionResult -> showToast(getString(R.string.lost_google_hint))) - .build(); - initListener(); - - mLoginControler = new LoginControler(this); - } - - private void initListener() { - binding.textView3.setOnClickListener(v -> startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.privacy_html))))); - binding.button2.setOnClickListener(v -> signIn()); - binding.button3.setOnClickListener(v -> finish()); - } - - private void signIn() { - Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); - startActivityForResult(signInIntent, RC_SIGN_IN); - } - - @Override - public void onActivityResult(int requestCode, int resultCode, Intent data) { - super.onActivityResult(requestCode, resultCode, data); - // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...); - if (requestCode == RC_SIGN_IN) { - GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); - if (result.isSuccess()) { - GoogleSignInAccount account = result.getSignInAccount(); - firebaseAuthWithGoogle(account); - } else { - Log.e("LOGIN", result.getStatus().toString()); - try { - String msg = result.getStatus().getStatusMessage().trim(); - showToast(getString(R.string.login_error) + (msg.equals("") ? "" : ": ") + msg); - initUserInfo(null); - } catch (NullPointerException ignore) { - showToast(getString(R.string.no_google)); - } - } - } - } - - private void firebaseAuthWithGoogle(GoogleSignInAccount acct) { - showLoading(); - AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), "45:FD:60:98:01:9A:37:D9:84:03:06:36:02:F6:85:2C:A2:1F:B8:67"); - mAuth.signInWithCredential(credential) - .addOnCompleteListener(this, task -> { - if (task.isSuccessful()) { - FirebaseUser user = mAuth.getCurrentUser(); - initUserInfo(user); - } else { - showToast(getString(R.string.auth_failed)); - initUserInfo(null); - hideLoading(); - } - }); - } - - private void initUserInfo(FirebaseUser currentUser) { - if (currentUser == null) { - App.setUser(null); - return; - } - Log.d("SingInActivity", "NICK:"+currentUser.getDisplayName()+"-UN:"+currentUser.getEmail()); - User user = new User(); - user.setUserId(currentUser.getUid()); - user.setAvatarUrl(currentUser.getPhotoUrl() == null ? "" : currentUser.getPhotoUrl().toString()); - user.setEmail(currentUser.getEmail()); - user.setUserName(currentUser.getEmail()); - user.setNick(currentUser.getDisplayName()); - App.setUser(user); - if (mLoginControler!=null) { - mLoginControler.login(user); - } else { - Toast.makeText(this, R.string.signin_error, Toast.LENGTH_SHORT).show(); - } - } - - @Override - public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { - initUserInfo(null); - } - - @Override - public void showLoading() { - binding.progressBar2.setVisibility(View.VISIBLE); - } - - @Override - public void hideLoading() { - binding.progressBar2.setVisibility(View.GONE); - } - - @Override - public void showToast(String msg) { - Toast.makeText(SignInActivity.this, msg, Toast.LENGTH_SHORT) - .show(); - } - - @Override - public void loginSuccess() { - Log.d("SignInActivity", "loginSuccess"); -// setResult(RESULT_OK); -// this.finish(); - - setResult(RESULT_OK); - binding.progressBar2.setVisibility(View.GONE); - showToast("login successfully"); - finish(); - } - - @Override - protected void onDestroy() { - super.onDestroy(); - if (mLoginControler!=null) { - - mLoginControler.onDestroy(); - } - } -} \ No newline at end of file diff --git a/qpython/src/od/java/org/qpython/qpy/main/activity/UserActivity.java b/qpython/src/od/java/org/qpython/qpy/main/activity/UserActivity.java deleted file mode 100644 index 09607c79676183bb536aa4642a0df958dcb5357f..0000000000000000000000000000000000000000 --- a/qpython/src/od/java/org/qpython/qpy/main/activity/UserActivity.java +++ /dev/null @@ -1,77 +0,0 @@ -package org.qpython.qpy.main.activity; - -import android.content.Context; -import android.content.Intent; -import android.databinding.DataBindingUtil; -import android.os.Bundle; -import android.support.annotation.Nullable; -import android.support.v7.app.AlertDialog; -import android.support.v7.app.AppCompatActivity; -import android.view.View; - -import com.google.firebase.auth.FirebaseAuth; -import com.quseit.util.FileUtils; -import com.quseit.util.ImageDownLoader; - -import org.qpython.qpy.R; -import org.qpython.qpy.codeshare.CONSTANT; -import org.qpython.qpy.codeshare.ShareCodeUtil; -import org.qpython.qpy.databinding.ActivityUserBinding; -import org.qpython.qpy.main.app.App; -import org.qpython.qpy.main.app.CONF; - -import java.io.File; - -public class UserActivity extends AppCompatActivity { - ActivityUserBinding binding; - - public static void start(Context context) { - Intent starter = new Intent(context, UserActivity.class); - context.startActivity(starter); - } - - @Override - protected void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - binding = DataBindingUtil.setContentView(this, R.layout.activity_user); - setSupportActionBar(binding.toolbar); - setTitle(getString(R.string.me)); - binding.toolbar.setNavigationIcon(R.drawable.ic_back); - binding.toolbar.setNavigationOnClickListener(v -> finish()); - - ImageDownLoader.setImageFromUrl(this, binding.avatar, App.getUser().getAvatarUrl()); - binding.name.setText(App.getUser().getNick()); - //binding.email.setText(App.getUser().getEmail()); - - binding.usage.setText(R.string.my_space_empty); - binding.logout.setOnClickListener(v -> logout()); - binding.myShareLayout.setOnClickListener(v -> MyGistActivity.startMyShare(UserActivity.this)); - setUsage(); - } - - private void setUsage() { - ShareCodeUtil.getInstance().initUsage(integer -> - binding.usage.setText(getString(R.string.my_space, integer == null ? 0 : integer))); - } - - private void logout() { - new AlertDialog.Builder(this, R.style.MyDialog) - .setTitle(R.string.lout) - .setPositiveButton(R.string.yes, (dialog, which) -> { - FirebaseAuth.getInstance().signOut(); - App.setUser(null); - getPreferences(MODE_PRIVATE).edit().putBoolean(CONSTANT.IS_UPLOAD_INIT, false) - .putString(CONSTANT.CLOUDED_MAP, "") - .apply(); - File cloud_cache = new File(FileUtils.getCloudMapCachePath(getApplicationContext())); - if (cloud_cache.exists()) { - cloud_cache.delete(); - } - finish(); - }) - .setNegativeButton(R.string.no, null) - .create() - .show(); - - } -} \ No newline at end of file diff --git a/qpython/src/od/java/org/qpython/qpy/main/app/AppInit.java b/qpython/src/od/java/org/qpython/qpy/main/app/AppInit.java deleted file mode 100644 index 76cc52abe199d52c6a83d84e3db6545c8f3cf857..0000000000000000000000000000000000000000 --- a/qpython/src/od/java/org/qpython/qpy/main/app/AppInit.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.qpython.qpy.main.app; - -import android.content.Context; -import android.util.Log; - -import com.google.firebase.FirebaseApp; -import com.google.firebase.iid.FirebaseInstanceId; -import com.quseit.config.BASE_CONF; - -import org.qpython.qpy.codeshare.ShareCodeUtil; - -/** - * 文 件 名: AppInit - * 创 建 人: ZhangRonghua - * 创建日期: 2018/3/8 15:13 - * 修改时间: - * 修改备注: - */ - -public class AppInit { - - public static void init(Context context){ - - FirebaseApp.initializeApp(context); - if (BASE_CONF.DEBUG) { - try { - FirebaseInstanceId xx = FirebaseInstanceId.getInstance(); - if (xx != null) { - Log.e("Firebase", xx.getToken()); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - ShareCodeUtil.getInstance(); - } -} diff --git a/qpython/src/od/java/org/qpython/qpy/main/fragment/ExplorerFragment.java b/qpython/src/od/java/org/qpython/qpy/main/fragment/ExplorerFragment.java deleted file mode 100644 index 5713b1ec869397952eda95e607e9ee7687e8adb5..0000000000000000000000000000000000000000 --- a/qpython/src/od/java/org/qpython/qpy/main/fragment/ExplorerFragment.java +++ /dev/null @@ -1,505 +0,0 @@ -package org.qpython.qpy.main.fragment; - -import android.content.Intent; -import android.databinding.DataBindingUtil; -import android.graphics.Color; -import android.net.Uri; -import android.os.Bundle; -import android.os.Environment; -import android.support.annotation.Nullable; -import android.support.v4.app.Fragment; -import android.support.v7.app.AlertDialog; -import android.support.v7.widget.LinearLayoutManager; -import android.text.TextUtils; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.Toast; - -import com.google.firebase.database.DatabaseReference; -import com.quseit.util.FileHelper; -import com.quseit.util.ImageUtil; -import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator; -import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem; - -import org.qpython.qpy.R; -import org.qpython.qpy.codeshare.ShareCodeUtil; -import org.qpython.qpy.codeshare.pojo.CloudFile; -import org.qpython.qpy.databinding.FragmentExplorerBinding; -import org.qpython.qpy.main.activity.NotebookActivity; -import org.qpython.qpy.main.activity.SettingActivity; -import org.qpython.qpy.main.activity.SignInActivity; -import org.qpython.qpy.main.app.App; -import org.qpython.qpy.main.app.CONF; -import org.qpython.qpy.texteditor.EditorActivity; -import org.qpython.qpy.texteditor.TedLocalActivity; -import org.qpython.qpy.texteditor.common.CommonEnums; -import org.qpython.qpy.texteditor.common.RecentFiles; -import org.qpython.qpy.texteditor.ui.adapter.FolderAdapter; -import org.qpython.qpy.texteditor.ui.adapter.bean.FolderBean; -import org.qpython.qpy.texteditor.ui.view.EnterDialog; -import org.qpython.qpy.texteditor.widget.crouton.Crouton; -import org.qpython.qpy.texteditor.widget.crouton.Style; -import org.qpython.qpy.utils.FileUtils; -import org.qpython.qpy.utils.NotebookUtil; - -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static com.quseit.util.FolderUtils.sortTypeByName; - -public class ExplorerFragment extends Fragment { - private static final int REQUEST_SAVE_AS = 107; - private static final int REQUEST_HOME_PAGE = 109; - private static final int REQUEST_RECENT = 111; - private static final int LOGIN_REQUEST = 2741; - - private static final String TYPE = "type"; - - private int WIDTH = (int) ImageUtil.dp2px(60); - - private FragmentExplorerBinding binding; - private List folderList; - private FolderAdapter adapter; - private Map cloudedMap = new HashMap<>(); - - private boolean openable = true; // 是否可打开文件 - private boolean uploadable; - - private int type; - private String curPath; - - public static ExplorerFragment newInstance(int type) { - ExplorerFragment myFragment = new ExplorerFragment(); - - Bundle args = new Bundle(); - args.putInt(TYPE, type); - myFragment.setArguments(args); - - return myFragment; - } - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { - return inflater.inflate(R.layout.fragment_explorer, null); - } - - @Override - public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - binding = DataBindingUtil.bind(view); - type = getArguments().getInt(TYPE); - initView(); - initListener(); - initCloud(); - switch (type) { - case REQUEST_RECENT: - binding.rlPath.setVisibility(View.GONE); - uploadable = false; - break; - case REQUEST_SAVE_AS: - binding.ivNewFolder.setVisibility(View.VISIBLE); - uploadable = false; - break; - case REQUEST_HOME_PAGE: - binding.ivNewFolder.setVisibility(View.VISIBLE); - uploadable = true; - break; - } - } - - private void initView() { - SwipeMenuCreator swipeMenuCreator = (leftMenu, rightMenu, viewType) -> { -// SwipeMenuItem uploadItem = new SwipeMenuItem(getContext()) -// .setBackgroundColor(Color.parseColor("#FF4798F3")) -// .setImage(R.drawable.ic_cloud_upload) -// .setHeight(ViewGroup.LayoutParams.MATCH_PARENT) -// .setWidth(WIDTH); - - SwipeMenuItem renameItem = new SwipeMenuItem(getContext()) - .setBackgroundColor(Color.parseColor("#FF4BAC07")) - .setImage(R.drawable.ic_file_rename) - .setHeight(ViewGroup.LayoutParams.MATCH_PARENT) - .setWidth(WIDTH); - - SwipeMenuItem deleteItem = new SwipeMenuItem(getContext()) - .setBackgroundColor(Color.parseColor("#FFD14136")) - .setImage(R.drawable.ic_editor_filetree_close) - .setHeight(ViewGroup.LayoutParams.MATCH_PARENT) - .setWidth(WIDTH); - - switch (type) { - case REQUEST_RECENT: - rightMenu.addMenuItem(deleteItem); - break; - case REQUEST_SAVE_AS: - rightMenu.addMenuItem(deleteItem); - break; - case REQUEST_HOME_PAGE: - //rightMenu.addMenuItem(uploadItem); - rightMenu.addMenuItem(renameItem); - rightMenu.addMenuItem(deleteItem); - break; - } - }; - - folderList = new ArrayList<>(); - adapter = new FolderAdapter(folderList, getArguments().getInt(TYPE) == REQUEST_RECENT); - adapter.setCloudMap(cloudedMap); - binding.swipeList.setLayoutManager(new LinearLayoutManager(getContext())); - binding.swipeList.setSwipeMenuCreator(swipeMenuCreator); - openDir(FileUtils.getAbsolutePath(App.getContext())); - } - - private void initListener() { - binding.ivNewFolder.setOnClickListener(v -> doNewDir()); - binding.prevFolder.setOnClickListener(v -> { - try { - //采用Environment来获取sdcard路径 - String parentPath = new File(curPath).getParent(); - - if (parentPath.length() >= com.quseit.util.FileUtils.getQyPath(App.getContext()).length()) { - openDir(parentPath); - } - } catch (Exception e) { - e.printStackTrace(); - } - }); - binding.swipeList.setSwipeMenuItemClickListener(menuBridge -> { - binding.swipeList.smoothCloseMenu(); - switch (menuBridge.getPosition()) { - case 0: -// if (uploadable) { -// uploadFile(menuBridge.getAdapterPosition()); -// } else { -// deleteFile(menuBridge.getAdapterPosition()); -// } -// break; -// case 1: - renameFile(menuBridge.getAdapterPosition()); - break; - case 1: - deleteFile(menuBridge.getAdapterPosition()); - break; - default:break; - } - }); - adapter.setClickListener(new FolderAdapter.Click() { - @Override - public void onItemClick(int position) { - FolderBean item = folderList.get(position); - if (item.getType().equals(CommonEnums.FileType.FILE)) { - if (!openable) { - Toast.makeText(getActivity(), R.string.cant_open, Toast.LENGTH_SHORT).show(); - return; - } - //判断文件类型 - int lastDot = item.getName().lastIndexOf("."); - if (lastDot != -1) { - String ext = item.getName().substring(lastDot + 1); - openFile(item.getFile(), ext); - } - } else { - openDir(item.getPath()); - } - } - - @Override - public void onLongClick(int position) { - binding.swipeList.smoothOpenRightMenu(position); - } - }); - - binding.swipeList.setAdapter(adapter); - } - - private void gotoSetting() { - SettingActivity.startActivity(getActivity()); - } - - private void openFile(File file, String ext) { - List textExts = Arrays.asList(getContext().getResources().getStringArray(R.array.text_ext)); - if (textExts.contains(ext)) { - EditorActivity.start(getContext(), Uri.fromFile(file)); - } else if (ext.equals("ipynb")) { - boolean notebookenable = NotebookUtil.isNotebookEnable(getActivity()); - if (notebookenable) { - NotebookActivity.start(getActivity(), file.getAbsolutePath(), false); - } else { - - new AlertDialog.Builder(getActivity(), R.style.MyDialog) - .setTitle(R.string.dialog_alert) - .setMessage(getString(R.string.ennable_notebook_first)) - .setNegativeButton(R.string.cancel, (dialog1, which) -> dialog1.dismiss()) - .setPositiveButton(R.string.ok, (dialog1, which) -> gotoSetting()) - .create() - .show(); - - //Toast.makeText(getActivity(), R.string.ennable_notebook_first, Toast.LENGTH_SHORT).show(); - } - } else { - FileUtils.openFile(getContext(), file); - } - } - - private void uploadFile(int adapterPosition) { - File file = folderList.get(adapterPosition).getFile(); - - // only support type in - String ext = ""; - if (file.getName().lastIndexOf(".") > 0) { - ext = file.getName().substring(file.getName().lastIndexOf(".") + 1); - } - boolean isSupport = false; - if (!file.isDirectory()) { - for (String s : getResources().getStringArray(R.array.support_file_ext)) { - if (s.equals(ext)) { - isSupport = true; - break; - } - } - } else { - isSupport = true; - } - - if (!isSupport) { - Toast.makeText(getContext(), R.string.not_support_type_hint, Toast.LENGTH_SHORT).show(); - return; - } - - // only available for already login user - if (App.getUser() == null) { - new AlertDialog.Builder(getActivity(), R.style.MyDialog) - .setTitle(R.string.need_login) - .setMessage(R.string.upload_login_hint) - .setNegativeButton(R.string.no, null) - .setPositiveButton(getString(R.string.login_now), (dialog, which) -> - startActivityForResult(new Intent(getActivity(), SignInActivity.class), LOGIN_REQUEST) - ) - .create() - .show(); - return; - } - - // upload - folderList.get(adapterPosition).setUploading(true); - adapter.notifyItemChanged(adapterPosition); - int[] size = {1}; - DatabaseReference.CompletionListener listener = ((databaseError, databaseReference) -> { - if (databaseError == null) { -// updateClouded(folderList.get(adapterPosition).getFile()); -// adapter.setUploadFile(adapterPosition); -// ((TedLocalActivity) getActivity()).setNewUpload(); -// Toast.makeText(getActivity(), R.string.upload_suc, Toast.LENGTH_SHORT).show(); -// ShareCodeUtil.getInstance().changeUsage(size[0]); - } else { - Toast.makeText(getActivity(), databaseError.getMessage(), Toast.LENGTH_SHORT).show(); - } - folderList.get(adapterPosition).setUploading(false); - adapter.notifyDataSetChanged(); - }); - if (folderList.get(adapterPosition).getFile().isDirectory()) { - // 如果上传整个projects目录,则将该目录下项目分开上传 - if (folderList.get(adapterPosition).getName().contains("projects")) { - File[] files = folderList.get(adapterPosition).getFile().listFiles(); - for (int i = 0; i < files.length; i++) { - if (!ShareCodeUtil.getInstance().uploadFolder(files[i].getPath(), i == 0 ? null : listener, size)) { - folderList.get(adapterPosition).setUploading(false); - adapter.notifyDataSetChanged(); - } - } - } else { - if (!ShareCodeUtil.getInstance().uploadFolder(folderList.get(adapterPosition).getPath(), listener, size)) { - folderList.get(adapterPosition).setUploading(false); - adapter.notifyDataSetChanged(); - } - } - } else { - if (!ShareCodeUtil.getInstance().uploadFile(folderList.get(adapterPosition).getPath(), listener)) { - folderList.get(adapterPosition).setUploading(false); - adapter.notifyDataSetChanged(); - } - } - } - - private void renameFile(int adapterPosition) { - new EnterDialog(getContext()) - .setTitle(getString(R.string.rename)) - .setConfirmListener(name -> { - File oldFile = folderList.get(adapterPosition).getFile(); - File newFile = new File(oldFile.getParent(), name); - boolean renameSuc = oldFile.renameTo(newFile); - if (renameSuc) { - folderList.set(adapterPosition, new FolderBean(newFile)); - adapter.notifyItemChanged(adapterPosition); - return true; - } else { - Toast.makeText(getActivity(), R.string.rename_fail, Toast.LENGTH_SHORT).show(); - return false; - } - }) - .setText(folderList.get(adapterPosition).getName()) - .show(); - } - - private void deleteFile(int adapterPosition) { - switch (type) { - case REQUEST_RECENT: - RecentFiles.removePath(folderList.get(adapterPosition).getPath()); - folderList.remove(adapterPosition); - adapter.notifyDataSetChanged(); - break; - case REQUEST_HOME_PAGE: - case REQUEST_SAVE_AS: - AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.MyDialog); - builder.setTitle(R.string.warning) - .setMessage(R.string.delete_file_hint) - .setNegativeButton(R.string.no, null) - .setPositiveButton(R.string.yes, (dialog, which) -> { - String dir = folderList.get(adapterPosition).getFile().getParent(); - FileHelper.clearDir(folderList.get(adapterPosition).getFile().getAbsolutePath(), 0, true); - openDir(dir); - -// folderList.remove(adapterPosition); -// adapter.notifyItemRemoved(adapterPosition); - }) - .show(); - break; - } - } - - private void openDir(String dirPath) { - if (type == REQUEST_RECENT) { - folderList.clear(); - for (String path : RecentFiles.getRecentFiles()) { - folderList.add(new FolderBean(new File(path))); - } - - if (folderList.size() == 0) { - binding.emptyHint.setVisibility(View.VISIBLE); - } else { - binding.emptyHint.setVisibility(View.GONE); - adapter.notifyDataSetChanged(); - } - } else { - binding.tvPath.setText(dirPath); - curPath = dirPath; - File dir = new File(dirPath); - if (dir.exists()) { - File[] files = dir.listFiles(); - if (files != null) { - Arrays.sort(files, sortTypeByName); - folderList.clear(); - adapter.notifyDataSetChanged(); - for (File file : files) { - if (!dir.getName().equals(CONF.BASE_PATH)) { - if (!file.getName().startsWith(".")) { - folderList.add(new FolderBean(file)); - } - - } else { - folderList.add(new FolderBean(file)); - - } - - } - adapter.notifyDataSetChanged(); - } - } else { - Toast.makeText(getContext(), R.string.file_not_exists, Toast.LENGTH_SHORT).show(); - } - } - } - - private void doNewDir() { - new EnterDialog(getContext()) - .setTitle(getString(R.string.new_folder)) - .setHint(getString(R.string.folder_name)) - .setConfirmListener(name -> { - File dirN = new File(curPath, name.equals("") ? getString(R.string.untitled_folder) : name); - if (dirN.exists()) { - Crouton.makeText(getActivity(), getString(R.string.toast_folder_exist), Style.ALERT).show(); - return false; - } else { - if (dirN.mkdirs()) { - openDir(curPath + "/" + name); - } else { - Toast.makeText(getContext(), R.string.mkdir_fail, Toast.LENGTH_SHORT).show(); - } - return true; - } - }) - .show(); - } - - public void backToPrev() { - Log.d("ExplorerFragment", "backToPrev:" + curPath); - String qpyDir = com.quseit.util.FileUtils.getQyPath(App.getContext()) + "/qpython"; - if (curPath == null || qpyDir.equals(curPath) || com.quseit.util.FileUtils.getQyPath(App.getContext()).equals(curPath)) { - getActivity().finish(); - } else { - String parentPath = new File(curPath).getParent(); - if (!TextUtils.isEmpty(parentPath)) openDir(parentPath); - } - } - - private void updateClouded(File file) { - if (file.getParent().contains("projects")) { - String parent = file.getParent() + "/"; - String subPath = file.getPath().substring(file.getPath().indexOf(parent) + parent.length()); - String projName = subPath.contains("/") ? subPath.substring(0, subPath.indexOf("/")) : "/" + subPath; - cloudedMap.put(FileUtils.getAbsolutePath(App.getContext()) + projName, true); - } - if (file.isDirectory()) { - for (File file1 : FileHelper.filterExt(file, getResources().getStringArray(R.array.support_file_ext))) { - cloudedMap.put(file1.getPath(), true); - } - } else { - cloudedMap.put(file.getPath(), true); - } - } - - public String getCurPath() { - return curPath; - } - - private void initCloud() { - if (App.getUser() == null) { - return; - } - ShareCodeUtil.getInstance().getUploadedScripts(false, getActivity(), cloudFiles -> { - if (cloudFiles == null || cloudFiles.size() == 0) { - return; - } - for (CloudFile cloudFile : cloudFiles) { - if (cloudFile.getPath().contains("/projects")) { - String projNode = cloudFile.getPath().contains("/projects3/") ? "/projects3/" : "/projects/"; - cloudedMap.put(FileUtils.getAbsolutePath(App.getContext()) + projNode + cloudFile.getProjectName(), true); - } - cloudedMap.put(FileUtils.getAbsolutePath(App.getContext()) + cloudFile.getPath(), true); - } - adapter.setCloudMap(cloudedMap); - adapter.notifyDataSetChanged(); - }); - } - - public void deleteCloudedMap(String absolutePath) { - if (cloudedMap.containsKey(absolutePath)) { - cloudedMap.remove(absolutePath); - adapter.notifyDataSetChanged(); - } - } - - public void updateCloudedFiles(Map map) { - if (map != null) { - cloudedMap.putAll(map); - } - adapter.notifyDataSetChanged(); - } -} diff --git a/qpython/src/od/java/org/qpython/qpy/main/fragment/MyProjectFragment.java b/qpython/src/od/java/org/qpython/qpy/main/fragment/MyProjectFragment.java deleted file mode 100644 index 5d250ec0b6d7f6e9c67e71193d90f8d38f297731..0000000000000000000000000000000000000000 --- a/qpython/src/od/java/org/qpython/qpy/main/fragment/MyProjectFragment.java +++ /dev/null @@ -1,259 +0,0 @@ -package org.qpython.qpy.main.fragment; - -import android.annotation.SuppressLint; -import android.content.Context; -import android.databinding.DataBindingUtil; -import android.graphics.Color; -import android.os.Bundle; -import android.support.annotation.Nullable; -import android.support.v4.app.Fragment; -import android.support.v7.app.AlertDialog; -import android.support.v7.widget.LinearLayoutManager; -import android.text.Html; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.Toast; - -import com.quseit.util.DateTimeHelper; -import com.quseit.util.ImageUtil; -import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator; -import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem; - -import org.qpython.qpy.R; -import org.qpython.qpy.codeshare.CONSTANT; -import org.qpython.qpy.codeshare.ShareCodeUtil; -import org.qpython.qpy.codeshare.pojo.CloudFile; -import org.qpython.qpy.databinding.FragmentRefreshRvBinding; -import org.qpython.qpy.main.adapter.CloudScriptAdapter; -import org.qpython.qpy.main.app.App; -import org.qpython.qpy.texteditor.TedLocalActivity; -import org.qpython.qpy.utils.FileUtils; -import org.qpython.qpysdk.QPyConstants; - -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import rx.Observable; -import rx.android.schedulers.AndroidSchedulers; - -public class MyProjectFragment extends Fragment { - private int WIDTH = (int) ImageUtil.dp2px(60); - private FragmentRefreshRvBinding binding; - private CloudScriptAdapter adapter; - private List scriptList = new ArrayList<>(); - private TedLocalActivity activity; - - public boolean isLoading; - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { - binding = DataBindingUtil.bind(LayoutInflater.from(getContext()).inflate(R.layout.fragment_refresh_rv, null)); - return binding.getRoot(); - } - - @Override - public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - scriptList = new ArrayList<>(); - adapter = new CloudScriptAdapter(scriptList); - ShareCodeUtil.getInstance().clearAll(); - initView(); - initListener(); - retry(true); - } - - @Override - public void onAttach(Context context) { - super.onAttach(context); - activity = (TedLocalActivity) context; - } - - @Override - public void onResume() { - super.onResume(); - if (adapter != null) { - adapter.notifyDataSetChanged(); - } - } - - @Override - public void onStop() { - super.onStop(); -// activity.locatedCloud(scriptList); - } - - public void retry(boolean forceRefresh) { - if (scriptList != null && adapter != null) { - scriptList.clear(); - adapter.notifyDataSetChanged(); - } - startProgressBar(); - isLoading = true; - ShareCodeUtil.getInstance().getUploadedScripts(forceRefresh, getActivity(), cloudFiles -> { - isLoading = false; - if (cloudFiles == null || cloudFiles.size() == 0) { - showEmpty(); - return; - } -// ((TedLocalActivity) getActivity()).updateCloudFiles(cloudFiles); - scriptList.clear(); - scriptList.addAll(cloudFiles); - adapter.notifyDataSetChanged(); - binding.progressBar.setVisibility(View.GONE); - binding.netError.setVisibility(View.GONE); - }); - } - - public void notifyDataSetChange() { - if (adapter != null) adapter.notifyDataSetChanged(); - } - - private void startProgressBar() { - binding.progressBar.setVisibility(View.VISIBLE); - binding.netError.setVisibility(View.GONE); - Observable.just(null) - .delay(5, TimeUnit.SECONDS) - .observeOn(AndroidSchedulers.mainThread()) - .doOnNext(o -> showNetErrorText()) - .subscribe(); - } - - private void showEmpty() { - if (binding.progressBar.getVisibility() == View.VISIBLE) { - binding.progressBar.setVisibility(View.GONE); - binding.netError.setText(R.string.cloud_empty_hint); - binding.netError.setVisibility(View.VISIBLE); - } - } - - private void showNetErrorText() { - if (binding.progressBar.getVisibility() == View.VISIBLE) { - binding.progressBar.setVisibility(View.GONE); - binding.netError.setText(R.string.net_lagging); - binding.netError.setVisibility(View.VISIBLE); - } - } - - private void initView() { - SwipeMenuCreator swipeMenuCreator = (leftMenu, rightMenu, viewType) -> { - SwipeMenuItem deleteItem = new SwipeMenuItem(getContext()) - .setBackgroundColor(Color.parseColor("#FFD14136")) - .setImage(R.drawable.ic_editor_filetree_close) - .setHeight(ViewGroup.LayoutParams.MATCH_PARENT) - .setWidth(WIDTH); - - SwipeMenuItem downloadItem = new SwipeMenuItem(getContext()) - .setBackgroundColor(Color.parseColor("#FF4798F3")) - .setImage(R.drawable.ic_cloud_download) - .setHeight(ViewGroup.LayoutParams.MATCH_PARENT) - .setWidth(WIDTH); - rightMenu.addMenuItem(downloadItem); - rightMenu.addMenuItem(deleteItem); - }; - binding.swipeList.setLayoutManager(new LinearLayoutManager(getContext())); - binding.swipeList.setSwipeMenuCreator(swipeMenuCreator); - } - - @SuppressLint("StringFormatMatches") - private void initListener() { - binding.netError.setOnClickListener(v -> retry(true)); - binding.swipeList.setSwipeMenuItemClickListener(menuBridge -> { - menuBridge.closeMenu(); - switch (menuBridge.getPosition()) { - default:break; - case 0: - // download - CloudFile cloudFile = scriptList.get(menuBridge.getAdapterPosition()); - cloudFile.setUploading(true); - adapter.notifyItemChanged(menuBridge.getAdapterPosition()); - String path; - path = FileUtils.getAbsolutePath(App.getContext()) + cloudFile.getPath(); - File file = new File(path); - if (file.exists()) { - new AlertDialog.Builder(getContext(), R.style.MyDialog) - .setTitle(R.string.override_hint) - .setMessage(Html.fromHtml(getString(R.string.conflict_hint, - cloudFile.getUploadTime(), - DateTimeHelper.AGO_FULL_DATE_FORMATTER.format(new Date(file.lastModified()))))) - .setNegativeButton(R.string.no, (dialog, which) ->{ - cloudFile.setUploading(false); - adapter.notifyItemChanged(menuBridge.getAdapterPosition()); - }) - .setPositiveButton(R.string.yes, - (dialog, which) -> - getRemoteContentNWrite(cloudFile, path, menuBridge.getAdapterPosition())) - .create() - .show(); - } else { - getRemoteContentNWrite(cloudFile, path, menuBridge.getAdapterPosition()); - } - break; - case 1: - // delete - scriptList.get(menuBridge.getAdapterPosition()).setUploading(true); - adapter.notifyItemChanged(menuBridge.getAdapterPosition()); - ShareCodeUtil.getInstance().deleteUploadScript(scriptList.get(menuBridge.getAdapterPosition()), (databaseError, databaseReference) -> { -// if (databaseError == null && getContext() != null) { -// Toast.makeText(getContext(), R.string.delete_remote_suc, Toast.LENGTH_SHORT).show(); -// adapter.notifyItemRemoved(menuBridge.getAdapterPosition()); -// ((TedLocalActivity) getActivity()).deleteCloudFile(scriptList.get(menuBridge.getAdapterPosition()).getAbsolutePath()); -// scriptList.remove(menuBridge.getAdapterPosition()); -// if (scriptList.size() == 0) { -// binding.netError.setText(R.string.cloud_empty_hint); -// binding.netError.setVisibility(View.VISIBLE); -// } else { -// binding.netError.setVisibility(View.INVISIBLE); -// } -// } else { -// Toast.makeText(getContext(), databaseError.getMessage(), Toast.LENGTH_SHORT).show(); -// } - }); - break; - } - }); - adapter.setCallback((position) -> binding.swipeList.smoothOpenRightMenu(position)); - binding.swipeList.setAdapter(adapter); - } - - private void getRemoteContentNWrite(CloudFile cloudFile, String path, int position) { - String key = cloudFile.getKey(); - if (cloudFile.getProjectName() != null && !cloudFile.getKey().contains("projects3")) { - key = key.replace(cloudFile.getProjectName() + CONSTANT.SLASH_REPLACE, cloudFile.getProjectName() + "/" + CONSTANT.SLASH_REPLACE); - } - ShareCodeUtil.getInstance().getFileContent(key, content -> { - writeFile(path, content, position); - scriptList.get(position).setUploading(false); - adapter.notifyItemChanged(position); - }); - } - - private void writeFile(String path, String content, int adapterPosition) { - try { - FileWriter writer = new FileWriter(new File(path), false); - writer.write(content); - writer.close(); - Toast.makeText(getContext(), R.string.file_downloaded, Toast.LENGTH_SHORT).show(); - adapter.notifyItemChanged(adapterPosition); - } catch (IOException e) { - e.printStackTrace(); - Toast.makeText(getContext(), R.string.override_fail_hint, Toast.LENGTH_SHORT).show(); - } - } - - public void needRefresh(boolean isNewUpload) { - if (binding == null) { - // not init yet - return; - } - if (isNewUpload) { - retry(true); - } - } -} diff --git a/qpython/src/od/java/org/qpython/qpy/main/receiver/LeancloudReceiver.java b/qpython/src/od/java/org/qpython/qpy/main/receiver/LeancloudReceiver.java deleted file mode 100644 index 6f12375e6fe7c0f7f6bf2862210cd621c0b7fc24..0000000000000000000000000000000000000000 --- a/qpython/src/od/java/org/qpython/qpy/main/receiver/LeancloudReceiver.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.qpython.qpy.main.receiver; - -import android.annotation.SuppressLint; -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; - -/** - * 处理leancloud的消息推送 - */ -public class LeancloudReceiver extends BroadcastReceiver { - - @SuppressLint("UnsafeProtectedBroadcastReceiver") - @Override - public void onReceive(Context context, Intent intent) { - - } -} \ No newline at end of file diff --git a/qpython/src/od/java/org/qpython/qpy/main/service/MyFirebaseInstanceIDService.java b/qpython/src/od/java/org/qpython/qpy/main/service/MyFirebaseInstanceIDService.java deleted file mode 100644 index 362c23361708ee947b02c2a578363eb3ab2c3050..0000000000000000000000000000000000000000 --- a/qpython/src/od/java/org/qpython/qpy/main/service/MyFirebaseInstanceIDService.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.qpython.qpy.main.service; - -import com.google.firebase.iid.FirebaseInstanceId; -import com.google.firebase.iid.FirebaseInstanceIdService; - -/** - * Created by Hmei on 2017-06-29. - */ - -public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService { - @Override - public void onTokenRefresh() { - String refreshedToken = FirebaseInstanceId.getInstance().getToken(); - } -} diff --git a/qpython/src/od/java/org/qpython/qpy/main/service/MyFirebaseMessagingService.java b/qpython/src/od/java/org/qpython/qpy/main/service/MyFirebaseMessagingService.java deleted file mode 100644 index 9f333943b146bd7edb85605a0155acbdd3a105c7..0000000000000000000000000000000000000000 --- a/qpython/src/od/java/org/qpython/qpy/main/service/MyFirebaseMessagingService.java +++ /dev/null @@ -1,88 +0,0 @@ -package org.qpython.qpy.main.service; - -import android.app.Notification; -import android.app.NotificationManager; -import android.app.PendingIntent; -import android.content.Intent; -import android.content.SharedPreferences; -import android.net.Uri; -import android.os.Bundle; -import android.preference.PreferenceManager; - -import com.google.firebase.messaging.FirebaseMessagingService; -import com.google.firebase.messaging.RemoteMessage; - -import org.json.JSONException; -import org.json.JSONObject; -import org.qpython.qpy.R; -import org.qpython.qpy.main.activity.QWebViewActivity; -import org.qpython.qpy.main.app.App; -import org.qpython.qpy.main.app.CONF; -import org.qpython.qpy.main.receiver.NotificationBean; - -import java.util.Map; - - -public class MyFirebaseMessagingService extends FirebaseMessagingService { - private static final int LOG_NOTIFICATION_ID = (int) System.currentTimeMillis(); - - private boolean handled = false; - - @Override - public void onMessageReceived(RemoteMessage remoteMessage) { - super.onMessageReceived(remoteMessage); - Map data = remoteMessage.getData(); - String json = App.getGson().toJson(data); - NotificationBean bean = App.getGson().fromJson(json, NotificationBean.class); - if (!bean.isForce()&&!PreferenceManager.getDefaultSharedPreferences(this).getBoolean(getString(R.string.key_hide_push), true)) { - return; - } - Intent intent; - if (bean.getType().equals("ext")) { - intent = new Intent(Intent.ACTION_VIEW, Uri.parse(bean.getLink())); - } else { - intent = new Intent(App.getContext(), QWebViewActivity.class); - intent.putExtra(QWebViewActivity.TITLE, bean.getTitle()); - intent.putExtra("url", bean.getLink()); - } - - PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT); - - Notification.Builder builder = new Notification.Builder(this) - .setSmallIcon(R.drawable.img_home_logo) - .setContentTitle(getString(R.string.app_name)) - .setContentText(bean.getMsg()) - .setContentIntent(pendingIntent) - .setAutoCancel(true); - - Notification notification; - if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) { - notification = builder.build(); - } else { - notification = builder.getNotification(); - } - NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); - mNotifyMgr.notify(LOG_NOTIFICATION_ID, notification); - handled = true; - } - - /* @Override - public void handleIntent(Intent intent) { - super.handleIntent(intent); - if (handled) { - return; - } - Bundle bundle = intent.getExtras(); - JSONObject extras = new JSONObject(); - try { - for (String s : bundle.keySet()) { - extras.put(s, bundle.get(s)); - } - } catch (JSONException e) { - e.printStackTrace(); - } - SharedPreferences.Editor editor = getSharedPreferences(CONF.NOTIFICATION_SP_NAME, MODE_PRIVATE).edit(); - editor.putString(CONF.NOTIFICATION_SP_OBJ, extras.toString()); - editor.apply(); - }*/ -} \ No newline at end of file diff --git a/qpython/src/od/java/org/qpython/qpy/main/service/PayUtil.java b/qpython/src/od/java/org/qpython/qpy/main/service/PayUtil.java deleted file mode 100644 index 8b88e8cc878444a422e6d441ffaf1d1940f60ebc..0000000000000000000000000000000000000000 --- a/qpython/src/od/java/org/qpython/qpy/main/service/PayUtil.java +++ /dev/null @@ -1,150 +0,0 @@ -package org.qpython.qpy.main.service; - -import android.app.Activity; -import android.app.PendingIntent; -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.content.IntentSender; -import android.content.ServiceConnection; -import android.os.Bundle; -import android.os.IBinder; -import android.os.RemoteException; -import android.view.View; -import android.widget.Toast; - -import com.android.vending.billing.IInAppBillingService; - -import org.json.JSONException; -import org.json.JSONObject; -import org.qpython.qpy.R; -import org.qpython.qpy.main.server.MySubscriber; - -import java.util.ArrayList; -import java.util.Arrays; - -import rx.Observable; -import rx.android.schedulers.AndroidSchedulers; -import rx.schedulers.Schedulers; - -/** - * Created by Hmei - * 1/31/18. - */ - -public class PayUtil { - private static final int BUY_REQUEST_CODE = 2333; - private IInAppBillingService mService; - private ServiceConnection mServiceConn; - private Activity context; - - public PayUtil(Activity context) { - this.context = context; - } - - public void initIAP(PayCallback callback) { - mServiceConn = new ServiceConnection() { - @Override - public void onServiceDisconnected(ComponentName name) { - mService = null; - } - - @Override - public void onServiceConnected(ComponentName name, - IBinder service) { - mService = IInAppBillingService.Stub.asInterface(service); - if (callback != null) callback.doAfterConn(); - } - }; - Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND"); - serviceIntent.setPackage("com.android.vending"); - context.bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE); - } - - /** - * 从Google服务器获取不同国家价格表并显示 - */ - public void getPrices(ArrayList skuList, MySubscriber callback) { - if (mService == null) { - Toast.makeText(context, R.string.lose_google_server, Toast.LENGTH_SHORT).show(); - if (context.findViewById(R.id.pb) != null) - context.findViewById(R.id.pb).setVisibility(View.GONE); - return; - } - Bundle querySkus = new Bundle(); - querySkus.putStringArrayList("ITEM_ID_LIST", skuList); - try { - Observable.just(mService.getSkuDetails(3, context.getPackageName(), "inapp", querySkus)) - .map(bundle -> { - ArrayList responseList = bundle.getStringArrayList("DETAILS_LIST"); - if (responseList == null) { - return null; - } - String[] prices = new String[responseList.size()]; - for (int i = 0; i < responseList.size(); i++) { - JSONObject object; - try { - object = new JSONObject(responseList.get(i)); - String price = object.getString("price"); - prices[i] = price; - } catch (JSONException e) { - e.printStackTrace(); - } - } - Arrays.sort(prices, (o1, o2) -> Integer.parseInt(o1.replaceAll("[^0-9]", "")) - Integer.parseInt(o2.replaceAll("[^0-9]", ""))); - return prices; - } - ) - .subscribeOn(Schedulers.newThread()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(callback); - } catch (RemoteException e) { - e.printStackTrace(); - } - } - - public void digestPurchase(String purchaseToken) { - // 消耗购买,使能重复赞赏同一金额 - try { - Observable.just(mService.consumePurchase(3, context.getPackageName(), purchaseToken)) - .subscribeOn(Schedulers.newThread()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(); - } catch (RemoteException e) { - e.printStackTrace(); - } - } - - public void purchase(String sku) { - try { - if (mService == null) { - Toast.makeText(context, R.string.lose_google_server, Toast.LENGTH_SHORT).show(); - return; - } - Bundle buyIntentBundle = mService.getBuyIntent(3, context.getPackageName(), - sku, "inapp", "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ"); - switch (buyIntentBundle.getInt("RESPONSE_CODE")) { - case 0: - //BILLING_RESPONSE_RESULT_OK - PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT"); - context.startIntentSenderForResult(pendingIntent.getIntentSender(), - BUY_REQUEST_CODE, new Intent(), 0, 0, 0); - break; - - } - } catch (RemoteException | IntentSender.SendIntentException | NullPointerException e) { - e.printStackTrace(); - } - } - - public void unbindPayService() { - if (mService != null) { - context.unbindService(mServiceConn); - } - } - - public interface PayCallback { - void doAfterConn(); - } - -} diff --git a/qpython/src/od/java/org/qpython/qpy/texteditor/TedLocalActivity.java b/qpython/src/od/java/org/qpython/qpy/texteditor/TedLocalActivity.java deleted file mode 100644 index 466f0c8a00a38ae98e370fe40929460a278eb079..0000000000000000000000000000000000000000 --- a/qpython/src/od/java/org/qpython/qpy/texteditor/TedLocalActivity.java +++ /dev/null @@ -1,308 +0,0 @@ -package org.qpython.qpy.texteditor; - - -import android.app.Activity; -import android.content.Context; -import android.content.Intent; -import android.content.res.Configuration; -import android.databinding.DataBindingUtil; -import android.graphics.drawable.Drawable; -import android.os.Bundle; -import android.support.v4.app.Fragment; -import android.support.v7.app.AppCompatActivity; -import android.view.MotionEvent; -import android.view.View; -import android.widget.EditText; -import android.widget.Toast; - -import com.google.gson.reflect.TypeToken; -import com.quseit.util.FileHelper; -import com.quseit.util.NAction; - -import org.qpython.qpy.R; -import org.qpython.qpy.codeshare.pojo.CloudFile; -import org.qpython.qpy.databinding.ActivityLocalBinding; -import org.qpython.qpy.main.activity.SignInActivity; -import org.qpython.qpy.main.app.App; -import org.qpython.qpy.main.app.CONF; -import org.qpython.qpy.main.fragment.ExplorerFragment; -import org.qpython.qpy.main.fragment.LocalFragment; -import org.qpython.qpy.main.fragment.MyProjectFragment; -import org.qpython.qpy.utils.NotebookUtil; -import org.qpython.qpysdk.QPyConstants; - -import java.io.File; -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class TedLocalActivity extends AppCompatActivity { - public static final int REQUEST_SAVE_AS = 107; - public static final int REQUEST_OPEN = 108; - public static final int REQUEST_HOME_PAGE = 109; - public static final int REQUEST_RECENT = 111; - private static final int LOGIN_REQUEST_CODE = 4806; - - private static final String EXTRA_REQUEST_CODE = "request_code"; - private static final String EXTRA_REQUEST_FN = "request_fn"; - - private static final String FRAGMENT_EXPLORER = "explorer"; - private static final String FRAGMENT_CLOUD = "cloud"; - - private ActivityLocalBinding binding; - - private Fragment firstPageFragment; - private MyProjectFragment myProjectFragment; - - private boolean isExplorer = true; - private boolean isNewUpload = false; - //private String defaultFileName = ""; - - public static void start(Context context, int type) { - Intent starter = new Intent(context, TedLocalActivity.class); - starter.putExtra(EXTRA_REQUEST_CODE, type); - context.startActivity(starter); - } - - public static void start(Activity context, int type, int requestCode, String filename) { - Intent starter = new Intent(context, TedLocalActivity.class); - starter.putExtra(EXTRA_REQUEST_CODE, type); - starter.putExtra(EXTRA_REQUEST_FN, filename); - - context.startActivityForResult(starter, requestCode); - } - - public void finishForGetPath(String path) { - Intent intent = new Intent(); - intent.putExtra("path", path); - setResult(Activity.RESULT_OK, intent); - finish(); - } - - public void finishForOpen(String path, boolean isProj) { - Intent intent = new Intent(); - intent.putExtra("path", path); - intent.putExtra("isProj", isProj); - setResult(Activity.RESULT_OK, intent); - finish(); - } - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - binding = DataBindingUtil.setContentView(this, R.layout.activity_local); - setSupportActionBar(binding.toolbar); - int type = getIntent().getIntExtra(EXTRA_REQUEST_CODE, REQUEST_HOME_PAGE); - - initView(); - initListener(); - switch (type) { - case REQUEST_RECENT: - setTitle(R.string.recent); - binding.switchBtn.setVisibility(View.GONE); - firstPageFragment = ExplorerFragment.newInstance(type); - break; - case REQUEST_OPEN: - setTitle(R.string.open); - binding.switchBtn.setVisibility(View.GONE); - binding.explore.setVisibility(View.VISIBLE); - firstPageFragment = new LocalFragment(); - break; - case REQUEST_SAVE_AS: - setTitle(R.string.save_as); - binding.vsSave.getRoot().setVisibility(View.VISIBLE); - initSaveListener(); - - String fn = getIntent().getStringExtra(EXTRA_REQUEST_FN); - if (fn!=null) { - binding.vsSave.etName.setText(fn); - } - binding.switchBtn.setVisibility(View.GONE); - firstPageFragment = ExplorerFragment.newInstance(type); - break; - case REQUEST_HOME_PAGE: - setTitle(R.string.explorer); - firstPageFragment = ExplorerFragment.newInstance(type); - break; - } - - getSupportFragmentManager().beginTransaction() - .add(R.id.container, firstPageFragment, FRAGMENT_EXPLORER) - .commit(); - } - - @Override - public void onConfigurationChanged(Configuration newConfig) { - super.onConfigurationChanged(newConfig); - } - - private void initView() { - binding.toolbar.setNavigationIcon(R.drawable.ic_back); - binding.toolbar.setNavigationOnClickListener(v -> finish()); - if (binding.switchBtn.getVisibility() == View.VISIBLE) { - myProjectFragment = new MyProjectFragment(); - } - } - - private void initListener() { - binding.switchBtn.setOnClickListener(v -> { - if (isExplorer) { - if (App.getUser() == null) { - startActivityForResult(new Intent(this, SignInActivity.class), LOGIN_REQUEST_CODE); - return; - } - binding.switchBtn.setImageResource(R.drawable.ic_folder_open); - binding.refresh.setVisibility(View.VISIBLE); - if (getSupportFragmentManager().findFragmentByTag(FRAGMENT_CLOUD) == null) { - getSupportFragmentManager().beginTransaction().add(R.id.container, myProjectFragment, FRAGMENT_CLOUD).commit(); - getSupportFragmentManager().beginTransaction().hide(firstPageFragment).commit(); - } else { - getSupportFragmentManager().beginTransaction() - .hide(firstPageFragment) - .show(myProjectFragment) - .commit(); - } - myProjectFragment.needRefresh(isNewUpload); - isNewUpload = false; - if (!myProjectFragment.isLoading) { - myProjectFragment.notifyDataSetChange(); - } - } else { - binding.switchBtn.setImageResource(R.drawable.ic_cloud_list); - binding.refresh.setVisibility(View.GONE); - getSupportFragmentManager().beginTransaction() - .hide(myProjectFragment) - .show(firstPageFragment) - .commit(); - } - isExplorer = !isExplorer; - }); - - binding.refresh.setOnClickListener(v -> myProjectFragment.retry(true)); - - binding.explore.setOnClickListener(v -> { - start(this, REQUEST_HOME_PAGE); - finish(); - }); - } - - public void doSave(String fn) { - if (fn.length() == 0) { - Toast.makeText(getApplicationContext(), R.string.toast_filename_empty, Toast.LENGTH_SHORT).show(); - } else { - String filename = ((ExplorerFragment) firstPageFragment).getCurPath() + "/" + fn; - final File f = new File(filename); - if (f.exists()) { - Toast.makeText(this, R.string.file_exist_hint, Toast.LENGTH_SHORT).show(); - } else { - setSaveResult(f.getAbsolutePath()); - } - } - } - - protected boolean setSaveResult(String filepath) { - File f = new File(filepath); - if (f.getParentFile().canWrite()) { - finishForGetPath(filepath); - } else { - Toast.makeText(getApplicationContext(), R.string.toast_folder_cant_write, Toast.LENGTH_SHORT).show(); - } - return true; - } - - private void initSaveListener() { - binding.vsSave.btnSave.setOnClickListener(v -> doSave(binding.vsSave.etName.getText().toString())); - binding.vsSave.etName.setOnTouchListener((v, event) -> { - final int DRAWABLE_RIGHT = 2; - switch (event.getAction()) { - case MotionEvent.ACTION_DOWN: - Drawable deleteText = ((EditText) v).getCompoundDrawables()[DRAWABLE_RIGHT]; - if (deleteText != null) { - if (event.getRawX() >= (v.getRight() - deleteText.getBounds().width())) { - ((EditText) v).setText(""); - return true; - } - } - break; - case MotionEvent.ACTION_UP: - v.performClick(); - break; - default: - break; - } - return false; - }); - } - - @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) { - super.onActivityResult(requestCode, resultCode, data); - if (resultCode == RESULT_OK) { - switch (requestCode) { - case LOGIN_REQUEST_CODE: - binding.switchBtn.setImageResource(R.drawable.ic_folder_open); - if (getSupportFragmentManager().findFragmentByTag(FRAGMENT_CLOUD) == null) { - getSupportFragmentManager().beginTransaction().add(R.id.container, myProjectFragment, FRAGMENT_CLOUD).commit(); - getSupportFragmentManager().beginTransaction().hide(firstPageFragment).commit(); - } else { - getSupportFragmentManager().beginTransaction() - .hide(firstPageFragment) - .show(myProjectFragment) - .commit(); - } - isExplorer = !isExplorer; - break; - } - } - } - - @Override - public void onBackPressed() { - if (firstPageFragment.isVisible() && firstPageFragment instanceof ExplorerFragment) { - ((ExplorerFragment) firstPageFragment).backToPrev(); - } else { - super.onBackPressed(); - } - } - -// public void deleteCloudFile(String path) { -// if (firstPageFragment instanceof ExplorerFragment) { -// ((ExplorerFragment) firstPageFragment).deleteCloudedMap(path); -// } -// } -// -// public void updateCloudFiles(List cloudFiles) { -// Map map = new HashMap<>(); -// boolean isQPy3 = NAction.isQPy3(getBaseContext()); -// String tag = isQPy3?"/projects3/":"/projects/"; -// for (CloudFile cloudFile : cloudFiles) { -// if (cloudFile.getPath().contains(tag)) { -// map.put(QPyConstants.ABSOLUTE_PATH + tag + cloudFile.getProjectName(), true); -// } -// map.put(QPyConstants.ABSOLUTE_PATH + cloudFile.getPath(), true); -// } -// ((ExplorerFragment) firstPageFragment).updateCloudedFiles(map); -// } -// -// public void setNewUpload() { -// isNewUpload = true; -// } - - /** - * 保存云端文件目录到本地 - */ -// public void locatedCloud(List cloudFiles) { -// if (cloudFiles.size() > 0) { -// Type type = new TypeToken>() { -// }.getType(); -// FileHelper.writeToFile(CONF.CLOUD_MAP_CACHE_PATH, App.getGson().toJson(cloudFiles, type)); -// } -// } - - @Override - protected void onDestroy() { - super.onDestroy(); - NotebookUtil.killServer(); - } -} diff --git a/qpython/src/od/res/layout/activity_local.xml b/qpython/src/od/res/layout/activity_local.xml deleted file mode 100644 index abdcb0aa6c377b9f24fda22f490364298c9ac216..0000000000000000000000000000000000000000 --- a/qpython/src/od/res/layout/activity_local.xml +++ /dev/null @@ -1,86 +0,0 @@ - - - - - - - - - - - - - -