PluginProbe ʕ •ᴥ•ʔ
Robin Image Optimizer – Unlimited Image Optimization, WebP & AVIF / 2.0.7
Robin Image Optimizer – Unlimited Image Optimization, WebP & AVIF v2.0.7
2.0.7 2.0.6 2.0.5 trunk 1.3.7 1.4.0 1.4.1 1.4.2 1.4.6 1.5.0 1.5.3 1.5.6 1.5.8 1.6.5 1.6.6 1.6.9 1.7.0 1.7.4 1.8.1 1.8.2 1.9.0 2.0.0 2.0.1 2.0.2 2.0.3 2.0.4
robin-image-optimizer / admin / assets / js / calculate-attachments.js
robin-image-optimizer / admin / assets / js Last commit date
Chart.min.js 7 months ago bulk-conversion.js 7 months ago bulk-optimization.js 7 months ago calculate-attachments.js 1 year ago index.php 3 years ago meta-migrations.js 3 years ago modals.js 7 months ago notices.js 4 months ago restore-backup.js 7 months ago settings-premium.js 7 months ago single-optimization.js 7 months ago statistic.js 7 months ago sweetalert2.js 3 years ago wrio-license-manager.js 7 months ago
calculate-attachments.js
169 lines
1 (function ($) {
2 class BulkOptimization {
3 constructor(ajaxUrl, i18n, settings) {
4 if (!i18n || !settings) {
5 console.error('[Error]: Required global variables are missing.');
6 return;
7 }
8 this.ajaxUrl = ajaxUrl;
9 this.i18n = i18n;
10 this.settings = settings;
11
12 this.totalImages = 0;
13 this.countAttachments = 0;
14 this.countThumbs = 0;
15 }
16
17 /**
18 * Initializes the bulk optimization process by chaining multiple calculations.
19 * If any error occurs during the process, it will be caught and handled.
20 */
21 init() {
22 this.calculateTotalAttachments()
23 .then(() => this.calculateTotalThumbs())
24 .then(() => this.calculateTotalImages())
25 .catch((error) => this.throwError(error));
26 }
27
28 /**
29 * Sends an AJAX POST request to the server.
30 *
31 * @param {string} action - The AJAX action to trigger on the server.
32 * @param {Object} additionalData - Additional data to send with the request.
33 * @returns {Promise<Object>} - A promise that resolves with the response data from the server.
34 * @throws Will throw an error if the response is invalid or the request fails.
35 */
36 async postAjax(action, additionalData = {}) {
37 const data = {
38 action: action,
39 _wpnonce: this.settings.optimization_nonce,
40 ...additionalData,
41 };
42
43 try {
44 const response = await $.post(this.ajaxUrl, data);
45
46 if (!response || !response.success || !response.data) {
47 console.error('[Error]: Invalid AJAX response.', response);
48 if (response?.data?.error) {
49 console.error(response.data.error);
50 }
51
52 throw new Error(this.i18n.ajaxError || 'AJAX Error Occurred');
53 }
54
55 return response.data;
56 } catch (xhr) {
57 console.error('[Error]: AJAX Request Failed.', xhr);
58 throw xhr;
59 }
60 }
61
62 /**
63 * Calculates the total number of attachments.
64 *
65 * This method sends an AJAX request to the server to fetch the total
66 * number of media attachments and updates the corresponding UI element with the result.
67 *
68 * @returns {Promise<void>} - A promise that resolves when the calculation is complete.
69 */
70 async calculateTotalAttachments() {
71 try {
72 const data = await this.postAjax('wbcr-rio-calculate-total-attachments');
73
74 this.countAttachments = data.found_attachments;
75
76 $('#wio-stat-totals__originals')
77 .removeClass('wio-stat-totals__loading')
78 .text(data.found_attachments);
79 } catch (error) {
80 this.throwError(error);
81 }
82 }
83
84 /**
85 * Updates the total count of images by summing attachments and thumbnails.
86 *
87 * This method does not send an AJAX request. Instead, it calculates the total
88 * number of found images and updates the corresponding UI element.
89 */
90 async calculateTotalImages() {
91 this.totalImages = this.countAttachments + this.countThumbs;
92 $('#wio-stat-totals__totals')
93 .removeClass('wio-stat-totals__loading')
94 .text(this.totalImages);
95 }
96
97 /**
98 * Calculates the total number of thumbnails in a paginated manner.
99 *
100 * This method sends multiple AJAX requests based on the `offset` returned
101 * from the server. It stops once the `done` parameter is `true` and accumulates
102 * the total number of thumbnails found during the process.
103 *
104 * @returns {Promise<void>} - A promise that resolves when all requests are complete.
105 * @throws Will throw an error if `next_offset` is missing or undefined in the response.
106 */
107 async calculateTotalThumbs() {
108 try {
109 let offset = 0;
110 let totalThumbs = 0;
111
112 // Sequentially fetch thumbnail counts in batches
113 while (true) {
114 const data = await this.postAjax('wbcr-rio-calculate-total-thumbs', { offset });
115
116 // Update the total thumbnail counter
117 totalThumbs = data.found_thumbs;
118
119 // Update the thumbnails count in the UI
120 $('#wio-stat-totals__thumbnails')
121 .removeClass('wio-stat-totals__loading')
122 .text(totalThumbs);
123
124 // Break the loop if the server indicates the process is complete
125 if (data.done) {
126 break;
127 }
128
129 // Update the offset for the next request
130 offset = data.next_offset;
131
132 // Validate the offset to avoid infinite loops
133 if (offset === undefined || offset === null) {
134 console.error('[Error]: Missing offset in server response.');
135 throw new Error('Invalid server response: offset is undefined.');
136 }
137 }
138
139 this.countThumbs = totalThumbs;
140
141 } catch (error) {
142 this.throwError(error);
143 }
144 }
145
146 /**
147 * Handles errors by logging them to the console and displaying an alert.
148 *
149 * This method provides a standardized way to handle any unexpected errors
150 * that occur during the execution of the bulk optimization process.
151 *
152 * @param {Error|string} error - The error message or object to handle.
153 */
154 throwError(error) {
155 console.error('[Error]:', error);
156 alert(this.i18n.generalError || 'An error occurred. Please try again.');
157 }
158 }
159
160 // Initialize the bulk optimization process on document ready
161 $(document).ready(() => {
162 const bulkOptimization = new BulkOptimization(
163 ajaxurl, // The URL for WordPress AJAX requests
164 window.wrio_l18n_bulk_page, // Localization data for the UI
165 window.wrio_settings_bulk_page // Settings data for the optimization
166 );
167 bulkOptimization.init();
168 });
169 })(jQuery);