Skip to content

Commit

Permalink
feat: add getchannel
Browse files Browse the repository at this point in the history
  • Loading branch information
riderx committed Nov 3, 2022
1 parent cddbf50 commit 52fb699
Show file tree
Hide file tree
Showing 7 changed files with 182 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -457,6 +457,60 @@ public void onErrorResponse(VolleyError error) {
}
}

public void getChannel(final CallbackChannel callback) {
String channelUrl = this.channelUrl;
if (channelUrl == null || "".equals(channelUrl) || channelUrl.length() == 0) {
return;
}
try {
JSONObject json = new JSONObject();
json.put("platform", "android");
json.put("device_id", this.deviceID);
json.put("app_id", this.appId);
json.put("version_build", this.versionBuild);
json.put("version_code", this.versionCode);
json.put("version_os", this.versionOs);
json.put("version_name", this.getCurrentBundle().getVersionName());
json.put("plugin_version", pluginVersion);

// Building a request
JsonObjectRequest request = new JsonObjectRequest(
Request.Method.PUT,
channelUrl,
json,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject res) {
final JSObject ret = new JSObject();
Iterator<String> keys = res.keys();
while (keys.hasNext()) {
String key = keys.next();
if (res.has(key)) {
try {
ret.put(key, res.get(key));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Log.i(TAG, "Channel get to \"" + ret);
callback.callback(ret);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error get channel: " + error);
}
}
);
this.requestQueue.add(request);
} catch (JSONException ex) {
// Catch if something went wrong with the params
Log.e(TAG, "Error getChannel JSONException", ex);
}
}

public void sendStats(final String action, final String versionName) {
String statsUrl = this.statsUrl;
if (statsUrl == null || "".equals(statsUrl) || statsUrl.length() == 0) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,28 @@ public void run() {
}
}

@PluginMethod
public void getChannel(final PluginCall call) {
try {
Log.i(CapacitorUpdater.TAG, "getChannel");
new Thread(
new Runnable() {
@Override
public void run() {
CapacitorUpdaterPlugin.this.implementation.getChannel(
res -> {
call.resolve(res);
});
}
}
)
.start();
} catch (final Exception e) {
Log.e(CapacitorUpdater.TAG, "Failed to getChannel", e);
call.reject("Failed to getChannel", e);
}
}

@PluginMethod
public void download(final PluginCall call) {
final String url = call.getString("url");
Expand Down
66 changes: 66 additions & 0 deletions ios/Plugin/CapacitorUpdater.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,30 @@ extension SetChannel {
return dict
}
}
struct GetChannelDec: Decodable {
let channel: String?
let status: String?
let error: String?
let allowSet: Bool?
}
public class GetChannel: NSObject {
var channel: String = ""
var status: String = ""
var error: String = ""
var allowSet: Bool = true
}
extension GetChannel {
func toDict() -> [String: Any] {
var dict = [String: Any]()
let otherSelf = Mirror(reflecting: self)
for child in otherSelf.children {
if let key = child.label {
dict[key] = child.value
}
}
return dict
}
}
struct AppVersionDec: Decodable {
let version: String?
let checksum: String?
Expand Down Expand Up @@ -515,6 +539,48 @@ extension CustomError: LocalizedError {
return setChannel
}

func getChannel() -> SetChannel? {
if self.channelUrl == "" {
return nil
}
let semaphore = DispatchSemaphore(value: 0)
let getChannel = GetChannel()
let parameters: [String: String] = [
"platform": "ios",
"device_id": self.deviceID,
"version_name": self.getCurrentBundle().getVersionName(),
"version_build": self.versionName,
"version_code": self.versionCode,
"version_os": self.versionOs,
"plugin_version": self.pluginVersion,
"app_id": self.appId
]
let request = AF.request(self.channelUrl, method: .put, parameters: parameters, encoder: JSONParameterEncoder.default)

request.validate().responseDecodable(of: GetChannelDec.self) { response in
switch response.result {
case .success:
if let status = response.value?.status {
getChannel.status = status
}
if let error = response.value?.error {
getChannel.error = error
}
if let channel = response.value?.channel {
getChannel.channel = channel
}
if let allowSet = response.value?.allowSet {
getChannel.allowSet = allowSet
}
case let .failure(error):
print("\(self.TAG) Error get Channel", error )
}
semaphore.signal()
}
semaphore.wait()
return getChannel
}

func sendStats(action: String, versionName: String) {
if self.statsUrl == "" {
return
Expand Down
1 change: 1 addition & 0 deletions ios/Plugin/CapacitorUpdaterPlugin.m
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
CAP_PLUGIN_METHOD(cancelDelay, CAPPluginReturnPromise);
CAP_PLUGIN_METHOD(getLatest, CAPPluginReturnPromise);
CAP_PLUGIN_METHOD(setChannel, CAPPluginReturnPromise);
CAP_PLUGIN_METHOD(getChannel, CAPPluginReturnPromise);
CAP_PLUGIN_METHOD(getDeviceId, CAPPluginReturnPromise);
CAP_PLUGIN_METHOD(getPluginVersion, CAPPluginReturnPromise);
CAP_PLUGIN_METHOD(next, CAPPluginReturnPromise);
Expand Down
10 changes: 10 additions & 0 deletions ios/Plugin/CapacitorUpdaterPlugin.swift
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,16 @@ public class CapacitorUpdaterPlugin: CAPPlugin {
}
}

@objc func getChannel(_ call: CAPPluginCall) {
DispatchQueue.global(qos: .background).async {
guard let res = self.implementation.getChannel() else {
call.reject("Cannot getChannel")
return
}
call.resolve(res.toDict())
}
}

@objc func _reset(toLastSuccessful: Bool) -> Bool {
guard let bridge = self.bridge else { return false }

Expand Down
21 changes: 21 additions & 0 deletions src/definitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,18 @@ export interface channelRes {
error?: any;
}

export interface getChannelRes {
/**
* Current status of get channel
*
* @since 4.8.0
*/
channel?: string;
error?: any;
status?: string,
allowSet?: boolean,
}

export interface DownloadEvent {
/**
* Current status of download, between 0 and 100.
Expand Down Expand Up @@ -346,6 +358,15 @@ export interface CapacitorUpdaterPlugin {
*/
setChannel(options: SetChannelOptions): Promise<channelRes>;

/**
* get Channel for this device
*
* @returns {Promise<channelRes>} an Promise resolved with channel info
* @throws An error if the something went wrong
* @since 4.8.0
*/
getChannel(): Promise<getChannelRes>;

/**
* Listen for download event in the App, let you know when the download is started, loading and finished
*
Expand Down
9 changes: 8 additions & 1 deletion src/web.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { WebPlugin } from '@capacitor/core';

import type { CapacitorUpdaterPlugin, BundleInfo, latestVersion, DelayCondition, channelRes, SetChannelOptions } from './definitions';
import type { CapacitorUpdaterPlugin, BundleInfo, latestVersion, DelayCondition, channelRes, SetChannelOptions, getChannelRes } from './definitions';

const BUNDLE_BUILTIN: BundleInfo = {
status: 'success',
Expand Down Expand Up @@ -68,6 +68,13 @@ export class CapacitorUpdaterWeb extends WebPlugin implements CapacitorUpdaterPl
error: 'Cannot setChannel in web',
};
}
async getChannel(): Promise<getChannelRes> {
console.warn('Cannot getChannel in web');
return {
status: 'error',
error: 'Cannot getChannel in web',
};
}
async notifyAppReady(): Promise<BundleInfo> {
console.warn('Cannot notify App Ready in web');
return BUNDLE_BUILTIN;
Expand Down

0 comments on commit 52fb699

Please sign in to comment.