В статье рассмотрено работа с сервисами Яндекс диска с помощью Delphi и библиотеки Synapse, исходники будут написаны в Delphi XE6.
Во второй части рассматривается уже сама работа с Янднес диском
Доброго времени суток уважаемый читатель. Прошло уже более полугода как я написал первую часть, вторая часть собственно была готова еще тогда но начались какие-то проблемы и неприятности… но не будем блудословить и начнем заниматься делом т.е. разбором работы с яндекс диском используя Delphi и библиотеки senapse. Сразу хочу выразить огромную признательность сайту и , а также разделу справка яндекс диска, именно блягадоря я и написал маленькое тестовое приложение работающие с яндекс диском, а дальше была написанна утилита резервного копирования БД 1С на яндекс диск.
Сначала я выложу весь код модуля содержащего процедуры и функции для работы с яндекс диском, а потом я попытаюсь объяснить назначение процедур и функций данного модуля, и в самом конце я прекреплю пример откомпелированое приложения для работы с яндекс диском.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 |
unit webDAV; interface uses Classes, SysUtils, httpsend, synacode, ssl_openssl, synautil, httpapp, XMLDoc, XMLIntf, Generics.Collections, Winapi.Windows, Winapi.Messages, Vcl.ComCtrls; const cWebDAVServer = 'https://webdav.yandex.ru/'; type TWDResource = class private FHref : string; FStatusCode : integer; FContentLength: int64; FCreationDate : TDateTime; FLastmodified : TDateTime; FDisplayName : string; FContentType : string; FCollection : Boolean; public property StatusCode : integer read FStatusCode; property ContentLength: int64 read FContentLength; property CreationDate : TDateTime read FCreationDate; property Lastmodified : TDateTime read FLastmodified; property DisplayName : string read FDisplayName; property ContentType : string read FContentType; property Href: string read FHref; property Collection : Boolean read FCollection; end; TWDResourceList = class(TList<TWDResource>) public constructor Create; destructor Destroy;override; procedure Clear; end; type TWebDAVSend = class private FHTTP : THTTPSend; FToken: AnsiString; FPassword: string; FLogin: string; FCurDir : string; FResources: TWDResourceList; procedure SetLogin(const Value: string); procedure SetPassword(const Value: string); procedure SetToken; procedure ParseResources(const AXMLStr: string); function GetRequestURL(const Element: string; EncodePath:boolean=True): string; function EncodeUTF8URI(const URI: string): string; function PROPFIND(Depth: integer; const Element: String; errToDisplay : boolean = false): string; public constructor Create; destructor Destroy; override; property Login: string read FLogin write SetLogin; property Password: string read FPassword write SetPassword; property Resources: TWDResourceList read FResources; property CurDir : string read FCurDir; function GetData(DAVDir : string; errToDisplay : boolean = false): TListview; function PUT(const ElementHref: string; aFileName: string; errToDisplay : boolean = false): boolean; function MKCOL(const ElementPath: string; errToDisplay : boolean = false): boolean; function Get(const ElementHref: string; var Response:TStream; errToDisplay : boolean = false): boolean; function DAVDelete(const ElementPath: string; errToDisplay : boolean = false): boolean; end; //================================================================== implementation uses DateUtils; resourcestring rsPropfindError = 'Ошибка при выполнении запроса PROPFIND'; procedure SaveErrFile(errStr : string); var ErrFile : string; f : TextFile; begin ErrFile := ExtractFileDir(ExtractFilePath(ParamStr(0))) + '\error.log'; AssignFile(f, ErrFile); if not FileExists(ErrFile) then begin Rewrite(f); CloseFile(f); end; Append(f); Writeln(f, DateToStr(SysUtils.Date) + ' ' + TimeToStr(SysUtils.Time) + ' - ' + errStr ); Flush(f); CloseFile(f); end; function GetFileSize(FileName: string): Int64; var F: TMemoryStream; begin try F:=TMemoryStream.Create; F.LoadFromFile(FileName); Result:=F.Size; finally F.Free; end; end; function TzSpecificLocalTimeToSystemTime(lpTimeZoneInformation: PTimeZoneInformation; var lpLocalTime, lpUniversalTime: TSystemTime): BOOL; stdcall; external kernel32 name 'TzSpecificLocalTimeToSystemTime'; {$EXTERNALSYM TzSpecificLocalTimeToSystemTime} function SystemTimeToUTC(Sys: TDateTime): TDateTime; var TimeZoneInf: _TIME_ZONE_INFORMATION; SysTime, LocalTime: TSystemTime; begin if GetTimeZoneInformation(TimeZoneInf) < $FFFFFFFF then begin DatetimetoSystemTime(Sys, SysTime); if TzSpecificLocalTimeToSystemTime(@TimeZoneInf, SysTime, LocalTime) then Result := SystemTimeToDateTime(LocalTime) else Result := Sys; end else Result := Sys; end; function UTCToSystemTime(UTC: TDateTime): TDateTime; var TimeZoneInf: _TIME_ZONE_INFORMATION; UTCTime, LocalTime: TSystemTime; begin if GetTimeZoneInformation(TimeZoneInf) < $FFFFFFFF then begin DatetimetoSystemTime(UTC, UTCTime); if SystemTimeToTzSpecificLocalTime(@TimeZoneInf, UTCTime, LocalTime) then begin Result := SystemTimeToDateTime(LocalTime); end else Result := UTC; end else Result := UTC; end; function ISODateTime2UTC(const AValue: string; ADateOnly: Boolean = False): TDateTime; var I, Len: Integer; DD, MM, YY: Word; HH, MN, SS, ZZ: Word; HH1, MN1: Integer; TimeOffsetSign: Char; begin Len := Length(AValue); YY := StrToIntDef(copy(AValue, 1, 4), 0); I := 5; if (I <= Len) and (AValue[I] = '-') then inc(I); MM := StrToIntDef(copy(AValue, I, 2), 0); inc(I, 2); if (I <= Len) and (AValue[I] = '-') then inc(I); DD := StrToIntDef(copy(AValue, I, 2), 0); inc(I, 2); HH := 0; MN := 0; SS := 0; ZZ := 0; if not ADateOnly and (I <= Len) and (AValue[I] = 'T') then begin inc(I); HH := StrToIntDef(copy(AValue, I, 2), 0); inc(I, 2); if (I <= Len) and CharInSet(AValue[I], [':', '0' .. '5']) then begin if AValue[I] = ':' then inc(I); MN := StrToIntDef(copy(AValue, I, 2), 0); inc(I, 2); if (I <= Len) and CharInSet(AValue[I], [':', '0' .. '5']) then begin if AValue[I] = ':' then inc(I); SS := StrToIntDef(copy(AValue, I, 2), 0); inc(I, 2); if (I <= Len) and (AValue[I] = '.') then begin inc(I); ZZ := StrToIntDef(copy(AValue, I, 3), 0); inc(I, 3); end; end; end; end; Result := EncodeDateTime(YY, MM, DD, HH, MN, SS, ZZ); if ADateOnly then Exit; if (I <= Len) and CharInSet(AValue[I], ['Z', '+', '-']) then begin if AValue[I] <> 'Z' then begin TimeOffsetSign := AValue[I]; inc(I); HH1 := StrToIntDef(copy(AValue, I, 2), 0); inc(I, 2); if (I <= Len) and CharInSet(AValue[I], [':', '0' .. '5']) then begin if AValue[I] = ':' then inc(I); MN1 := StrToIntDef(copy(AValue, I, 2), 0); end else MN1 := 0; if TimeOffsetSign = '+' then begin HH1 := -HH1; MN1 := -MN1; end; Result := IncHour(Result, HH1); Result := IncMinute(Result, MN1); end; end else Result := SystemTimeToUTC(Result); end; constructor TWebDAVSend.Create; begin inherited; FHTTP := THTTPSend.Create; FResources := TWDResourceList.Create; end; destructor TWebDAVSend.Destroy; begin FHTTP.Free; FResources.Free; inherited; end; procedure TWebDAVSend.SetToken; begin FToken:=EncodeBase64(FLogin+':'+FPassword); end; procedure TWebDAVSend.SetLogin(const Value: string); begin FLogin := Value; SetToken; end; procedure TWebDAVSend.SetPassword(const Value: string); begin FPassword := Value; SetToken; end; function TWebDAVSend.EncodeUTF8URI(const URI: string): string; var i: integer; Char: AnsiChar; begin result := ''; for i := 1 to length(URI) do begin if not(URI[i] in URLFullSpecialChar) then begin for Char in UTF8String(URI[i]) do Result:=Result+'%'+IntToHex(Ord(Char), 2) end else Result:=Result+URI[i]; end; end; function TWebDAVSend.GetRequestURL(const Element: string; EncodePath:boolean): string; var URI: string; begin if Length(Element)>0 then begin URI:=Element; if URI[1]='/' then Delete(URI,1,1); if EncodePath then Result:=cWebDAVServer+EncodeUTF8URI(URI) else Result:=cWebDAVServer+URI end else Result:=cWebDAVServer; end; //чтение содержимого каталога //********************************************************************* procedure TWebDAVSend.ParseResources(const AXMLStr: string); var XMLDoc: IXMLDocument; ResponseNode,ChildNode,PropNodeChild, PropertyNode: IXMLNode; s, su,Value: string; begin XMLDoc:=TXMLDocument.Create(nil); try XMLDoc.LoadFromXML(AXMLStr); if not XMLDoc.IsEmptyDoc then begin ResponseNode:=XMLDoc.DocumentElement.ChildNodes.First; while Assigned(ResponseNode) do begin FResources.Add(TWDResource.Create); ChildNode:=ResponseNode.ChildNodes.First; while Assigned(ChildNode) do begin if ChildNode.NodeName='d:href' then // FResources.Last.FHref:=ChildNode.Text FResources.Last.FHref:=Utf8ToAnsi(ChildNode.Text) else if ChildNode.NodeName='d:propstat' then begin PropNodeChild:=ChildNode.ChildNodes.First; while Assigned(PropNodeChild) do begin if PropNodeChild.NodeName='d:status' then begin Value:=PropNodeChild.Text; s := Trim(SeparateRight(Value, ' ')); su := Trim(SeparateLeft(s, ' ')); FResources.Last.FStatusCode:=StrToIntDef(su, 0); end else if PropNodeChild.NodeName='d:prop' then begin PropertyNode:=PropNodeChild.ChildNodes.First; while Assigned(PropertyNode) do begin if PropertyNode.NodeName='d:creationdate' then FResources.Last.FCreationDate := UTCToSystemTime(ISODateTime2UTC(PropertyNode.Text)) else if PropertyNode.NodeName='d:displayname' then FResources.Last.FDisplayName:=Utf8ToAnsi(PropertyNode.Text) else if PropertyNode.NodeName='d:getcontentlength' then FResources.Last.FContentLength:=PropertyNode.NodeValue else if PropertyNode.NodeName='d:getlastmodified' then FResources.Last.FLastmodified:=DecodeRfcDateTime(PropertyNode.Text) else if PropertyNode.NodeName='d:resourcetype' then FResources.Last.FCollection:=PropertyNode.ChildNodes.Count > 0; PropertyNode:=PropertyNode.NextSibling; end; end; PropNodeChild:=PropNodeChild.NextSibling; end; end; ChildNode:=ChildNode.NextSibling; end; ResponseNode:=ResponseNode.NextSibling; end; end; finally XMLDoc:=nil; end; end; function TWebDAVSend.GetData(DAVDir : string; errToDisplay : boolean): TListView; var Str: string; lvl : byte; begin FResources.Clear; lvl := 1; // Str:= PROPFIND(1, InputBox('Ресурс', 'Ресурс', '')); str := PROPFIND(lvl, DAVDir, errToDisplay); if (Length(Trim(Str)) > 0) then begin ParseResources(Str); FCurDir := DAVDir; end; end; //************************ Чтение содержимого каталога ******************** function TWebDAVSend.PROPFIND(Depth: integer; const Element: String; errToDisplay : boolean): string; begin with FHTTP do begin Headers.Clear; Document.Clear; Headers.Add('Authorization: Basic ' + FToken); Headers.Add('Depth: ' + IntToStr(Depth)); Headers.Add('Accept: */*'); if HTTPMethod('PROPFIND', GetRequestURL(Element)) then result := ReadStrFromStream(Document, Document.Size) else if errToDisplay then raise Exception.Create(rsPropfindError+' '+ResultString) else SaveErrFile(rsPropfindError+' '+ResultString + ' (PROPFIND' + Element + ')'); end; end; //************************ Создание папки ********************************* function TWebDAVSend.MKCOL(const ElementPath: string; errToDisplay : boolean): boolean; begin Result:=False; with FHTTP do begin Headers.Clear; Document.Clear; Headers.Add('Authorization: Basic ' + FToken); Headers.Add('Accept: */*'); if HTTPMethod('MKCOL', GetRequestURL(ElementPath)) then begin Result:=ResultCode=201; if not Result then if errToDisplay then raise Exception.Create(IntToStr(ResultCode)+' '+ResultString) else SaveErrFile(IntToStr(ResultCode)+' '+ResultString + ' (MKCOL ' + ElementPath + ')'); end else if errToDisplay then raise Exception.Create(rsPropfindError+' '+ResultString + ' (MKCOL ' + ElementPath + ')') else SaveErrFile(rsPropfindError+' '+ResultString); end; end; //************************ скачивание с яндекс дтска*********************** function TWebDAVSend.Get(const ElementHref: string; var Response:TStream; errToDisplay : boolean): boolean; var URL: string; begin if not Assigned(Response) then Exit; URL:=GetRequestURL(ElementHref, false); with FHTTP do begin Headers.Clear; Document.Clear; Headers.Add('Authorization: Basic ' + FToken); Headers.Add('Accept: */*'); if HTTPMethod('GET', URL) then begin Result:=ResultCode=200; if not Result then begin if errToDisplay then raise Exception.Create(IntToStr(ResultCode)+' '+ResultString) else SaveErrFile(IntToStr(ResultCode)+' '+ResultString + ' (GET ' + ElementHref + ')'); end else Document.SaveToStream(Response); end else if errToDisplay then raise Exception.Create(rsPropfindError+' '+ResultString) else SaveErrFile(rsPropfindError+' '+ResultString + ' (GET ' + ElementHref + ')'); end; end; //-------------------------- загрузкам на яндекс диск----------------------- function TWebDAVSend.PUT(const ElementHref: string; aFileName: string; errToDisplay : boolean): boolean; var s : TStream; st : String; fLength : int64; begin s := TFileStream.Create(aFileName,fmOpenRead); fLength := s.Size; with FHTTP do begin Headers.Clear; Document.Clear; Headers.Add('Authorization: Basic ' + FToken); Headers.Add('Accept: */*'); Document.LoadFromStream(s); Headers.Add('Expect: 100-continue'); Headers.Add('Content-Type: application/binary'); // Headers.Add('Content-Length: ' + intToStr(fLength)); // if HTTPMethod('PUT', GetRequestURL(ElementHref)) then begin result:=ResultCode=201; if not Result then if errToDisplay then raise Exception.Create(IntToStr(ResultCode)+' '+ResultString) else SaveErrFile(IntToStr(ResultCode)+' '+ResultString + ' (PUT ' + ElementHref + ')'); end else if errToDisplay then raise Exception.Create(rsPropfindError+' '+ResultString + ' (PUT ' + ElementHref + ')') else SaveErrFile(rsPropfindError+' '+ResultString); end; s.Free; end; //----------------------------- удаление файла/папки --------------------------- function TWebDAVSend.DAVDelete(const ElementPath: string; errToDisplay : boolean): boolean; begin Result:=False; with FHTTP do begin Headers.Clear; Document.Clear; Headers.Add('Authorization: Basic ' + FToken); Headers.Add('Accept: */*'); if HTTPMethod('DELETE', GetRequestURL(ElementPath)) then begin Result:=ResultCode=204; if not Result then if errToDisplay then raise Exception.Create(IntToStr(ResultCode)+' '+ResultString) else SaveErrFile(IntToStr(ResultCode)+' '+ResultString + ' (DELETE ' + ElementPath + ')'); end else if errToDisplay then raise Exception.Create(rsPropfindError+' '+ResultString + ' (DELETE ' + ElementPath + ')') else SaveErrFile(rsPropfindError+' '+ResultString); end; end; { TWDResourceList } procedure TWDResourceList.Clear; var i:integer; begin for I := Count-1 downto 0 do Extract(Items[0]).Free; inherited Clear; end; constructor TWDResourceList.Create; begin inherited Create; end; destructor TWDResourceList.Destroy; begin Clear; inherited; end; end. |

There are no comments