Skip to content

Commit

Permalink
feat: add stats methods
Browse files Browse the repository at this point in the history
  • Loading branch information
riderx committed Feb 13, 2022
1 parent 9b9ccc0 commit 53a50d7
Show file tree
Hide file tree
Showing 5 changed files with 71 additions and 19 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.util.Log;

import com.android.volley.RequestQueue;
Expand All @@ -22,18 +23,23 @@
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.ArrayList;
import android.provider.Settings.Secure;

interface Callback {
void callback(JSONObject jsonObject);
}

public class CapacitorUpdater {
String TAG = "Capacitor-updater";
private String TAG = "Capacitor-updater";
public String statsUrl = "";

private Context context;
private String basePathHot = "versions";
private SharedPreferences prefs;
Expand Down Expand Up @@ -245,4 +251,41 @@ public void reset() {
editor.putString("versionName", "");
editor.commit();
}

public void sendStats(String action, String version) {
if (statsUrl == "") { return; }

String statsUrl = this.statsUrl;
Context context = this.context;
new Thread(new Runnable(){
@Override
public void run() {
try {
URL url = new URL(statsUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; utf-8");
con.setRequestProperty("Accept", "application/json");
con.setDoOutput(true);
JSONObject json = new JSONObject();
String android_id = Secure.getString(context.getContentResolver(),
Secure.ANDROID_ID);
PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
json.put("platform", "android");
json.put("action", action);
json.put("device_id", android_id);
json.put("version_name", version);
json.put("version_build", pInfo.versionName);
json.put("app_id", "");
con.setConnectTimeout(500);
try(OutputStream os = con.getOutputStream()) {
byte[] input = json.toString().getBytes("utf-8");
os.write(input, 0, input.length);
}
} catch (Exception ex) {
Log.e(TAG, "Error post stats");
}
}
}).start();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

@CapacitorPlugin(name = "CapacitorUpdater")
public class CapacitorUpdaterPlugin extends Plugin implements Application.ActivityLifecycleCallbacks {
String TAG = "Capacitor-updater";
private String TAG = "Capacitor-updater";
private CapacitorUpdater implementation;
private SharedPreferences prefs;
private SharedPreferences.Editor editor;
Expand All @@ -35,6 +35,8 @@ public void load() {
this.prefs = this.getContext().getSharedPreferences("CapWebViewSettings", Activity.MODE_PRIVATE);
this.editor = prefs.edit();
implementation = new CapacitorUpdater(this.getContext());
String statsUrl = getConfig().getString("statsUrl");
implementation.statsUrl = statsUrl == null ? statsUrl : "https://capgo.app/api/stats";
this.autoUpdateUrl = getConfig().getString("autoUpdateUrl");
if (this.autoUpdateUrl == null || this.autoUpdateUrl.equals("")) return;
Application application = (Application) this.getContext().getApplicationContext();
Expand Down Expand Up @@ -93,8 +95,9 @@ public void set(PluginCall call) {
@PluginMethod
public void delete(PluginCall call) {
String version = call.getString("version");
String versionName = implementation.getVersionName();
try {
Boolean res = implementation.delete(version);
Boolean res = implementation.delete(version, versionName);

if (res) {
call.resolve();
Expand Down Expand Up @@ -123,6 +126,8 @@ private boolean _reset() {
}
@PluginMethod
public void reset(PluginCall call) {
String version = prefs.getString("versionName", "");
implementation.sendStats("reset", version);
this._reset();
call.resolve();
}
Expand Down Expand Up @@ -161,6 +166,7 @@ public void delayUpdate(PluginCall call) {
public void onActivityStarted(@NonNull Activity activity) {
Log.i(TAG, "Check for update in the server");
if (autoUpdateUrl == null || autoUpdateUrl.equals("")) return;
CapacitorUpdater implementation = this.implementation;
new Thread(new Runnable(){
@Override
public void run() {
Expand All @@ -180,9 +186,15 @@ public void run() {
Log.i(TAG, "New version: " + newVersion + " found. Current is " + (currentVersion == "" ? "builtin" : currentVersion) + ", next backgrounding will trigger update.");
editor.putString("nextVersion", dl);
editor.putString("nextVersionName", (String) res.get("version"));
implementation.sendStats("set", (String) res.get("version"));
editor.commit();
} catch (JSONException e) {
e.printStackTrace();
try {
implementation.sendStats("set_fail", (String) res.get("version"));
} catch (JSONException jsonException) {
jsonException.printStackTrace();
}
}
}
}).start();
Expand Down Expand Up @@ -234,6 +246,7 @@ public void onActivityStopped(@NonNull Activity activity) {
Log.i(TAG, "Version: " + curVersionName + ", is considered broken");
Log.i(TAG, "Will downgraded to " + pastVersionName + " for next start");
Log.i(TAG, "Don't forget to trigger 'notifyAppReady()' in js code to validate a version.");
implementation.sendStats("revert",curVersionName);
if (!pastVersion.equals("") && !pastVersionName.equals("")) {
Boolean res = implementation.set(pastVersion, pastVersionName);
if (res) {
Expand All @@ -252,7 +265,7 @@ public void onActivityStopped(@NonNull Activity activity) {
editor.putString("failingVersion", curVersionName);
editor.commit();
try {
Boolean res = implementation.delete(curVersion);
Boolean res = implementation.delete(curVersion, curVersionName);
if (res) {
Log.i(TAG, "Delete failing version: " + curVersionName);
}
Expand All @@ -262,7 +275,7 @@ public void onActivityStopped(@NonNull Activity activity) {
} else if (!pastVersion.equals("")) {
Log.i(TAG, "Validated version: " + curVersionName);
try {
Boolean res = implementation.delete(pastVersion);
Boolean res = implementation.delete(pastVersion, curVersionName);
if (res) {
Log.i(TAG, "Delete past version: " + pastVersionName);
}
Expand Down
19 changes: 8 additions & 11 deletions ios/Plugin/CapacitorUpdater.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ extension Bundle {

@objc public class CapacitorUpdater: NSObject {

private var statsUrl = ""
public var statsUrl = ""
private var lastPathHot = ""
private var lastPathPersist = ""
private let basePathHot = "versions"
Expand All @@ -38,10 +38,6 @@ extension Bundle {
private let libraryUrl = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first!


init(statsUrl: String = "") {
self.statsUrl = statsUrl
}

@objc private func randomString(length: Int) -> String {
let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
return String((0..<length).map{ _ in letters.randomElement()! })
Expand Down Expand Up @@ -156,7 +152,7 @@ extension Bundle {
} catch {
print("✨ Capacitor-updater: No version available" + dest.path)
return []
}
}
}

@objc public func delete(version: String, versionName: String) -> Bool {
Expand Down Expand Up @@ -221,15 +217,16 @@ extension Bundle {
let versionBuild = Bundle.main.buildVersionNumber ?? ""
let bundleIdentifier = Bundle.main.bundleIdentifier ?? ""
_ = Just.post(self.statsUrl,
data: [
json: [
"platform": "ios",
"action": action,
"device_id": deviceID,
"version": version,
"versionBuild": versionBuild,
"appid": bundleIdentifier
]
"version_name": version,
"version_build": versionBuild,
"app_id": bundleIdentifier
]
)
print("✨ Capacitor-updater: Stats send for " + action + ", version " + version)
}
}

Expand Down
3 changes: 1 addition & 2 deletions ios/Plugin/CapacitorUpdaterPlugin.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@ public class CapacitorUpdaterPlugin: CAPPlugin {

override public func load() {
autoUpdateUrl = getConfigValue("autoUpdateUrl") as? String ?? ""
let statsUrl = getConfigValue("statsUrl") as? String ?? ""
implementation = CapacitorUpdater(statsUrl: statsUrl)
implementation.statsUrl = getConfigValue("statsUrl") as? String ?? "https://capgo.app/api/stats"
if (autoUpdateUrl == "") { return }
let nc = NotificationCenter.default
nc.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "capacitor-updater",
"version": "1.2.1",
"version": "1.3.0",
"license": "AGPL-3.0-only",
"description": "Download app update from url",
"main": "dist/plugin.cjs.js",
Expand Down

0 comments on commit 53a50d7

Please sign in to comment.