GithubHelp home page GithubHelp logo

cap-go / capacitor-updater Goto Github PK

View Code? Open in Web Editor NEW
457.0 10.0 101.0 3.3 MB

Live update for capacitor apps

Home Page: https://capgo.app

License: Mozilla Public License 2.0

Ruby 0.63% Java 46.43% HTML 0.15% TypeScript 10.22% CSS 0.08% Swift 41.37% Objective-C 0.90% JavaScript 0.22%
capacitor capacitor-plugin ios android hot-reload ionic cordova typescript

capacitor-updater's Introduction

Capacitor updater

Capgo - Instant updates for capacitor Discord Discord npm GitHub latest commit https://good-labs.github.io/greater-good-affirmation/assets/images/badge.svg Security Rating Bugs Maintainability Rating Code Smells Vulnerabilities Quality Gate Status Technical Debt Open Bounties Rewarded Bounties

Update Ionic Capacitor apps without App/Play Store review (Code-push / hot-code updates).

You have 3 ways possible :

  • Use capgo.app a full featured auto-update system in 5 min Setup, to manage version, update, revert and see stats.
  • Use your own server update with auto-update system
  • Use manual methods to zip, upload, download, from JS to do it when you want.

Community

Join the discord to get help.

Documentation

I maintain a more user-friendly and complete documentation here.

Installation

npm install @capgo/capacitor-updater
npx cap sync

Auto-update setup

Create your account in capgo.app and get your API key

  • Login to CLI npx @capgo/cli@latest init API_KEY And follow the steps by step to setup your app.

For detailed instructions on the auto-update setup, refer to the Auto update documentation.

Manual setup

Download update distribution zipfiles from a custom URL. Manually control the entire update process.

  • Edit your capacitor.config.json like below, set autoUpdate to false.
// capacitor.config.json
{
	"appId": "**.***.**",
	"appName": "Name",
	"plugins": {
		"CapacitorUpdater": {
			"autoUpdate": false,
		}
	}
}
  • Add to your main code
  import { CapacitorUpdater } from '@capgo/capacitor-updater'
  CapacitorUpdater.notifyAppReady()

This informs Capacitor Updater that the current update bundle has loaded succesfully. Failing to call this method will cause your application to be rolled back to the previously successful version (or built-in bundle).

  • Add this to your application.
  const version = await CapacitorUpdater.download({
    url: 'https://github.com/Cap-go/demo-app/releases/download/0.0.4/dist.zip',
  })
  await CapacitorUpdater.set(version); // sets the new version, and reloads the app
  • Failed updates will automatically roll back to the last successful version.
  • Example: Using App-state to control updates, with SplashScreen: You might also consider performing auto-update when application state changes, and using the Splash Screen to improve user experience.
  import { CapacitorUpdater, VersionInfo } from '@capgo/capacitor-updater'
  import { SplashScreen } from '@capacitor/splash-screen'
  import { App } from '@capacitor/app'

  let version: VersionInfo;
  App.addListener('appStateChange', async (state) => {
      if (state.isActive) {
        // Ensure download occurs while the app is active, or download may fail
        version = await CapacitorUpdater.download({
          url: 'https://github.com/Cap-go/demo-app/releases/download/0.0.4/dist.zip',
        })
      }

      if (!state.isActive && version) {
        // Activate the update when the application is sent to background
        SplashScreen.show()
        try {
          await CapacitorUpdater.set(version);
          // At this point, the new version should be active, and will need to hide the splash screen
        } catch () {
          SplashScreen.hide() // Hide the splash screen again if something went wrong
        }
      }
  })

TIP: If you prefer a secure and automated way to update your app, you can use capgo.app - a full-featured, auto-update system.

Store Guideline Compliance

Android Google Play and iOS App Store have corresponding guidelines that have rules you should be aware of before integrating the Capacitor-updater solution within your application.

Google play

Third paragraph of Device and Network Abuse topic describe that updating source code by any method besides Google Play's update mechanism is restricted. But this restriction does not apply to updating JavaScript bundles.

This restriction does not apply to code that runs in a virtual machine and has limited access to Android APIs (such as JavaScript in a web view or browser).

That fully allow Capacitor-updater as it updates just JS bundles and can't update native code part.

App Store

Paragraph 3.3.2, since back in 2015's Apple Developer Program License Agreement fully allowed performing over-the-air updates of JavaScript and assets.

And in its latest version (20170605) downloadable here this ruling is even broader:

Interpreted code may be downloaded to an Application, but only so long as such code:

  • (a) does not change the primary purpose of the Application by providing features or functionality that are inconsistent with the intended and advertised purpose of the Application as submitted to the App Store
  • (b) does not create a store or storefront for other code or applications
  • (c) does not bypass signing, sandbox, or other security features of the OS.

Capacitor-updater allows you to respect these rules in full compliance, so long as the update you push does not significantly deviate your product from its original App Store approved intent.

To further remain in compliance with Apple's guidelines, we suggest that App Store-distributed apps don't enable the Force update scenario, since in the App Store Review Guidelines it is written that:

Apps must not force users to rate the app, review the app, download other apps, or other similar actions to access functionality, content, or use of the app.

