Почему добавляет только 1000 товаров?

370
13 августа 2017, 05:30
<?php
namespace app\forms;
use bundle\jurl\jURL;
use app\classes\Vk,
    app\classes\Shttp,
    app\classes\ThreadPoolPlus;
use std, gui, framework, app;

class MainForm extends AbstractForm
{
    private $vk, $stack;
    /**
     * @event button_account.click-Left 
     */
    function doButton_accountClickLeft(UXMouseEvent $e = null)
    {    
        $this->panel1->enabled = false;
        (new Thread(function()
        {
            $user = $this->vk->query('account.getProfileInfo');
            uiLater(function() use ($user)
            {
                if($user)
                {
                    $name = $user['response']['first_name'].' '.$user['response']['last_name'];
                    $this->log('Авторизовался под "'.$name.'"');
                    $this->username->text = $name;
                    $this->button_get_products->enabled = true;
                    $this->label_products_parsed->text = 0;
                    $this->label_products_parsed_status->text = 'Ожидание';
                    $this->panel1->enabled = false;
                    $this->panel2->enabled = true;
                }else{
                    $this->panel1->enabled = true;
                }
            });
        }))->start();
    }
    /**
     * @event showing 
     */
    function doShowing(UXWindowEvent $e = null)
    {    
        $actions = [
            'invalid_login_password' => function()
            {
                $this->log('Неверный логин или пароль');
                $this->panel1->enabled = true;
                $this->panel2->enabled = $this->panel3->enabled = false;
            },
            'enter_login_password' => function()
            {
                $this->log('Введите логин и пароль');
                $this->panel1->enabled = true;
            },
            'account_blocked' => function()
            {
                $this->log('Страница заблокирована');
                $this->panel1->enabled = true;
                $this->panel2->enabled = $this->panel3->enabled = false;
            },
            'account_f2a_activation' => function()
            {
                $this->log('Отключите двухфакторную авторизацию или ваша страница не активирована');
                $this->panel1->enabled = true;
                $this->panel2->enabled = $this->panel3->enabled = false;
            },
            'captcha' => function($method = null)
            {
                $this->log('Получена капча'.(($method !== null) ? ' при выполнении метода '.$method : '').'. Решаем...');
            },
            'captchaAuth' => function()
            {
                $this->log('Получена капча при авторизации. Решаем...');
            },
        ];
        $this->vk = new Vk;
        $this->vk->setErrorHandler(function($data, $params, $method, $vk) use ($actions)
        {
            if($data['error_code'] == 14){ //Требуется ввод капчи.
                uiLater(function() use ($method)
                {
                    $actions['captcha']($method);
                });
                return [Vk::ACTION_RETRY, ['captcha_sid' => $data['captcha_sid'], 'captcha_key' => AntiCaptcha::vk($config['anticaptcha'], $oauth['captcha_img'])]];
                sleep(30);
                return Vk::ACTION_RETRY;
            }elseif($data['error_code'] == 17){ //Нужна валидация
                $login = $this->edit_login->text;
                $link = $data['redirect_uri'];
                if(str::startsWith($login, '+') and !str::startsWith($link, 'https://m.vk.com/activation'))
                {
                    $page = Shttp::get($link);
                    if(str::pos($page, '<a href="/login?act=blocked') == -1 and
                       str::pos($page, '<div class="service_msg service_msg_warning">') == -1){
                        $page = str::replace(str::replace(str::replace($page, "&amp;", "&"), "\n", null), '&nbsp;', null);
                        $hash = self::parse_between($page, '<form method="post" action="/login.php?act=security_check&to=&hash=', '&api_hash=');
                        $api_hash = self::parse_between($page, '<form method="post" action="/login.php?act=security_check&to=&hash='.$hash.'&api_hash=', '">');
                        $number = self::parse_between_count($page, '<span class="field_prefix">', '</span>', 2);
                        $code = str::sub($login, str::length($number[0]), str::length($login)-str::length($number[1]));
                        Shttp::get('https://m.vk.com/login.php?'.self::http_build_query(['act' => 'security_check', 'to' => '', 'hash' => $hash, 'api_hash' => $api_hash, 'code' => $code]));
                        return Vk::ACTION_RETRY;
                    }else{
                        uiLater($actions['account_blocked']);
                        return;
                    }
                }else{
                    uiLater($actions['account_f2a_activation']);
                    return;
                }
            }elseif($data['error_code'] == 6){ //Слишком много запросов в секунду.
                sleep(1);
                return Vk::ACTION_RETRY;
            }elseif($data['error_code'] == 5 or ($data['error_code'] == 15 and $data['error_msg'] <> 'Access denied') or $data['error_code'] == 113){ //Если токен не валидный / Нет доступа по данному методу.
                $login = $this->edit_login->text;
                $password = $this->edit_password->text;
                if(empty($login) or empty($password))
                {
                    uiLater($actions['enter_login_password']);
                    return;
                }
                $captcha = ['sid' => null, 'key' => null];
                while(true)
                {
                    sleep(1);
                    $oauth = Shttp::get('https://oauth.vk.com/token?'.self::http_build_query(['grant_type' => 'password', 'client_id' => 2274003, 'client_secret' => 'hHbZxrka2uZ6jB1inYsH', 'username' => $login, 'password' => $password, 'captcha_sid' => $captcha['sid'], 'captcha_key' => $captcha['key']]));
                    $oauth = json_decode($oauth, true);
                    if($oauth['error'] == 'need_captcha') #Капча при атворизации.
                    {
                        uiLater($actions['captchaAuth']);
                        if($this->captcha_key->length <> 32)
                        {
                            $this->log('Требуется ключ капчи');
                        }
                        $captcha['sid'] = $oauth['captcha_sid'];
                        $captcha['key'] = AntiCaptcha::vk($this->captcha_key->text, $oauth['captcha_img']);
                        continue;
                    }elseif($oauth['error'] == 'need_validation') #Нужна валидация
                    {
                        $login = $bot['login'];
                        $link = $oauth['redirect_uri'];
                        if(str::startsWith($login, '+') and !str::startsWith($link, 'https://m.vk.com/activation') and $oauth['validation_type'] <> '2fa_sms' and $oauth['validation_type'] <> '2fa_app')
                        {
                            $page = Shttp::get($link);
                            if(str::pos($page, '<a href="/login?act=blocked') == -1)
                            {
                                $page = str::replace(str::replace(str::replace($page, "&amp;", "&"), "\n", null), '&nbsp;', null);
                                $hash = self::parse_between($page, '<form method="post" action="/login.php?act=security_check&to=&hash=', '&api_hash=');
                                $api_hash = self::parse_between($page, '<form method="post" action="/login.php?act=security_check&to=&hash='.$hash.'&api_hash=', '">');
                                $number = self::parse_between_count($page, '<span class="field_prefix">', '</span>', 2);
                                $code = str::sub($login, str::length($number[0]), str::length($login)-str::length($number[1]));
                                Shttp::get('https://m.vk.com/login.php?'.self::http_build_query(['act' => 'security_check', 'to' => '', 'hash' => $hash, 'api_hash' => $api_hash, 'code' => $code]));
                                continue;
                            }else{
                                uiLater($actions['account_blocked']);
                            }
                        }else{
                            uiLater($actions['account_f2a_activation']);
                        }
                        continue;
                    }elseif($oauth['error'] == 'invalid_client'){
                        uiLater($actions['invalid_login_password']);
                        return;
                    }elseif(isset($oauth['access_token'])){
                        $vk->setAccessToken($oauth['access_token']);
                        return Vk::ACTION_RETRY;
                    }
                }
            }
        });
    }
    /**
     * @event button_place_products.click-Left 
     */
    function doButton_place_productsClickLeft(UXMouseEvent $e = null)
    {    
        $stack = $this->stack;
        $pool = new ThreadPoolPlus(100, $stack->count());
        $vk = $this->vk;
        $id = $this->edit_group_id_to->text;
        $unavailable = $this->checkbox_unavailable->selected;
        mkdir('./temp');
        $this->panel2->enabled = $this->panel3->enabled = false;
        (new Thread(function() use ($id, $stack, $pool, $vk, $unavailable)
        {
            while(($data = $stack->pop()) !== null)
                $pool->execute(function() use ($id, $data, $vk, $unavailable)
                {
                    $photo_ids = [];
                    foreach($data['photo_urls'] AS $key => $photos)
                    {
                        file_put_contents($filename=fs::abs('./temp/'.str::uuid().'.png'), file_get_contents($photos));
                        $temp = $vk->upload(Vk::UPLOAD_MARKET_PHOTO, $filename, $id);
                        if($key == 0)
                            $photo = $temp;
                        else
                            $photo_ids[] = $temp;
                        unlink($filename);
                    }
                    $vk->query('market.add', [
                        'owner_id' => $id,
                        'name' => $data['name'],
                        'description' => $data['description'],
                        'category_id' => $data['category_id'],
                        'price' => substr($data['price'], 0, -2),
                        'deleted' => $unavailable,
                        'main_photo_id' => $photo,
                        'photo_ids' => implode(',', $photo_ids)
                    ]);
                });
            while(!$pool->isDone())
            {
                Thread::sleep(1000);
                uiLater(function() use ($pool)
                {
                    $this->label_products_placed->text = $pool->doneCount();
                    $this->label_products_placed_status->text = round($pool->doneCount(true), 2).'%';
                });
            }
            uiLater(function()
            {
                $this->label_products_placed_status->text = 'Завершено';
                $this->panel2->enabled = $this->panel3->enabled = true;
            });
        }))->start();
    }
    /**
     * @event button_get_products.click-Left 
     */
    function doButton_get_productsClickLeft(UXMouseEvent $e = null)
    {    
        $this->panel2->enabled = $this->panel3->enabled = false;
        $id = $this->edit_group_id_from->text;
        (new Thread(function() use ($id)
        {
            $vk = $this->vk;
            $result = $vk->query('market.get', [
                'owner_id' => $id,
                'count' => 0,
                'v' => 5.67
            ]);
            if($result['response'])
            {
                if($result['response']['count'] > 0)
                {
                    $count = ceil($result['response']['count']/200);
                    $this->stack = $stack = new SharedStack;
                    for($i=1;$i<=$count;$i++)
                    {
                        $products = $vk->query('market.get', [
                            'owner_id' => $id,
                            'count' => 200,
                            'extended' => true,
                            'offset' => ($i-1)*200,
                            'v' => 5.67
                        ]);
                        foreach($products['response']['items'] AS $item)
                        {
                            $urls = [];
                            foreach($item['photos'] AS $photo)
                                foreach(array_reverse($photo, true) AS $ak => $av)
                                {
                                    if(strpos($ak, 'photo_') === 0)
                                    {
                                        $urls[] = $av;
                                        break;
                                    }
                                }
                            $stack->push([
                                'name' => $item['title'],
                                'description' => $item['description'],
                                'category_id' => $item['category']['id'],
                                'price' => $item['price']['amount'],
                                'photo_urls' => $urls
                            ]);
                        }
                        $percent = round($i*100/$count, 2);
                        uiLater(function() use ($percent, $stack)
                        {
                            $this->label_products_parsed->text = $stack->count();
                            $this->label_products_parsed_status->text = $percent.'%';
                        });
                    }
                    uiLater(function()
                    {
                        $this->label_products_parsed_status->text = 'Завершено';
                        $this->panel2->enabled = true;
                        $this->panel3->enabled = true;
                    });
                }else{
                    uiLater(function()
                    {
                        $this->button_get_products->enabled = true;
                        $this->edit_group_id_from->enabled = true;
                        $this->panel2->enabled = true;
                        $this->panel3->enabled = true;
                        $this->log('Товаров нет');
                    });
                }
            }
        }))->start();
    }
    /**
     * @event close 
     */
    function doClose(UXWindowEvent $e = null)
    {    
        exit;
    }
    public function log($msg)
    {
        $this->log->items->add($msg);
    }
    private static function http_build_query($a,$b='',$c=0){
    if (!is_array($a)) return $a;
            foreach ($a as $k=>$v){
                if($c){
                    if( is_numeric($k) ){
                        $k=$b."[]";
                    }
                    else{
                        $k=$b."[$k]";
                    }
                }
                else{   
                    if (is_int($k)){
                        $k=$b.$k;
                    }
                }
                if (is_array($v)||is_object($v)){
                    $r[] = self::http_build_query($v,$k,1);
                        continue;
                }
                $r[] = urlencode($k) . "=" . urlencode($v);
            }
            return implode("&",$r);
        }
    private static function parse_between($str, $first, $second)
    {
        $pos1 = str::pos($str, $first);
        $pos2 = str::pos($str, $second, $pos1);
        return str::sub($str, $pos1+str::length($first), $pos2);
    }
    private static function parse_between_count($str, $first, $second, $count = 1)
    {
        $start = 0;
        $data = [];
        for($i=0;$i<$count;$i++)
        {
            $pos1 = str::pos($str, $first, $start);
            $pos2 = str::pos($str, $second, $pos1);
            $pos3 = $pos1+str::length($first);
            $data[] = str::sub($str, $pos3, $pos2);
            $start += $pos3;
        }
        return $data;
    }
}
READ ALSO
Проверка наличия интернет соединения

Проверка наличия интернет соединения

Как можно проверить наличие интернет соединения через java

323
Чистый Java web-app БЕЗ web.xml на Servlet

Чистый Java web-app БЕЗ web.xml на Servlet

Доброго времени всем! Не так давно начал изучать Java и сейчас хочу написать учебный проект на чистом Java, без Spring и тд

202
Как сделать такой эффект у слайдера?

Как сделать такой эффект у слайдера?

Как сделать такой эффект у слайдера? Чтобы картинка увеличивалась до момента пока не переключится ан следующий слайд Пример themesprofteamsolutions

193
аналог htmllint для razor

аналог htmllint для razor

У нас в фирме проект на ASPNET MVC 4

187