blib/lib/Yandex/Disk.pm untested

filter: Statementstmt 0.0% 0 / 263 Branchbran 0.0% 0 / 76 Conditioncond 0.0% 0 / 49 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 31 Podpod 0.0% 0 / 18 totaltotal 0.0% 0 / 437 CC 39 SCAR 31.1
CC
39
Cov
0%
uploadFile
72.0
emptyTrash
42.0
createFolder
30.0
CRAP 22.4
1 package Yandex::Disk;
2  
3 use 5.008001;
4 use strict;
5 use warnings;
6 use utf8;
7 use Yandex::Disk::Public;
8 use Carp qw/croak carp/;
9 use LWP::UserAgent;
10 use JSON::XS;
11 use File::Basename;
12 use URI::Escape;
13 use Encode;
14 use IO::Socket::SSL;
15 use Term::Sk;
16  
17 our $VERSION = '0.05';
18  
19 my $WAIT_RETRY = 20;
20 #my $BUFF_SIZE = 8192;
21 my $BUFF_SIZE = 81;
22  
23 sub new {
24 my $class = shift;
25 my %opt = @_;
26 my $self = {};
27 $self->{token} = $opt{-token} || croak "Specify -token param";
28  
29 my $ua = LWP::UserAgent->new;
30 $ua->agent("Yandex::Disk perl module");
31 $ua->default_header('Accept' => 'application/json');
32 $ua->default_header('Content-Type' => 'application/json');
33 $ua->default_header('Connection' => 'keep-alive');
34 $ua->default_header('Authorization' => 'OAuth ' . $self->{token});
35 $self->{ua} = $ua;
36 $self->{public_info} = {};
37 return bless $self, $class;
38 }
39  
40  
41 sub getDiskInfo {
42 my $self = shift;
43 my $url = 'https://cloud-api.yandex.net/v1/disk/';
44 my $res = $self->__request($url, "GET");
45 if ($res->is_success) {
46 return __fromJson($res->decoded_content);
47 }
48 else {
49 croak "Cant execute request to $url: " . $res->status_line;
50 }
51 }
52  
53 sub uploadFile {
54 my $self = shift;
55 my %opt = @_;
56 my $overwrite = $opt{-overwrite};
57 my $file = $opt{-file} || croak "Specify -file param";
58 my $remote_path = $opt{-remote_path} || croak "Specify -remote_path param";
59 my $show_progress_bar = $opt{-show_progress_bar};
60  
61 $overwrite = 1 if not defined $overwrite;
62  
63 if (not -f $file) {
64 croak "File $file not exists";
65 }
66  
67 $overwrite = $overwrite ? 'true' : 'false';
68  
69 #Delete end slash
70 $remote_path =~ s/^\/|\/$//g;
71 $remote_path = sprintf("/%s/%s", $remote_path, basename($file));
72  
73 my $param = "?path=" . uri_escape($remote_path) . "&overwrite=$overwrite";
74 my $res = $self->__request('https://cloud-api.yandex.net/v1/disk/resources/upload' . $param, "GET");
75 my $url_to_upload;
76 my $code = $res->code;
77 if ($code eq '409') {
78 croak "Folder $remote_path not exists";
79 }
80 elsif ($code eq '200') {
81 $url_to_upload = __fromJson($res->decoded_content)->{href};
82 }
83 else {
84 croak "Cant uploadFile: " . $res->status_line;
85 }
86
87 # Progress bar if need
88 my $term;
89 if ($show_progress_bar) {
90 $term = __prepareProgressBar(-s $file);
91 }
92  
93 my $upl_code = __upload_file($url_to_upload, $file, $term);
94  
95 if ($upl_code ne '201') {
96 croak "Cant upload file. Code: $code";
97 }
98 return 1;
99 }
100  
101 sub createFolder {
102 my $self = shift;
103 my %opt = @_;
104 my $path = $opt{-path} || croak "Specify -path param";
105 my $recursive = $opt{-recursive};
106  
107 if ($recursive) {
108 my @half_path;
109 for my $l_path (split /\//, $path) {
110 push @half_path, $l_path;
111 $self->createFolder( -path => join('/', @half_path) );
112 }
113 }
114  
115 my $res = $self->__request('https://cloud-api.yandex.net/v1/disk/resources/?path=' . uri_escape($path), "PUT");
116 my $code = $res->code;
117 if ($code eq '409') {
118 #Папка или существует или не создана родительская папка
119 my $json_res = __fromJson($res->decoded_content);
120 if ($json_res->{error} eq 'DiskPathPointsToExistentDirectoryError') {
121 return 1;
122 }
123 croak $json_res->{description};
124 }
125 elsif ($code ne '201') {
126 croak "Cant create folder $path. Error: " . $res->status_line;
127 }
128  
129 return 1;
130 }
131  
132 sub deleteResource {
133 my $self = shift;
134 my %opt = @_;
135 my $path = $opt{-path} || croak "Specify -path param";
136 my $wait = $opt{-wait};
137 my $permanently = $opt{-permanently};
138  
139 $permanently = $permanently ? 'true' : 'false';
140  
141 my $res = $self->__request('https://cloud-api.yandex.net/v1/disk/resources?path=' . uri_escape($path) . "&permanently=$permanently", "DELETE");
142 my $code = $res->code;
143 if ($code eq '204') {
144 #Free folder
145 return 1;
146 }
147 elsif ($code eq '202') {
148 if ($wait) {
149 my $href = __fromJson($res->decoded_content)->{href};
150 $self->__waitResponse($href, $WAIT_RETRY) or croak "Timeout to wait response. Try increase $WAIT_RETRY variable";
151 }
152 return 1;
153 }
154 else {
155 croak "Cant delete $path. Error: " . $res->status_line;
156 }
157 }
158  
159 sub downloadFile {
160 my $self = shift;
161 my %opt = @_;
162 my $path = $opt{-path} || croak "Specify -path param";
163 my $file = $opt{-file} || croak "Specify -file param";
164 my $show_progress_bar = $opt{-show_progress_bar};
165  
166 my $res = $self->__request('https://cloud-api.yandex.net/v1/disk/resources/download?path=' . uri_escape($path), "GET");
167 my $code = $res->code;
168 if ($code ne '200') {
169 croak "Error on request file $path: " . $res->status_line;
170 }
171  
172 my $download_url = __fromJson($res->decoded_content)->{href};
173  
174 my $term;
175 if ($show_progress_bar) {
176 if ($download_url =~ /[&?]fsize=(\d+)/) {
177 $term = __prepareProgressBar($1);
178 }
179 else {
180 carp "Can't get size of downloaded file. Progress bar will disabled.";
181 }
182 }
183  
184 $self->__download($download_url, $file, $term);
185 return 1;
186 }
187  
188 sub emptyTrash {
189 my $self = shift;
190 my %opt = @_;
191 my $path = $opt{-path} || '';
192 my $wait = $opt{-wait};
193  
194 my $param = $path ? '?path=' . uri_escape($path) : '';
195 my $res = $self->__request('https://cloud-api.yandex.net/v1/disk/trash/resources/' . $path, 'DELETE');
196 my $code = $res->code;
197 if ($code eq '204') {
198 return 1;
199 }
200 elsif ($code eq '202') {
201 if ($wait) {
202 my $href = __fromJson($res->decoded_content)->{href};
203 $self->__waitResponse($href, $WAIT_RETRY) or croak "Timeout to wait response. Try increase $WAIT_RETRY variable";
204 }
205 return 1;
206 }
207 else {
208 $path = "by path $path" if $path;
209 croak "Cant empty trash$path. Error: " . $res->status_line;
210 }
211 }
212  
213 sub listFiles {
214 my $self = shift;
215 my %opt = @_;
216 my $path = $opt{-path} || croak "Specify -path param";
217 my $limit = $opt{-limit} || 999999;
218 my $offset = $opt{-offset};
219 $offset = 0 if not $offset;
220  
221 my $param = '?path=' . uri_escape($path) . "&limit=$limit&offset=$offset&fields=_embedded.items";
222 my $res = $self->__request('https://cloud-api.yandex.net/v1/disk/resources' . $param, 'GET');
223 my $code = $res->code;
224 if ($code ne '200') {
225 croak "Error on listFiles. Error: " . $res->status_line;
226 }
227 my $json_res = __fromJson($res->decoded_content);
228  
229 return $json_res->{_embedded}->{items};
230 }
231  
232 sub listAllFiles {
233 my $self = shift;
234 my %opt = @_;
235 my $limit = $opt{-limit} || 999999;
236 my $media_type = $opt{-media_type};
237 my $offset = $opt{-offset};
238 $offset = 0 if not $offset;
239  
240 my $param = "?limit=$limit&offset=$offset";
241 $param .= '&media_type=' . $media_type if $media_type;
242  
243 my $res = $self->__request('https://cloud-api.yandex.net/v1/disk/resources/files' . $param, 'GET');
244 my $code = $res->code;
245 if ($code ne '200') {
246 croak "Error on listFiles. Error: " . $res->status_line;
247 }
248 my $json_res = __fromJson($res->decoded_content);
249  
250 return $json_res->{items};
251 }
252  
253 sub lastUploadedFiles {
254 my $self = shift;
255 my %opt = @_;
256 my $limit = $opt{-limit} || 999999;
257 my $media_type = $opt{-media_type};
258  
259 my $param = "?limit=$limit";
260 $param .= '&media_type=' . $media_type if $media_type;
261  
262 my $res = $self->__request('https://cloud-api.yandex.net/v1/disk/resources/last-uploaded' . $param, 'GET');
263 my $code = $res->code;
264 if ($code ne '200') {
265 croak "Error on listFiles. Error: " . $res->status_line;
266 }
267 my $json_res = __fromJson($res->decoded_content);
268  
269 return $json_res->{items};
270 }
271  
272  
273 sub public {
274 my $self = shift;
275 return Yandex::Disk::Public->new( -token => $self->{token} );
276 }
277  
278 sub __download {
279 my ($self, $url, $fname, $term) = @_;
280 my $ua = $self->{ua};
281  
282 open my $FL, ">$fname" or croak "Cant open $fname to write $!";
283 binmode $FL;
284 my $res = $ua->get($url, ':read_size_hint' => $BUFF_SIZE, ':content_cb' =>
285 sub {
286 print $FL $_[0];
287 $term->up($BUFF_SIZE) if $term;
288 }
289 );
290 close $FL;
291 $term->close if $term;
292  
293 if ($res->code eq '200') {
294 return 1;
295 }
296 croak "Cant download file $url to $fname. Error: " . $res->status_line;
297 }
298  
299 sub __waitResponse {
300 #Дожидается ответа о статусе операции
301 my ($self, $url, $retry) = @_;
302  
303 while ($retry > 0) {
304 my $res = $self->__request($url, "GET");
305 my $code = $res->code;
306 if ($code eq '200' && __fromJson($res->decoded_content)->{status} eq 'success') {
307 return 1;
308 }
309 sleep 1;
310 $retry--;
311 }
312 return;
313 }
314  
315  
316 sub __upload_file {
317 #Buffered chunked upload file
318 my ($url, $file, $term) = @_;
319  
320 my $u1 = URI->new($url);
321  
322 # $IO::Socket::SSL::DEBUG = 3;
323 my $host = $u1->host;
324 my $port = $u1->port;
325 my $path = $u1->path;
326  
327 my $sock = IO::Socket::SSL->new(
328 PeerAddr => $host,
329 PeerPort => $port,
330 Proto => 'tcp',
331 ) or croak "Cant connect to $host:$port";
332 binmode $sock;
333 $sock->autoflush(1);
334  
335 $sock->print("PUT $path HTTP/1.1\n");
336 $sock->print("HOST: $host\n");
337 $sock->print("Connection: close\n");
338 $sock->print("Content-Type: application/json\n");
339 $sock->print("Transfer-Encoding: chunked\n");
340 $sock->print("\n");
341  
342 open my $FH, "<$file" or croak "Cant open $file $!";
343 binmode $FH;
344 my $filebuf;
345 while (my $bytes = read($FH, $filebuf, $BUFF_SIZE)) {
346 my $hex = sprintf("%X", $bytes);
347 $sock->print($hex) or croak "Cant print to socket";
348 $sock->print("\r\n") or croak "Cant print to socket";
349  
350 $sock->print($filebuf) or croak "Cant print to socket";
351 $sock->print("\r\n") or croak "Cant print to socket";
352  
353 $term->up($BUFF_SIZE) if $term;
354 }
355 close $FH;
356  
357 $sock->print("0\r\n") or croak "Cant print to socket";
358 $sock->print("\r\n") or croak "Cant print to socket";
359
360 my @answer = $sock->getlines();
361 $sock->close();
362  
363 $term->close if $term;
364  
365 my ($code) = $answer[0] =~ /(\d{3})/;
366  
367 return $code;
368 }
369  
370  
371 sub __request {
372 my ($self, $url, $type) = @_;
373  
374 my $ua = $self->{ua};
375 my $req = HTTP::Request->new($type => $url);
376 my $res = $ua->request($req);
377
378 return $res;
379 }
380  
381 sub __fromJson {
382 my $string = ref($_[0]) ? $_[1] : $_[0];
383 my $res = JSON::XS::decode_json($string);
384 return $res;
385 }
386  
387 sub __prepareProgressBar {
388 my ($file_size) = @_;
389 my $format = '%2d Elapsed: %8t %21b %4p %2d (%8c of %11m bytes)';
390 my $target = $file_size;
391 my $term = Term::Sk->new($format, {
392 freq => 'd',
393 base => 0,
394 target => $target,
395 pdisp => '!',
396 }
397 );
398 return $term;
399 }
400  
401  
402 sub errstr {
403 return shift->{errstr};
404 }
405
406 1;
407  
408 __END__