This is not a problem for the default behavior of background update, since it won't force the user to apply the new version until the next app close, but at least you should be aware of that ruling if you decide to show it.

Packaging dist.zip update bundles

Capacitor Updater works by unzipping a compiled app bundle to the native device filesystem. Whatever you choose to name the file you upload/download from your release/update server URL (via either manual or automatic updating), this .zip bundle must meet the following requirements:

  • The zip file should contain the full contents of your production Capacitor build output folder, usually {project directory}/dist/ or {project directory}/www/. This is where index.html will be located, and it should also contain all bundled JavaScript, CSS, and web resources necessary for your app to run.
  • Do not password encrypt the bundle zip file, or it will fail to unpack.
  • Make sure the bundle does not contain any extra hidden files or folders, or it may fail to unpack.

Updater Plugin Config

CapacitorUpdater can be configured with these options:

Prop Type Description Default Since
appReadyTimeout number Configure the number of milliseconds the native plugin should wait before considering an update 'failed'. Only available for Android and iOS. 10000 // (10 seconds)
responseTimeout number Configure the number of milliseconds the native plugin should wait before considering API timeout. Only available for Android and iOS. 20 // (20 second)
autoDeleteFailed boolean Configure whether the plugin should use automatically delete failed bundles. Only available for Android and iOS. true
autoDeletePrevious boolean Configure whether the plugin should use automatically delete previous bundles after a successful update. Only available for Android and iOS. true
autoUpdate boolean Configure whether the plugin should use Auto Update via an update server. Only available for Android and iOS. true
resetWhenUpdate boolean Automatically delete previous downloaded bundles when a newer native app bundle is installed to the device. Only available for Android and iOS. true
updateUrl string Configure the URL / endpoint to which update checks are sent. Only available for Android and iOS. https://api.capgo.app/auto_update
statsUrl string Configure the URL / endpoint to which update statistics are sent. Only available for Android and iOS. Set to "" to disable stats reporting. https://api.capgo.app/stats
privateKey string Configure the private key for end to end live update encryption. Only available for Android and iOS. undefined
version string Configure the current version of the app. This will be used for the first update request. If not set, the plugin will get the version from the native code. Only available for Android and iOS. undefined 4.17.48
directUpdate boolean Make the plugin direct install the update when the app what just updated/installed. Only for autoUpdate mode. Only available for Android and iOS. undefined 5.1.0
periodCheckDelay number Configure the delay period for period update check. the unit is in seconds. Only available for Android and iOS. Cannot be less than 600 seconds (10 minutes). 600 // (10 minutes)
localS3 boolean Configure the CLI to use a local server for testing or self-hosted update server. undefined 4.17.48
localHost string Configure the CLI to use a local server for testing or self-hosted update server. undefined 4.17.48
localWebHost string Configure the CLI to use a local server for testing or self-hosted update server. undefined 4.17.48
localSupa string Configure the CLI to use a local server for testing or self-hosted update server. undefined 4.17.48
localSupaAnon string Configure the CLI to use a local server for testing. undefined 4.17.48
allowModifyUrl boolean Allow the plugin to modify the updateUrl, statsUrl and channelUrl dynamically from the JavaScript side. false 5.4.0
defaultChannel string Set the default channel for the app in the config. undefined 5.5.0

Examples

In capacitor.config.json:

{
  "plugins": {
    "CapacitorUpdater": {
      "appReadyTimeout": 1000 // (1 second),
      "responseTimeout": 10 // (10 second),
      "autoDeleteFailed": false,
      "autoDeletePrevious": false,
      "autoUpdate": false,
      "resetWhenUpdate": false,
      "updateUrl": https://example.com/api/auto_update,
      "statsUrl": https://example.com/api/stats,
      "privateKey": undefined,
      "version": undefined,
      "directUpdate": undefined,
      "periodCheckDelay": undefined,
      "localS3": undefined,
      "localHost": undefined,
      "localWebHost": undefined,
      "localSupa": undefined,
      "localSupaAnon": undefined,
      "allowModifyUrl": undefined,
      "defaultChannel": undefined
    }
  }
}

In capacitor.config.ts:

/// <reference types="@capgo/capacitor-updater" />

import { CapacitorConfig } from '@capacitor/cli';

const config: CapacitorConfig = {
  plugins: {
    CapacitorUpdater: {
      appReadyTimeout: 1000 // (1 second),
      responseTimeout: 10 // (10 second),
      autoDeleteFailed: false,
      autoDeletePrevious: false,
      autoUpdate: false,
      resetWhenUpdate: false,
      updateUrl: https://example.com/api/auto_update,
      statsUrl: https://example.com/api/stats,
      privateKey: undefined,
      version: undefined,
      directUpdate: undefined,
      periodCheckDelay: undefined,
      localS3: undefined,
      localHost: undefined,
      localWebHost: undefined,
      localSupa: undefined,
      localSupaAnon: undefined,
      allowModifyUrl: undefined,
      defaultChannel: undefined,
    },
  },
};

export default config;

API

notifyAppReady()

notifyAppReady() => Promise<AppReadyResult>

