Plugin Directory

Changeset 3130894


Ignore:
Timestamp:
08/05/2024 08:43:50 AM (20 months ago)
Author:
immolare
Message:
  • Improvment of limitation to treats parallels queries
  • If credits are < balance, serve n images = maximum of balance
Location:
artist-image-generator/trunk
Files:
6 edited

Legend:

Unmodified
Added
Removed
  • artist-image-generator/trunk/README.txt

    r3130568 r3130894  
    55Tested up to: 6.6
    66Requires PHP: 7.4
    7 Stable tag: v1.1.8
     7Stable tag: v1.1.8.1
    88License: GPLv3
    99License URI: https://www.gnu.org/licenses/gpl-3.0.html
     
    2828
    2929Setting up a credit balance is simple. You just need to add a WooCommerce product (e.g., credit packs: 10 - 50 - 150). This works without any other WooCommerce extensions.
    30 
    31 https://www.youtube.com/watch?v=aFjRa8dpM0A
    3230
    3331When a user purchases a number of credits, they have a credit balance on their account to use the generators. When they run out of credits, a link to your product is suggested so they can purchase more.
     
    258256
    259257== Changelog ==
     2581.1.8.1 - 2024-08-04
     259- Improvment of limitation to treats parallels queries
     260- If credits are < balance, serve n images = maximum of balance
     261
    2602621.1.8 - 2024-08-04
    261263- Credit Balance feature
  • artist-image-generator/trunk/artist-image-generator.php

    r3130506 r3130894  
    1717 * Plugin URI:        https://artist-image-generator.com/
    1818 * Description:       Illustrate posts with Ai images (DALL·E). Text-to-Image, variation, editing. Public image generator & Ai avatars by topics.
    19  * Version:           1.1.8
     19 * Version:           1.1.8.1
    2020 * Author:            Pierre Viéville
    2121 * Author URI:        https://www.pierrevieville.fr
     
    3636 * Rename this for your plugin and update it as you release new versions.
    3737 */
    38 define( 'ARTIST_IMAGE_GENERATOR_VERSION', '1.1.8' );
     38define( 'ARTIST_IMAGE_GENERATOR_VERSION', '1.1.8.1' );
    3939
    4040/**
  • artist-image-generator/trunk/includes/class-artist-image-generator-constant.php

    r3130506 r3130894  
    6161    const REFILL_WC_PRODUCT_META_KEY = 'credits';
    6262    const REFILL_USER_META_KEY = '_aig_balance';
     63    const REFILL_USER_META_KEY_VERSION = '_aig_balance_version';
    6364    const REFILL_WC_ORDER_RECHARGED = '_aig_credits_recharged';
    6465}
  • artist-image-generator/trunk/public/class-artist-image-generator-credits-balance-manager.php

    r3130506 r3130894  
    7575    }
    7676
    77     public static function update_user_credits($user_id, $credits) {
     77    public static function update_user_credits($user_id, $credits) {   
     78        $current_version = get_user_meta($user_id, Constants::REFILL_USER_META_KEY_VERSION, true);
     79   
     80        if ($current_version === '') {
     81            // The version number doesn't exist yet for the user, so create it
     82            $current_version = 0;
     83            add_user_meta($user_id, Constants::REFILL_USER_META_KEY_VERSION, $current_version);
     84        }
     85   
    7886        $user_credits = self::get_user_balance($user_id);
    7987        $new_balance = $user_credits + $credits;
    80 
    81         update_user_meta($user_id, Constants::REFILL_USER_META_KEY, $new_balance, $user_credits);
    82 
     88        $new_version = $current_version + 1;
     89       
     90        $updated = update_user_meta($user_id, Constants::REFILL_USER_META_KEY, $new_balance, $user_credits);
     91        $version_updated = update_user_meta($user_id, Constants::REFILL_USER_META_KEY_VERSION, $new_version, $current_version);
     92   
    8393        return self::get_user_balance($user_id);
    8494    }
     
    8696    public static function get_user_balance($user_id) {
    8797        $user_credits = get_user_meta($user_id, Constants::REFILL_USER_META_KEY, true);
    88         if (!$user_credits) {
     98        if (!$user_credits || $user_credits < 0) {
    8999            $user_credits = 0;
    90100        }
     101
    91102        return $user_credits;
    92103    }
  • artist-image-generator/trunk/public/class-artist-image-generator-public.php

    r3130506 r3130894  
    7373    }
    7474
    75     private function get_credits_to_remove($post_data)
    76     {
     75    private function get_request_number($post_data)
     76    {
     77        // DALLE 3 model has a fixed number of requests of 1 (parrallel requests)
     78        if ($post_data['model'] === Constants::DALL_E_MODEL_3) {
     79            return 1;
     80        }
     81
     82        // DALLE 2 model needs to get the number of requests from the post data
    7783        return (int)$post_data['n'];
    7884    }
    7985
    80     private function check_and_update_user_limit($post_data)
     86    private function check_and_update_user_limit(&$post_data)
    8187    {
    8288        // If Constants::REFILL_PRODUCT_ID is set, handle the limit with the refill system
     
    8490            $user_id = get_current_user_id();
    8591            $current_balance = $this->credits_balance_manager::get_user_balance($user_id);
    86             $n_credits = $this->get_credits_to_remove($post_data);
    87             $balance = $current_balance - $n_credits;
    88 
    89             if ($balance < 1) {
     92
     93            $requests = $this->get_request_number($post_data);
     94            $balance = $current_balance - $requests;
     95
     96            if ($balance < 0) {
     97                $requests = $current_balance;
     98                $balance = $current_balance - $requests;
     99                $post_data['n'] = $requests;
     100            }
     101
     102            if ($balance < 0 || $requests <= 0) {
    90103                $refill_product_id = $this->options[Constants::REFILL_PRODUCT_ID];
    91104                $product_url = get_permalink($refill_product_id);
     
    94107                wp_send_json(array(
    95108                    'error' => array(
    96                         'type' => self::ERROR_TYPE_LIMIT_EXCEEDED, 
     109                        'type' => self::ERROR_TYPE_LIMIT_EXCEEDED,
    97110                        'message' => $error_message,
    98                         'product_url' => $product_url
     111                        'product_url' => $product_url,
     112                        'user_balance' => $current_balance
    99113                    )
    100114                ));
     
    109123                $user_ip = $_SERVER['REMOTE_ADDR'];
    110124                $user_identifier = $user_id ? 'artist_image_generator_user_' . $form_id . '_' . $user_id : 'artist_image_generator_ip_' . $form_id . '_' . $user_ip;
    111                 $requests = get_transient($user_identifier);
     125                $current_balance = get_transient($user_identifier);
    112126                $duration = isset($post_data['user_limit_duration']) && $post_data['user_limit_duration'] > 0 ? (int)$post_data['user_limit_duration'] : 0;
    113127                $expiration = get_option('_transient_timeout_' . $user_identifier);
    114128
    115                 if ($requests === false || ($duration > 0 && time() > $expiration)) {
    116                     $requests = 0;
    117                     set_transient($user_identifier, $requests, $duration);
     129                if ($current_balance === false || ($duration > 0 && time() > $expiration)) {
     130                    $current_balance = 0;
     131                    set_transient($user_identifier, $current_balance, $duration);
    118132                }
    119133
    120                 $requests++;
    121 
    122                 if ((int)$post_data['user_limit'] < $requests) {
     134                $requests = $this->get_request_number($post_data);
     135                $balance = $current_balance + $requests;
     136
     137                if ((int)$post_data['user_limit'] < $balance) {
     138                    $requests = (int)$post_data['user_limit'] - $current_balance;
     139                    $balance = $current_balance + $requests;
     140                    $post_data['n'] = $requests;
     141                }
     142
     143                if ((int)$post_data['user_limit'] < $balance || $requests <= 0) {
    123144                    $duration_msg = $duration > 0 ? sprintf(__(' Please try again in %d seconds.', 'artist-image-generator'), $expiration - time()) : '';
    124145                    $error_message = esc_html__('You have reached the limit of requests.', 'artist-image-generator') . $duration_msg;
    125146                    wp_send_json(array(
    126147                        'error' => array(
    127                             'type' => self::ERROR_TYPE_LIMIT_EXCEEDED, 
     148                            'type' => self::ERROR_TYPE_LIMIT_EXCEEDED,
    128149                            'message' => $error_message
    129150                        )
     
    132153                }
    133154
    134                 set_transient($user_identifier, $requests, $duration);
    135             }
    136         }
    137     }
     155                set_transient($user_identifier, $balance, $duration);
     156            }
     157        }
     158
     159        // Ensure that $post_data['n'] is not less than 1
     160        if ($post_data['n'] < 1) {
     161            $post_data['n'] = 1;
     162        }
     163    }
     164
    138165
    139166    public function generate_image()
     
    167194            $data = $dalle->prepare_data($images ?? [], $error ?? [], $post_data);
    168195
     196            $n_credits = $this->get_request_number($post_data);
     197
     198            /*$dummyImages = [];
     199           
     200            for ($i = 0; $i < $n_credits; $i++) {
     201                $dummyImages[] = [
     202                    'url' => 'https://artist-image-generator.com/wp-content/uploads/img-rck1GT0eGIYLu4oAXFEMqsPT.png'
     203                ];
     204            }
     205
     206            $data = [
     207                'error' => [],
     208                'images' => $dummyImages,
     209                'model_input' => $post_data['model'],
     210                'prompt_input' => 'Painting of a bird, including following criterias:',
     211                'size_input' => '1024x1024',
     212                'n_input' => $n_credits,
     213                'quality_input' => '',
     214                'style_input' => ''
     215            ];*/
     216           
    169217            if (!empty($this->options[Constants::REFILL_PRODUCT_ID]) && is_user_logged_in()) {
    170218                $user_id = get_current_user_id();
    171                 $n_credits = $this->get_credits_to_remove($post_data);
    172219                $newBalance = $this->credits_balance_manager::update_user_credits($user_id, -$n_credits);
     220                $data['user_credits_used'] = $n_credits;
    173221                $data['user_balance'] = $newBalance;
    174222            }
  • artist-image-generator/trunk/public/js/artist-image-generator-public.js

    r3130506 r3130894  
    9292                let requests = [];
    9393                if (data.model === 'dall-e-3' && data.n > 1) {
    94                     requests = Array.from({ length: data.n }, () => {
    95                         return fetch(ajaxurl, {
    96                             method: "POST",
    97                             body: new URLSearchParams(data),
    98                             headers: {
    99                                 "Content-Type": "application/x-www-form-urlencoded",
    100                                 "Cache-Control": "no-cache",
    101                             },
    102                         }).then((response) => response.json());
    103                     });
     94                  requests = Array.from({ length: data.n }, () => data);
    10495                } else {
    105                     requests.push(fetch(ajaxurl, {
    106                         method: "POST",
    107                         body: new URLSearchParams(data),
    108                         headers: {
    109                             "Content-Type": "application/x-www-form-urlencoded",
    110                             "Cache-Control": "no-cache",
    111                         },
    112                     }).then((response) => response.json()));
    113                 }
     96                  requests.push(data);
     97                }
     98               
     99                let responses = [];
     100                for (let i = 0; i < requests.length; i++) {
     101                  const requestData = requests[i];
     102                  const response = await fetch(ajaxurl, {
     103                    method: "POST",
     104                    body: new URLSearchParams(requestData),
     105                    headers: {
     106                      "Content-Type": "application/x-www-form-urlencoded",
     107                      "Cache-Control": "no-cache",
     108                    },
     109                  });
     110           
     111                  const json = await response.json();
     112                  responses.push(json);
     113               
     114                  // Add a timeout between each request
     115                  if (i < requests.length - 1) {
     116                    await new Promise(resolve => setTimeout(resolve, 200));
     117                  }
     118                }
     119
    114120
    115121                try {
    116                     const responses = await Promise.all(requests);
    117122                    // Merge all responses
    118123                    const mergedResponse = responses.reduce((acc, response) => {
     
    135140                            acc.images = acc.images.concat(response.images);
    136141                        }
    137                         if (response.user_balance) {
    138                             acc.user_balances.push(response.user_balance);
     142                        if (response.user_balance !== undefined) {
     143                            acc.user_balances.push(String(response.user_balance));
    139144                        }
    140145                        return acc;
     
    207212                    if (mergedResponse.errors && mergedResponse.errors.length > 0) {
    208213                        const errorContainer = form.querySelector(".aig-errors");
    209                         errorContainer.innerHTML = mergedResponse.errors.join('<br>');
    210                     }
    211 
    212                     const userBalanceValue = form.querySelector('.aig-credits-balance-value');
    213                     if (userBalanceValue) {
     214                        const uniqueErrors = [...new Set(mergedResponse.errors)];
     215                        errorContainer.innerHTML = uniqueErrors.join('<br>');
     216                    }
     217
     218                    const userBalanceValueElements = document.querySelectorAll('.aig-credits-balance-value');
     219                    if (userBalanceValueElements.length > 0) {
     220                        //console.log(mergedResponse.user_balances);
    214221                        if (Array.isArray(mergedResponse.user_balances) && mergedResponse.user_balances.length > 0) {
    215222                            const numericBalances = mergedResponse.user_balances.map(Number);
     223                           
    216224                            const minBalance = Math.min(...numericBalances);
    217                             userBalanceValue.innerHTML = minBalance;
     225                            userBalanceValueElements.forEach(element => {
     226                                element.innerHTML = minBalance;
     227                            });
    218228                        } else {
    219                             userBalanceValue.innerHTML = 0;
     229                            userBalanceValueElements.forEach(element => {
     230                                element.innerHTML = 0;
     231                            });
    220232                        }
    221233                    }
Note: See TracChangeset for help on using the changeset viewer.