@@ -34,6 +34,20 @@ class Upgrade {
3434 */
3535 private $ sync ;
3636
37+ /**
38+ * The cron frequency to ensure that the queue is progressing.
39+ *
40+ * @var int
41+ */
42+ protected $ cron_frequency ;
43+
44+ /**
45+ * The cron offset since the last update.
46+ *
47+ * @var int
48+ */
49+ protected $ cron_start_offset ;
50+
3751 /**
3852 * Filter constructor.
3953 *
@@ -42,6 +56,10 @@ class Upgrade {
4256 public function __construct ( \Cloudinary \Media $ media ) {
4357 $ this ->media = $ media ;
4458 $ this ->sync = $ media ->plugin ->components ['sync ' ];
59+
60+ $ this ->cron_frequency = apply_filters ( 'cloudinary_cron_frequency ' , 600 );
61+ $ this ->cron_start_offset = apply_filters ( 'cloudinary_cron_start_offset ' , 60 );
62+
4563 $ this ->setup_hooks ();
4664 }
4765
@@ -167,13 +185,44 @@ function ( $val ) use ( $media ) {
167185 update_post_meta ( $ attachment_id , Sync::META_KEYS ['downloading ' ], true );
168186 delete_post_meta ( $ attachment_id , Sync::META_KEYS ['syncing ' ] );
169187
188+ if ( ! wp_next_scheduled ( 'cloudinary_resume_upgrade ' ) ) {
189+ wp_schedule_single_event ( time () + $ this ->cron_frequency , 'cloudinary_resume_upgrade ' );
190+ }
191+
170192 if ( ! defined ( 'DOING_BULK_SYNC ' ) ) {
171193 $ this ->sync ->managers ['upload ' ]->add_to_sync ( $ attachment_id ); // Auto sync if upgrading outside of bulk sync.
172194 }
173195
174196 return $ public_id ;
175197 }
176198
199+ /**
200+ * Maybe resume the upgrading assets.
201+ * This is a fallback mechanism to resume the upgrade when it stops unexpectedly.
202+ *
203+ * @return void
204+ */
205+ public function maybe_resume_upgrade () {
206+ global $ wpdb ;
207+
208+ $ assets = $ wpdb ->get_col ( // phpcs:ignore WordPress.DB.DirectDatabaseQuery
209+ $ wpdb ->prepare (
210+ "SELECT post_id
211+ FROM $ wpdb ->postmeta
212+ WHERE meta_key = %s " ,
213+ Sync::META_KEYS ['downloading ' ]
214+ )
215+ );
216+
217+ if ( ! empty ( $ assets ) ) {
218+ wp_schedule_single_event ( time () + $ this ->cron_frequency , 'cloudinary_resume_upgrade ' );
219+
220+ foreach ( $ assets as $ asset ) {
221+ $ this ->sync ->managers ['upload ' ]->add_to_sync ( $ asset );
222+ }
223+ }
224+ }
225+
177226 /**
178227 * Setup hooks for the filters.
179228 */
@@ -193,5 +242,7 @@ public function setup_hooks() {
193242 }
194243 } );
195244 }
245+
246+ add_action ( 'cloudinary_resume_upgrade ' , array ( $ this , 'maybe_resume_upgrade ' ) );
196247 }
197248}
0 commit comments