Notify Capacitor Updater that the current bundle is working (a rollback will occur if this method is not called on every app launch) By default this method should be called in the first 10 sec after app launch, otherwise a rollback will occur. Change this behaviour with {@link appReadyTimeout}

Returns: Promise<AppReadyResult>


setUpdateUrl(...)

setUpdateUrl(options: UpdateUrl) => Promise<void>

Set the updateUrl for the app, this will be used to check for updates.

Param Type Description
options UpdateUrl contains the URL to use for checking for updates.

Since: 5.4.0


setStatsUrl(...)

setStatsUrl(options: StatsUrl) => Promise<void>

Set the statsUrl for the app, this will be used to send statistics. Passing an empty string will disable statistics gathering.

Param Type Description
options StatsUrl contains the URL to use for sending statistics.

Since: 5.4.0


setChannelUrl(...)

setChannelUrl(options: ChannelUrl) => Promise<void>

Set the channelUrl for the app, this will be used to set the channel.

Param Type Description
options ChannelUrl contains the URL to use for setting the channel.

Since: 5.4.0


download(...)

download(options: DownloadOptions) => Promise<BundleInfo>

Download a new bundle from the provided URL, it should be a zip file, with files inside or with a unique id inside with all your files

Param Type Description
options DownloadOptions The {@link DownloadOptions} for downloading a new bundle zip.

Returns: Promise<BundleInfo>


next(...)

next(options: BundleId) => Promise<BundleInfo>

Set the next bundle to be used when the app is reloaded.

Param Type Description
options BundleId Contains the ID of the next Bundle to set on next app launch. {@link BundleInfo.id}

Returns: Promise<BundleInfo>


set(...)

set(options: BundleId) => Promise<void>

Set the current bundle and immediately reloads the app.

Param Type Description
options BundleId A {@link BundleId} object containing the new bundle id to set as current.

delete(...)

delete(options: BundleId) => Promise<void>

Deletes the specified bundle from the native app storage. Use with {@link list} to get the stored Bundle IDs.

Param Type Description
options BundleId A {@link BundleId} object containing the ID of a bundle to delete (note, this is the bundle id, NOT the version name)

list()

list() => Promise<BundleListResult>

Get all locally downloaded bundles in your app

Returns: Promise<BundleListResult>


reset(...)

reset(options?: ResetOptions | undefined) => Promise<void>

Reset the app to the builtin bundle (the one sent to Apple App Store / Google Play Store ) or the last successfully loaded bundle.

Param Type Description
options ResetOptions Containing {@link ResetOptions.toLastSuccessful}, true resets to the builtin bundle and false will reset to the last successfully loaded bundle.

current()

current() => Promise<CurrentBundleResult>

Get the current bundle, if none are set it returns builtin. currentNative is the original bundle installed on the device

Returns: Promise<CurrentBundleResult>


reload()

reload() => Promise<void>

Reload the view


setMultiDelay(...)

setMultiDelay(options: MultiDelayConditions) => Promise<void>

Sets a {@link DelayCondition} array containing conditions that the Plugin will use to determine when to install updates.

Param Type Description
options MultiDelayConditions Containing the {@link MultiDelayConditions} array of conditions to set

Since: 4.3.0


cancelDelay()

cancelDelay() => Promise<void>

Cancels a {@link DelayCondition} to process an update immediately.

Since: 4.0.0


getLatest()

getLatest() => Promise<LatestVersion>

Get Latest bundle available from update Url

Returns: Promise<LatestVersion>

Since: 4.0.0


setChannel(...)

setChannel(options: SetChannelOptions) => Promise<ChannelRes>

Sets the channel for this device. The channel has to allow for self assignment for this to work. Do not use this method to set the channel at boot when autoUpdate is enabled in the {@link PluginsConfig}. This method is to set the channel after the app is ready.

Param Type Description
options SetChannelOptions Is the {@link SetChannelOptions} channel to set

Returns: Promise<ChannelRes>

Since: 4.7.0


unsetChannel(...)

unsetChannel(options: UnsetChannelOptions) => Promise<void>

Unset the channel for this device. The device will then return to the default channel

Param Type
options UnsetChannelOptions

Since: 4.7.0


getChannel()

getChannel() => Promise<GetChannelRes>

Get the channel for this device

Returns: Promise<GetChannelRes>

Since: 4.8.0


setCustomId(...)

setCustomId(options: SetCustomIdOptions) => Promise<void>

Set a custom ID for this device

Param Type Description
options SetCustomIdOptions is the {@link SetCustomIdOptions} customId to set

Since: 4.9.0


getBuiltinVersion()

getBuiltinVersion() => Promise<BuiltinVersion>

Get the native app version or the builtin version if set in config

Returns: Promise<BuiltinVersion>

Since: 5.2.0


getDeviceId()

getDeviceId() => Promise<DeviceId>

Get unique ID used to identify device (sent to auto update server)

Returns: Promise<DeviceId>


getPluginVersion()

getPluginVersion() => Promise<PluginVersion>

Get the native Capacitor Updater plugin version (sent to auto update server)

Returns: Promise<PluginVersion>


isAutoUpdateEnabled()

