Skip to content
This repository has been archived by the owner on Nov 25, 2018. It is now read-only.

Commit

Permalink
1.0.1
Browse files Browse the repository at this point in the history
  • Loading branch information
TsSaltan committed Oct 1, 2016
1 parent dd2df49 commit c7ad78d
Show file tree
Hide file tree
Showing 6 changed files with 117 additions and 69 deletions.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@

### Changelog
````
--- 1.0.1 ---
[Fix] Ошибка, возникающая если перед скачиванием файлов был редирект
[Fix] Заголовки не выводятся в файл при setReturnHeaders(true)
[Fix] Ошибка при установке/удалении пакета, если отсутствовал файл .bootstrap
--- 1.0 ---
[Add] Компонент загрузчик
[Add] Многопоточная загрузка
Expand Down
Binary file modified build/dn-jurl-bundle.dnbundle
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
<properties group="out" title="Вывод" sort="2000">
<property code="fieldUrl" name="Ссылка для загрузки [Поле ввода]" editor="object" />
<property code="progressBar" name="Прогресс загрузки [Прогресс-бар]" editor="object" />
<property code="labelProgress" name="Прогресс загрузки [Текст]" editor="object" />
<property code="labelProgress" name="Процент загрузки [Текст]" editor="object" />
<property code="labelSpeed" name="Скорость загрузки [Текст]" editor="object" />
<property code="labelThreads" name="Количество потоков [Текст]" editor="object" />
<property code="labelDownloaded" name="Объем скачанных данных [Tекст]" editor="object" />
Expand Down
33 changes: 26 additions & 7 deletions src/develnext/bundle/jurl/jURLBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,19 @@ public function onRemove(Project $project, AbstractBundle $owner = null)
}
}

public function onPreCompile($project, $env, $log = null)
{
$this->installCode();
parent::onPreCompile($project, $env, $log);
// todo remove it!
}

/**
* Чтоб подтянулись curl_* функции, объявим их
* в файле .bootstrap до старта приложения
*/

private $code = '<?php' . "\n" . 'new \cURL; // Generated by jURL bundle',
private $code = 'new \cURL; // Generated by jURL bundle',
$bootstrap;