isAutoUpdateEnabled() => Promise<AutoUpdateEnabled>

Get the state of auto update config.

Returns: Promise<AutoUpdateEnabled>


removeAllListeners()

removeAllListeners() => Promise<void>

Remove all listeners for this plugin.

Since: 1.0.0


addListener('download', ...)

addListener(eventName: "download", listenerFunc: (state: DownloadEvent) => void) => Promise<PluginListenerHandle> & PluginListenerHandle

Listen for bundle download event in the App. Fires once a download has started, during downloading and when finished.

Param Type
eventName 'download'
listenerFunc (state: DownloadEvent) => void

Returns: Promise<PluginListenerHandle> & PluginListenerHandle

Since: 2.0.11


addListener('noNeedUpdate', ...)

addListener(eventName: "noNeedUpdate", listenerFunc: (state: NoNeedEvent) => void) => Promise<PluginListenerHandle> & PluginListenerHandle

Listen for no need to update event, useful when you want force check every time the app is launched

Param Type
eventName 'noNeedUpdate'
listenerFunc (state: NoNeedEvent) => void

Returns: Promise<PluginListenerHandle> & PluginListenerHandle

Since: 4.0.0


addListener('updateAvailable', ...)

addListener(eventName: "updateAvailable", listenerFunc: (state: UpdateAvailableEvent) => void) => Promise<PluginListenerHandle> & PluginListenerHandle

Listen for available update event, useful when you want to force check every time the app is launched

Param Type
eventName 'updateAvailable'
listenerFunc (state: UpdateAvailableEvent) => void

Returns: Promise<PluginListenerHandle> & PluginListenerHandle

Since: 4.0.0


addListener('downloadComplete', ...)

addListener(eventName: "downloadComplete", listenerFunc: (state: DownloadCompleteEvent) => void) => Promise<PluginListenerHandle> & PluginListenerHandle

Listen for downloadComplete events.

Param Type
eventName 'downloadComplete'
listenerFunc (state: DownloadCompleteEvent) => void

Returns: Promise<PluginListenerHandle> & PluginListenerHandle

Since: 4.0.0


addListener('majorAvailable', ...)

addListener(eventName: "majorAvailable", listenerFunc: (state: MajorAvailableEvent) => void) => Promise<PluginListenerHandle> & PluginListenerHandle

Listen for Major update event in the App, let you know when major update is blocked by setting disableAutoUpdateBreaking

Param Type
eventName 'majorAvailable'
listenerFunc (state: MajorAvailableEvent) => void

Returns: Promise<PluginListenerHandle> & PluginListenerHandle

Since: 2.3.0


addListener('updateFailed', ...)

addListener(eventName: "updateFailed", listenerFunc: (state: UpdateFailedEvent) => void) => Promise<PluginListenerHandle> & PluginListenerHandle

Listen for update fail event in the App, let you know when update has fail to install at next app start

Param Type
eventName 'updateFailed'
listenerFunc (state: UpdateFailedEvent) => void

Returns: Promise<PluginListenerHandle> & PluginListenerHandle

Since: 2.3.0


addListener('downloadFailed', ...)

addListener(eventName: "downloadFailed", listenerFunc: (state: DownloadFailedEvent) => void) => Promise<PluginListenerHandle> & PluginListenerHandle

Listen for download fail event in the App, let you know when a bundle download has failed

Param Type
eventName 'downloadFailed'
listenerFunc (state: DownloadFailedEvent) => void

Returns: Promise<PluginListenerHandle> & PluginListenerHandle

Since: 4.0.0


addListener('appReloaded', ...)

addListener(eventName: "appReloaded", listenerFunc: () => void) => Promise<PluginListenerHandle> & PluginListenerHandle

Listen for reload event in the App, let you know when reload has happened

Param Type
eventName 'appReloaded'
listenerFunc () => void

Returns: Promise<PluginListenerHandle> & PluginListenerHandle

Since: 4.3.0


addListener('appReady', ...)

addListener(eventName: "appReady", listenerFunc: (state: AppReadyEvent) => void) => Promise<PluginListenerHandle> & PluginListenerHandle

Listen for app ready event in the App, let you know when app is ready to use

Param Type
eventName 'appReady'
listenerFunc (state: AppReadyEvent) => void

Returns: Promise<PluginListenerHandle> & PluginListenerHandle

Since: 5.1.0


Interfaces

AppReadyResult

Prop Type
bundle BundleInfo

BundleInfo

Prop Type
id string
version string
downloaded string
checksum string
status BundleStatus

UpdateUrl

Prop Type
url string

StatsUrl

Prop Type
url string

ChannelUrl

Prop Type
url string

DownloadOptions

Prop Type Description
url string The URL of the bundle zip file (e.g: dist.zip) to be downloaded. (This can be any URL. E.g: Amazon S3, a GitHub tag, any other place you've hosted your bundle.)
version string The version code/name of this bundle/version
sessionKey string
checksum string

BundleId

Prop Type
id string

BundleListResult

Prop Type
bundles BundleInfo[]

ResetOptions

Prop Type
toLastSuccessful boolean

CurrentBundleResult

Prop Type
bundle BundleInfo
native string

MultiDelayConditions

Prop Type
delayConditions DelayCondition[]

DelayCondition

Prop Type Description
kind DelayUntilNext Set up delay conditions in setMultiDelay
value string

LatestVersion

Prop Type Description Since
version string Result of getLatest method 4.0.0
major boolean
message string
sessionKey string
error string
old string
url string

ChannelRes

Prop Type Description Since
status string Current status of set channel 4.7.0
error any
message any

SetChannelOptions

Prop Type
channel string
triggerAutoUpdate boolean

UnsetChannelOptions

Prop Type
triggerAutoUpdate boolean

GetChannelRes

Prop Type Description Since
channel string Current status of get channel 4.8.0
error any
message any
status string
allowSet boolean

SetCustomIdOptions

Prop Type
customId string

BuiltinVersion

Prop Type
version string

DeviceId

Prop Type
deviceId string

PluginVersion

Prop Type
version string

AutoUpdateEnabled

Prop Type
enabled boolean

PluginListenerHandle

Prop Type
remove () => Promise<void>

DownloadEvent

Prop Type Description Since
percent number Current status of download, between 0 and 100. 4.0.0
bundle BundleInfo

NoNeedEvent

Prop Type Description Since
bundle BundleInfo Current status of download, between 0 and 100. 4.0.0

UpdateAvailableEvent

Prop Type Description Since
bundle BundleInfo Current status of download, between 0 and 100. 4.0.0

DownloadCompleteEvent

Prop Type Description Since
bundle BundleInfo Emit when a new update is available. 4.0.0

MajorAvailableEvent

Prop Type Description Since
version string Emit when a new major bundle is available. 4.0.0

UpdateFailedEvent

Prop Type Description Since
bundle BundleInfo Emit when a update failed to install. 4.0.0

DownloadFailedEvent

Prop Type Description Since
version string Emit when a download fail. 4.0.0

AppReadyEvent

Prop Type Description Since
bundle BundleInfo Emitted when the app is ready to use. 5.2.0
status string

Type Aliases

BundleStatus

"success" | "error" | "pending" | "downloading"

DelayUntilNext

"background" | "kill" | "nativeVersion" | "date"

Listen to download events

  import { CapacitorUpdater } from '@capgo/capacitor-updater';

CapacitorUpdater.addListener('download', (info: any) => {
  console.log('download was fired', info.percent);
});

On iOS, Apple don't allow you to show a message when the app is updated, so you can't show a progress bar.

Inspiration

Contributors

jamesyoung1337 Thank you so much for your guidance and support, it was impossible to make this plugin work without you.

capacitor-updater's People

Contributors

actions-user avatar atsuto-kawagoe avatar ayewo avatar bokanechase-digistorm avatar borjalive avatar bosh-code avatar craigzych avatar firen777 avatar github-actions[bot] avatar harriscarney avatar ihmpavel avatar legalmentedev avatar lincolnthree avatar luca-peruzzo avatar ludufre avatar manu2311 avatar matt-expedata avatar meilechwieder avatar menardi avatar merlinchen avatar neo773 avatar pawelplutauek20 avatar pilotkid avatar playaz87 avatar puopg avatar renovate[bot] avatar riderx avatar veneliniliev avatar wcaleniewolny avatar zakuru avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

capacitor-updater's Issues

NullPointer error in boolean comparison on reset()

Call reset() without any value for toAutoUpdate. App will native crash with NPE.

2022-04-24 12:38:03.402 15564-15693/com.maritlabs.topdecked.mtg V/Capacitor/Plugin: To native (Capacitor plugin): callbackId: 70857513, pluginId: CapacitorUpdater, methodName: reset
2022-04-24 12:38:03.402 15564-15693/com.maritlabs.topdecked.mtg V/Capacitor: callback: 70857513, pluginId: CapacitorUpdater, methodName: reset, methodData: {}
2022-04-24 12:38:03.403 15564-15666/com.maritlabs.topdecked.mtg E/Capacitor: Serious error executing plugin
    java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at com.getcapacitor.PluginHandle.invoke(PluginHandle.java:121)
        at com.getcapacitor.Bridge.lambda$callPluginMethod$0$com-getcapacitor-Bridge(Bridge.java:592)
        at com.getcapacitor.Bridge$$ExternalSyntheticLambda5.run(Unknown Source:8)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.os.HandlerThread.run(HandlerThread.java:67)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.Boolean.booleanValue()' on a null object reference
        at ee.forgr.capacitor_updater.CapacitorUpdaterPlugin._reset(CapacitorUpdaterPlugin.java:180)
        at ee.forgr.capacitor_updater.CapacitorUpdaterPlugin.reset(CapacitorUpdaterPlugin.java:196)
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.getcapacitor.PluginHandle.invoke(PluginHandle.java:121) 
        at com.getcapacitor.Bridge.lambda$callPluginMethod$0$com-getcapacitor-Bridge(Bridge.java:592) 
        at com.getcapacitor.Bridge$$ExternalSyntheticLambda5.run(Unknown Source:8) 
        at android.os.Handler.handleCallback(Handler.java:938) 
        at android.os.Handler.dispatchMessage(Handler.java:99) 
        at android.os.Looper.loopOnce(Looper.java:201) 
        at android.os.Looper.loop(Looper.java:288) 
        at android.os.HandlerThread.run(HandlerThread.java:67) 
    
    
    --------- beginning of crash
2022-04-24 12:38:03.405 15564-15666/com.maritlabs.topdecked.mtg E/AndroidRuntime: FATAL EXCEPTION: CapacitorPlugins
    Process: com.maritlabs.topdecked.mtg, PID: 15564
    java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
        at com.getcapacitor.Bridge.lambda$callPluginMethod$0$com-getcapacitor-Bridge(Bridge.java:601)
        at com.getcapacitor.Bridge$$ExternalSyntheticLambda5.run(Unknown Source:8)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.os.HandlerThread.run(HandlerThread.java:67)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at com.getcapacitor.PluginHandle.invoke(PluginHandle.java:121)
        at com.getcapacitor.Bridge.lambda$callPluginMethod$0$com-getcapacitor-Bridge(Bridge.java:592)
        at com.getcapacitor.Bridge$$ExternalSyntheticLambda5.run(Unknown Source:8) 
        at android.os.Handler.handleCallback(Handler.java:938) 
        at android.os.Handler.dispatchMessage(Handler.java:99) 
        at android.os.Looper.loopOnce(Looper.java:201) 
        at android.os.Looper.loop(Looper.java:288) 
        at android.os.HandlerThread.run(HandlerThread.java:67) 
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.Boolean.booleanValue()' on a null object reference
        at ee.forgr.capacitor_updater.CapacitorUpdaterPlugin._reset(CapacitorUpdaterPlugin.java:180)
        at ee.forgr.capacitor_updater.CapacitorUpdaterPlugin.reset(CapacitorUpdaterPlugin.java:196)
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.getcapacitor.PluginHandle.invoke(PluginHandle.java:121) 
        at com.getcapacitor.Bridge.lambda$callPluginMethod$0$com-getcapacitor-Bridge(Bridge.java:592) 
        at com.getcapacitor.Bridge$$ExternalSyntheticLambda5.run(Unknown Source:8) 
        at android.os.Handler.handleCallback(Handler.java:938) 
        at android.os.Handler.dispatchMessage(Handler.java:99) 
        at android.os.Looper.loopOnce(Looper.java:201) 
        at android.os.Looper.loop(Looper.java:288) 
        at android.os.HandlerThread.run(HandlerThread.java:67) 
2022-04-24 12:38:03.409 550-564/system_process W/ActivityTaskManager:   Force finishing activity com.maritlabs.topdecked.mtg/.MainActivity
2022-04-24 12:38:03.459 550-4034/system_process I/ActivityManager: Process com.maritlabs.topdecked.mtg (pid 15564) has died: fg  TOP 

Licencing?

Hi,

This looks like a fantastic library, but the AGPL licence seems a little prescriptive, correct me if I'm wrong, but If I include your npm package I would need to open source the rest of my Ionic mobile application?

Thanks

Neil

Launch paid offers

I’m thinking to have 3 tiers pricing + freemium

  Solo Maker Team
App 1 3 10
Channels per app 2 10 50
Versions history per app 10 100 1000
monthly update per app 2,500 25,000 250,000
Sharing per app No 10 100
Price $14 by month $39 by month $99 by month

Add option to block upgrade for breaking version

if the native app is 1.2.3and the live update is 2.0.0
then the update is skip

In the future it can be cool to let user have a way to continue updating app in past version

like for 1.x.x have way to push in channel fix and feature in backport way

No clear error message when download fails

When zip download fails for some reason, the plugin just outputs the error "Download failed" Without any clear message / error on what went wrong or why download has failed. Not helpful for debugging / investigating the issue

Unable to capacitor sync on iOS

Hello when I tried to run cap sync I get this error. It only happens when this package installed. Is there anyone that have any idea?

✖ Updating iOS native dependencies with pod install - failed!
✖ update ios - failed!
[error] Ignoring ffi-1.15.0 because its extensions are not built. Try: gem pristine ffi --version 1.15.0
        Analyzing dependencies
        objc[25636]: Class AMSupportURLConnectionDelegate is implemented in both /usr/lib/libamsupport.dylib
        (0x1efa1f130) and /Library/Apple/System/Library/PrivateFrameworks/MobileDevice.framework/Versions/A/MobileDevice
        (0x1065202c8). One of the two will be used. Which one is undefined.
        objc[25636]: Class AMSupportURLSession is implemented in both /usr/lib/libamsupport.dylib (0x1efa1f180) and
        /Library/Apple/System/Library/PrivateFrameworks/MobileDevice.framework/Versions/A/MobileDevice (0x106520318).
        One of the two will be used. Which one is undefined.

Add progressive deploy

The goal to this is to allow X% of the user base receive the update

See if that fine for them, and continue to have more, until 100%

Auto-revert on failed install

If the new version of the updated code does not run properly, the system should revert to the previously working version.

Previous plugins that have implemented "code-push updates" provide a feature where developers can specify when an update succeeds. Otherwise the update will be rolled back to the previous working version:


onAppStarted() {
      CapacitorUpdater.notifyApplicationReady(); 

      // If ".notifyApplicationReady()" is not called within ~5s (or a configured timeout) of an update & reload,
      // the update should be considered failed and the previous version should be loaded.
}

Example/Reference: https://github.com/mapiacompany/capacitor-codepush#codepushnotifyapplicationready

Install UX

Love the effort here, will be watching closely.

One thing I'd like to point out if it's not been considered already is the install method. It would be great to be able to configure how the app is updated;

a) Immediate install/switch/restart when the download of the new update is finished
b) Manual through function so developer can choose the best time when they know the user isn't doing something important.
c) Install/restart/switch when the app re-gains focus (e.g with App.addListener('appStateChange')

If you wait until re-focus then it prevents the user being in the middle of something when you randomly restart the app. (doesn't handle the case of them switching apps temporarily to copy/paste or reference something else during a form filling exercise of course).

Apple won't allow you to show an install update prompt so you have to consider the different background approaches.

Will you be exposing events for download started/finished/failed/update available etc?

`notifyAppReady()` should also be required in Manual update mode.

When performing manual updates, there is currently no protection against a failed/bad update.

I think we need the following changes/support:

Methods that return version information should also return an update status (success/error/pending):

  • success -> the update was downloaded, set, and launched successfully: notifyAppReady() was called for this version
  • error -> the update was downloaded and set, but notifyAppReady() was never called
  • pending -> the update was downloaded but never set() and never launched.
export interface VersionInfo {
    version: string;  // version identifier (random numbers returned by native plugin)
    status: 'success' | 'error' | 'pending'; // current status of this version
}

A configurable notifyAppReadyTimeout should be added to capacitor.config.ts (this is optional, but if not provided, the documentation should let the developer know how quickly this needs to be called):

// capacitor.config.ts
...
	"appId": "**.***.**",
	"appName": "Name",
	"plugins": {
		"CapacitorUpdater": {
			"notifyAppReadyTimeout": 10000 // <-- Milliseconds
		}
	}
...

** If notifyAppReady() is not called within the specified (or default value of) notifyAppReadyTimeout, the app should revert to the previous success version, or builtin if none was previously set: **

Let us consider the following workflow:

We perform the first download/set, as the current version is builtin, which can never be rolled back:

const builtin: VersionInfo = await CapacitorUpdater.current();
console.log(builtin);
// { version: 'builtin', status: 'success' }

const downloaded: VersionInfo = await CapacitorUpdater.download({  url: 'https://.../dist.zip' });
console.log(downloaded);
// { version: 'fdc2b4ae1', status: 'pending' }

const set: VersionInfo = await CapacitorUpdater.set('fdc2b4ae1');
console.log(set);
// { version: 'fdc2b4ae1', status: 'pending' } <--- status is still pending because app needs to reload

Now the app app is reloaded, and we call notifyAppReady() which returns the updated version info:

const current: VersionInfo = await CapacitorUpdater.notifyAppReady();
console.log(current);
// { version: 'fdc2b4ae1', status: 'success' }

The native code also stores a previous() version:

const previous: VersionInfo = await CapacitorUpdater.previous();
console.log(previous);
// { version: 'builtin', status: 'success' } <-- this should always return 'builtin' /  'success' if no previous version is set.

Now, for example's sake, we perform another manual update:

const info: VersionInfo = await CapacitorUpdater.download({  url: 'https://.../dist.zip' });
console.log(info);
// { version: 'b9a7dc3e5', status: 'pending' }

const info: VersionInfo = await CapacitorUpdater.set('b9a7dc3e5');
console.log(info);
// { version: 'b9a7dc3e5', status: 'pending' } <--- status is still pending because app needs to reload

Now the app app is reloaded, but notifyAppReady() is NOT called. The native plugin waits for notifyAppReadyTimeout milliseconds, then rolls back to previous version and reloads the application from native code.

The app starts successfully on the previous() version fdc2b4ae1 and notifyAppReady() is called again, but is a no-op for this version since it has already been confirmed successful:

const current: VersionInfo = await CapacitorUpdater.notifyAppReady();
console.log(current);
// { version: 'fdc2b4ae1', status: 'success' }

Listing all available version would return something like the following:

const downloads: VersionInfo[] = await CapacitorUpdater.list();
console.log(downloads);
// [
// { version: 'builtin', status: 'success' }
// { version: 'b9a7dc3e5', status: 'failed' }
// { version: 'fdc2b4ae1', status: 'success' }
// ]

Final note about fallback behavior:
On the rare occurrence that the previous version fdc2b4ae1 ALSO fails to call notifyAppReady() within the specified notifyAppReadyTimeout, the app could be reverted to builtin, but this behavior is probably something that could probably be configurable in capacitor.config.ts:

const current: VersionInfo = await CapacitorUpdater.notifyAppReady();
console.log(current);
// { version: 'builtin', status: 'success' }

	"plugins": {
		"CapacitorUpdater": {
			"allowRollbackToBuiltin": true
		}
	}

CapacitorUpdater.list() does not return correclty serialized result

Hi,

I'm experimenting with your lib, cause I also want to use a simple workflow without AppFlow.
I'm testing with an Android emulator and the latest version of capacitor-updater and having issues with the list() method.
Calling list() from my Angular application and calling JSON.stringify on the result shows that the serialization seems not to work as expected.

CapacitorUpdater.list().then(x => console.log(JSON.stringify(x)));
// output: {"versions":"[/data/user/0/de.tcwolfach/files/versions/SmuZ3lRen7, /data/user/0/de.tcwolfach/files/versions/gy1sGvaZ5f, /data/user/0/de.tcwolfach/files/versions/ey6GwoMTy8, /data/user/0/de.tcwolfach/files/versions/nlppoSqiMB]"}

As you can see the versions-Property is not a an array of strings. Instead it's a string property.

I'm not a Java expert, but it looks like the resulting string is not a correctly serialized string, it's the result of calling toString() on an ArrayList.
Changing this code in node_modules folder:

public void list(PluginCall call) {
        ArrayList<String> res = implementation.list();
        JSObject ret = new JSObject();
        ret.put("versions", res);
        call.resolve(ret);
    }

to this code

public void list(PluginCall call) {
        ArrayList<String> res = implementation.list();
        JSObject ret = new JSObject();
        ret.put("versions", new JSArray(res));
        call.resolve(ret);
    }

fixed the problem.
I only checked the issue for Android, maybe the same problem occurs in iOS.

Make autoUpdate setting simpler

auto-update not need app id to be set since it’s same as app
Channel could be set by default as “production” and override with config

Then URL should be set by default since that the main usage.

To allow user to enable auto-update a new config should appear.

This will result in simple first time config. just upload app and make it public

Explanatoin

Hi!

How will this work? if I set the update url is mywebsite.com/dist.zip, will download the zip every time app goes to background? how will it know if the zip has updates?

Add versionCode header in auto update mode on android

On Android currently the request sent to the server to check for auto updates is including header cap_version_build which has the value of versionName value from android project. Since versionName is free text it might be useful to introduce a new header containing versionCode value from android project since versionCode is unique while versionName can free text.

Need download/update progress

Hi, thank u for awesome project

I know Just package has asyncProgressHandler for HTTP requests. Maybe that can provide progress event for us.

resim
https://justhttp.github.io/

I thought there might be people like me who want to show the current progress as a percentage to users.

Best regards

Error: "CapacitorUpdater" plugin is not implemented on android

core.js:6210 ERROR Error: Uncaught (in promise): Error: "CapacitorUpdater" plugin is not implemented on android
Error: "CapacitorUpdater" plugin is not implemented on android

My function for update is :

  async updateHybrid() {
    var self = this;
    const version = await CapacitorUpdater.download({
      url: 'http://92.168.1.25/downloadhybridversion',
    })
    await CapacitorUpdater.set(version)
  }

my versiın is "capacitor-updater": "^1.0.22"

Disable sending usage statistics

Hi,

since version 1.3.0 usage stats are sent to cappgo. The documentation says that I can change this behaviour to send usage stats to a custom server. But I don't want to send any usage stats. Is there a possibility to disable sending usage stats at all? From some tests I think configuring an empty string as statsUrl does the job, but I'm not sure whether this is the correct way/intended behaviour because the docs don't say anythin about this.

What should be in dist.zip?

Hi there, thanks for sharing this project, I'm really looking forward to using it! Sorry if the answer to this is already out there and I've just missed it!

I'm just trying to give it a test with Android but I'm just wondering what I should be including in the update zip file?

I am using svelte, so I had assumed I should just zip up the contents of the build folder when running npm run build

I am attempting to apply the update as follows, I'm not catching any exceptions but the app doesn't appear to update.

const updateNow = async () => {
        try {
            const version = await CapacitorUpdater.download({
                url: 'http://192.168.0.39:45456/api/v1/mockreceiver/build.zip',
            })
            await SplashScreen.show()
            await CapacitorUpdater.set(version)
            await SplashScreen.hide()
        }catch (e){
            console.log(e);
        }

    }

Thanks again

Oh also, should I be adding anything to onCreate() in MainActivity for this plugin? I'm currently assuming not.

Help needed

Hello !
Since recent ionic crazy pricing trying to find solution :)

I am new to capacitor only cordova used in the past .

testing on iOS

async update() { const update = await CapacitorUpdater.updateApp({ url: 'https://myftpurl/upate.zip', }); console.log(update); }

gives me {done: false}

(upate.zip is my www zipped)

Beta channel system

Allow user to click in the app somewhere to try the beta channel of the app.

Delete doesn't seem to be working

I love this project. I've got it setup and updating properly, but I can't clean up old versions.

const {versions} = await CapacitorUpdater.list();
const {current} = await CapacitorUpdater.current();
for (const v of versions) {  
    if (v !== current) {  
        CapacitorUpdater.delete({version: v})  
            .then(() => console.log('deleted version', v));  
    }
}

This gives an error:

Error: Uncaught (in promise): Error: Delete failed, version don't exist
    Error: Delete failed, version don't exist
        at Object.cap.fromNative (:414)

Am I using the API wrong or is this a bug?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.