private function setBootstrap(Project $project){
Expand All @@ -60,22 +67,34 @@ private function setBootstrap(Project $project){

private function installCode(){
$code = $this->getBootstrap();
$code = Str::Replace($code, '<?php', $this->code);
$this->putBootstrap($code);
if($code !== false and !str::contains($code, $this->code)){
$code = Str::Replace($code, '<?php', '<?php' . "\n" . $this->code);
$this->putBootstrap($code);
}
}

private function removeCode(){
$code = $this->getBootstrap();
$code = Str::Replace($code, $this->code, '<?php');
$this->putBootstrap($code);
if($code !== false and str::contains($code, $this->code)){
$code = Str::Replace($code, "\n" . $this->code, '');
$this->putBootstrap($code);
}
}

private function getBootstrap(){
return Stream::getContents($this->bootstrap);
try{
return Stream::getContents($this->bootstrap);
} catch (\php\io\IOException $e){
return false;
}
}

private function putBootstrap($content){
return Stream::putContents($this->bootstrap, $content);
try{
Stream::putContents($this->bootstrap, $content);
} catch (\php\io\IOException $e){

}
}


Expand Down
113 changes: 67 additions & 46 deletions src/vendor/develnext.bundle.jurl.jURLBundle/bundle/jurl/jURL.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@

class jURL
{
public $version = '0.6.1';

const CRLF = "\r\n",
const
VERSION = '1.0.1.0',
CRLF = "\r\n",
LOG = false;

private $opts = [], // Параметры подключения
Expand Down Expand Up @@ -124,7 +124,6 @@ public function exec($byRedirect = false){
$cookies = NULL;
$this->boundary = Str::random(90);
$answer = false;
$useBuffer = !(isset($this->opts['outputFile']) and $this->opts['outputFile'] !== false);
$isMultipart = (is_array($this->opts['postFiles']) and (sizeof($this->opts['postFiles']) > 0));

// Если был редирект, ничего не сбрасываем
Expand Down Expand Up @@ -267,19 +266,15 @@ public function exec($byRedirect = false){
// Добавление заголовков в вывод
if(isset($this->opts['returnHeaders']) and $this->opts['returnHeaders'] === true){
// Если в foreach засунуть $headers, после цикла все данные куда-то исчезнут >:(
$hs = [];
//foreach($this->callConnectionFunc('getHeaderFields') as $k=>$v){
foreach($this->responseHeaders as $hk=>$hv){
foreach($hv as $kk => $s){
$hs[] = $hk. ((strlen($hk) > 0) ? ': ' : '') . $s;
$headString = $hk. ((strlen($hk) > 0) ? ': ' : '') . $s;
$this->writeBufferStream($headString . self::CRLF);
//$this->getBufferStream()->write($headString . self::CRLF);
}
}

if(sizeof($hs) > 0) {
$h = implode(self::CRLF, $hs);
$h.= self::CRLF . self::CRLF;
$this->buffer->write($h);
}
$this->writeBufferStream(self::CRLF);
}

/**
Expand All @@ -303,19 +298,15 @@ public function exec($byRedirect = false){

if($this->opts['returnBody'] === true) $this->getInputData();

if($useBuffer and $this->buffer->length() > 0){
if($this->isMemoryBuffer() and $this->buffer->length() > 0){
$this->buffer->seek(0);
$answer = $this->buffer->readFully();
}
else $answer = NULL;

$this->buffer->close();

if($this->charset != 'UTF-8'){
$answer = Str::Decode($answer, $this->charset);
}

// $this->log(['URLConnection' => $this->URLConnection]);

$this->connectionInfo = [
'url' => (object) $url,
Expand Down Expand Up @@ -373,12 +364,16 @@ public function __destruct(){
* --RU--
* Закрыть соединение
*/
public function destroyConnection(){
private function destroyConnection(){
$this->log('destroyConnection');
if($this->URLConnection instanceof URLConnection) $this->URLConnection->disconnect();
}

private function closeThreads(){
$this->log('closeThreads');
if($this->thread instanceof Thread) $this->thread->interrupt();
if($this->opts['inputFile'] instanceof FileStream) $this->opts['inputFile']->close();
if($this->opts['outputFile'] instanceof FileStream) $this->opts['outputFile']->close();
if($this->URLConnection instanceof URLConnection) $this->URLConnection->disconnect();
if($this->buffer instanceof MemoryStream) $this->buffer->close();
}

Expand All @@ -387,7 +382,8 @@ public function destroyConnection(){
* Остановить выполнение запроса
*/
public function close(){
return $this->destroyConnection();
$this->destroyConnection();
$this->closeThreads();
}

/**
Expand Down Expand Up @@ -522,6 +518,11 @@ public function setCookieFile($file){
public function setHttpHeaders($headers){
$this->opts['httpHeader'] = $headers;
}

// alias //
public function setHttpHeader($headers){
$this->opts['httpHeader'] = $headers;
}

/**
* --RU--
Expand Down Expand Up @@ -575,11 +576,11 @@ public function setReturnBody($return){
* @param string $file - path/to/file
*/
public function setOutputFile($file){
$this->opts['outputFile'] = $file;
$this->opts['outputFile'] = ($file === false || $file === null) ? $file : FileStream::of($file, 'w+');
}
// alias //
public function setFileStream($file){
$this->opts['outputFile'] = $file;
$this->setOutputFile($file);
}

/**
Expand Down Expand Up @@ -733,14 +734,12 @@ private function detectCharset($header){
}

private function createConnection(){
//Устанавливаем прокси-соединение
// Устанавливаем прокси-соединение
if(isset($this->opts['proxy']) and $this->opts['proxy'] !== false){
$ex = Str::Split($this->opts['proxy'], ':');
$proxy = new Proxy($this->opts['proxyType'], $ex[0], $ex[1]);
}

// $this->log(['Options' => $this->opts]);

$this->URLConnection = URLConnection::Create($this->opts['url'], $proxy);
$this->URLConnection->doInput = true;
$this->URLConnection->doOutput = ($this->opts['body'] !== false || $this->opts['postData'] !== false || $this->opts['postFiles'] !== false);
Expand All @@ -755,7 +754,7 @@ private function createConnection(){
private function resetBufferParams(){
$this->requestLength = 0;
$this->responseLength = 0;
$this->buffer = new MemoryStream;
if(!($this->buffer instanceof MemoryStream)) $this->buffer = new MemoryStream;
}

/*
Expand All @@ -779,10 +778,7 @@ private function loadToBuffer($input){
$data = $input->read($this->opts['bufferSize']);
$this->responseLength += Str::Length($data);

if($this->opts['outputFile'] instanceof FileStream){
$this->opts['outputFile']->write($data);
}
else $this->buffer->write($data);
$this->writeBufferStream($data);

$this->callProgressFunction($this->getConnectionParam('contentLength'), $this->responseLength, $this->responseLength, $this->responseLength);
}
Expand All @@ -791,23 +787,13 @@ private function loadToBuffer($input){
* Читает входной поток данных
*/
private function getInputData(){
$this->resetBufferParams();

if(isset($this->opts['outputFile']) and $this->opts['outputFile'] !== false){
$this->opts['outputFile'] = ($this->opts['outputFile'] instanceof FileStream) ? $this->opts['outputFile'] : FileStream::of($this->opts['outputFile'], 'w+');
}
else $this->opts['outputFile'] = false;

$in = $this->callConnectionFunc('getInputStream');
$this->loadToBuffer($in);

while(!$in->eof()){
$this->loadToBuffer($in);
}
$this->callProgressFunction($this->getConnectionParam('contentLength'), $this->getConnectionParam('contentLength'), $this->responseLength, $this->responseLength);


return $this->buffer;
}

/**
Expand Down Expand Up @@ -854,8 +840,6 @@ private function sendMultipartData($key, $source, $fileName = NULL, $totalSize =
* Отправляет файлы в выходной поток данных
*/
private function sendOutputData($files){
$this->resetBufferParams();

// Для начала узнаем общий размер файлов для progressFunction
$totalSize = 0;
if($this->issetProgressFunction()){
Expand All @@ -867,15 +851,26 @@ private function sendOutputData($files){
}

foreach ($files as $fKey => $file) {

$fileName = File::of($file)->getName();
$fStream = new FileStream($file, 'r+');

$this->sendMultipartData($fKey, $fStream, $fileName, $totalSize);
}
}

private function isMemoryBuffer(){
return !(isset($this->opts['outputFile']) and $this->opts['outputFile'] instanceof FileStream);
}

private function writeBufferStream($data){
$this->getBufferStream()->write($data);
}

private function getBufferStream(){
if($this->isMemoryBuffer()){
return $this->buffer;
}


return $this->opts['outputFile'];
}

/*
Expand Down Expand Up @@ -1029,7 +1024,7 @@ private function parseCookies($cookies, $defaultDomain){
* Генерирует дефолтный User-Agent
*/
private function genUserAgent(){
return 'jURL/'.$this->version.' (Java/'. System::getProperty('java.version') .'; '. System::getProperty('os.name') .'; DevelNext)';
return 'jURL/'. self::VERSION .' (Java/'. System::getProperty('java.version') .'; '. System::getProperty('os.name') .'; DevelNext)';
}

/**
Expand Down Expand Up @@ -1057,4 +1052,30 @@ private function issetProgressFunction(){
private function Log($data){
if(self::LOG) Logger::Debug('[jURL] ' . var_export($data, true));
}

public static function requreVersion($version){
$c = explode('.', self::VERSION);
$r = explode('.', $version);

for($i = 0; $i < 4; ++$i){
$c[$i] = str::format('%03d', intval(isset($c[$i])?$c[$i]:0));
$r[$i] = str::format('%03d', intval(isset($r[$i])?$r[$i]:0));
}

$current = intval(implode('', $c));
$require = intval(implode('', $r));

if($require > $current) {
if(
uiConfirm("Нужно обновить пакет расширений jURL! \nНеобходимая версия: $version \nУстановлен пакет версии: " . self::VERSION. "\n\n Завершить приложение и обновиться?")
) {
browse('https://github.com/TsSaltan/DevelNext-jURL/releases/latest');
app()->shutdown();
}
return false;
}


return true;
}
}
Loading

0 comments on commit c7ad78d

Please sign in to comment.