Delphi ile Youtube data API işlemleri

Merhabalar,

Youtube’un bize sağladığı apileri Delphi uygulaması ile nasıl kullanabiliriz (in)  cevabı bu yazıda olacak.

Öncelikle Buradaki youtube developer sitesinden bir api key edinmeniz gerekiyor.

Api keyinizi aldıktan sonra aşağıdaki hazırladığımUV3 .pas dosyasını inceleyebilirsiniz. nerede ne yaptığımı uzun uzun anlatmaya zamanım yok ancak sorunuz olur ise aşağıdan sorabilirsiniz.

 

Uygulamamızın ilk ekran görüntüsü.

 

 

unit UV3;

interface

{  İlk Versiyon diyelim sadece bir videonun detaylarını alabildiğimiz videos Metodu var elimizde  05.02.2019  }

 uses
    System.classes,
    System.SysUtils,
    System.Json,
    clHttp;

 const
      apiurl = 'https://www.googleapis.com/youtube/v3/';

 type


    //// Videos
    rpageInfo  =  record 
       totalResults   : Integer;
       resultsPerPage : Integer;
    end;
    rthumb = record
      name    : String;
      url     : String;
      width   : String;
      height  : String;
    end;
    
    
    rlocalized = record
      localized : String;
    end;
    
    rsnippet = record
       publishedAt           : String;
       channelId             : String;
       title                 : String;
       description           : String;
       thumbnails            : array of rthumb;
       channelTitle          : String;
       tags                  : array of String;
       categoryId            : String;
       liveBroadcastContent  : String;
       defaultLanguage       : String;
       localized             : rlocalized;
       defaultAudioLanguage  : String;
    end;
    ritems =  record
      kind    : String;
      etag    : String;
      id      : String;
      snippet : rsnippet; 
    end;
    VideoResult =  record
      kind : String;
      etag : String; 
      pageInfo : rpageInfo;  
      items : ritems;
    end;
   //// Videos



  TYoutubeV3 = class(TObject)
  private
    FApiKey: String;
    FLogPath: String;
    function RestApi(Url:String):String;
    procedure SetApiKey(const Value: String);
    procedure SetLogPath(const Value: String);
    function Video(watchcode:String):String;
  public
    property ApiKey: String read FApiKey write SetApiKey;
    property LogPath: String read FLogPath write SetLogPath;

    function GetVideo(watchcode:String):VideoResult;
  end;

implementation

{ TYoutubeV3 }


function TYoutubeV3.Video(watchcode: String): String;
begin
   if Trim(watchcode)='' then raise Exception.Create(Format('%s Boş Olamaz..!', ['watchcode']));
   if Trim(FApiKey)='' then raise Exception.Create(Format('%s Boş Olamaz..!', ['ApiKey']));   
   Result := RestApi(Format('%svideos?part=snippet&id=%s&key=%s', [apiurl,watchcode,ApiKey]));
end;

function TYoutubeV3.GetVideo(watchcode: String): VideoResult;
const
  thm: array [0 .. 4] of string = ('default', 'medium', 'high', 'standard', 'maxres');
var
  json ,
  pageInfo,
  item,
  snippet,
  thumbnails,
  thumbnail   : TJSONObject;
  items       : TJSONArray;
  i:integer;
begin
  try
    json        := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(Video(watchcode)),0) as TJSONObject;
    Result.kind :=   json.GetValue('kind').Value;
    Result.etag :=   json.GetValue('etag').Value;


    pageInfo                       := json.GetValue('pageInfo') as TJsonObject;
    Result.pageInfo.totalResults   := StrToIntDef(pageInfo.GetValue('totalResults').ToJSON,0);
    Result.pageInfo.resultsPerPage := StrToIntDef(pageInfo.GetValue('resultsPerPage').ToJSON,0);


               
    items    := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(json.GetValue('items').ToString),0) as TJSONArray;
    item     := items.Get(0) as TJsonObject;

    Result.items.kind :=  item.GetValue('kind').Value;
    Result.items.etag :=  item.GetValue('etag').Value;
    Result.items.id   :=  item.GetValue('id').Value;
    

    snippet                                    := item.GetValue('snippet') as TJsonObject;    
    Result.items.snippet.publishedAt           := snippet.GetValue('publishedAt').Value;
    Result.items.snippet.channelId             := snippet.GetValue('channelId').Value;
    Result.items.snippet.title                 := snippet.GetValue('title').Value;
    Result.items.snippet.description           := snippet.GetValue('description').Value;
    Result.items.snippet.channelTitle          := snippet.GetValue('channelTitle').Value;
    Result.items.snippet.categoryId            := snippet.GetValue('categoryId').Value;
    Result.items.snippet.liveBroadcastContent  := snippet.GetValue('liveBroadcastContent').Value;

     if snippet.GetValue('defaultLanguage') <> nil then
        Result.items.snippet.defaultLanguage       := snippet.GetValue('defaultLanguage').Value;


    if snippet.GetValue('defaultAudioLanguage') <> nil then
      Result.items.snippet.defaultAudioLanguage  := snippet.GetValue('defaultAudioLanguage').Value;


    thumbnails    := snippet.GetValue('thumbnails') as TJsonObject;
     for I := Low(thm) to High(thm) do
       begin
          try
          SetLength(Result.items.snippet.thumbnails,Length(Result.items.snippet.thumbnails)+1);
           thumbnail      := thumbnails.GetValue(thm[i]) as TJsonObject;
           Result.items.snippet.thumbnails[i].name   := thm[i];

           if thumbnail.GetValue('url') <> nil then
            Result.items.snippet.thumbnails[i].url    := thumbnail.GetValue('url').Value;

           if thumbnail.GetValue('width') <> nil then
            Result.items.snippet.thumbnails[i].width  := thumbnail.GetValue('width').Value;

           if thumbnail.GetValue('height') <> nil then
            Result.items.snippet.thumbnails[i].height := thumbnail.GetValue('height').Value;
          except on E: Exception do
          end;
       end;
    
  except on E: Exception do
    raise;
  end;
end;

function TYoutubeV3.RestApi(Url:String): String;
var
  Response : TMemoryStream;
  FireBase : TclHttp;
  Ts : TStringList;
begin

  Response  := TMemoryStream.Create;
  FireBase  := TclHttp.Create(nil);
  Ts        := TStringList.Create;
  try
    FireBase.Get (url, Response);
    FireBase.TimeOut  := 60 * 1000;
    Response.Position := 0;
    Ts.LoadFromStream( Response , TEncoding.UTF8);
    Ts.SaveToFile(LogPath + '.json');
    Result := Ts.Text;
  finally
   FreeAndNil(Ts);
   FreeAndNil(Response);
   FreeAndNil(FireBase);
  end;
end;



procedure TYoutubeV3.SetApiKey(const Value: String);
begin
  FApiKey := Value;
end;

procedure TYoutubeV3.SetLogPath(const Value: String);
begin
  FLogPath := Value;
end;

end.

 

Uygulamanın Kodları ise bu şekilde.

unit UYoutubeApiv3;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus, dxSkinsCore,
  dxSkinBlack, dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide,
  dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary,
  dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMetropolis, dxSkinMetropolisDark,
  dxSkinMoneyTwins, dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink,
  dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinOffice2013DarkGray,
  dxSkinOffice2013LightGray, dxSkinOffice2013White, dxSkinOffice2016Colorful, dxSkinOffice2016Dark, dxSkinPumpkin,
  dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus, dxSkinSilver, dxSkinSpringTime, dxSkinStardust,
  dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinTheBezier, dxSkinsDefaultPainters, dxSkinValentine,
  dxSkinVisualStudio2013Blue, dxSkinVisualStudio2013Dark, dxSkinVisualStudio2013Light, dxSkinVS2010, dxSkinWhiteprint,
  dxSkinXmas2008Blue, Vcl.StdCtrls, cxButtons, Vcl.ComCtrls,
  Vcl.Clipbrd, Vcl.ExtCtrls,
  Uv3, Data.DB,
  clHttp ,
  Vcl.Imaging.jpeg, dxmdaset, Vcl.Grids, Vcl.DBGrids;

type
  TForm1 = class(TForm)
    YoutubeApiPageControl: TPageControl;
    TabKeys: TTabSheet;
    TabVideos: TTabSheet;
    ApiKeyGroupBox: TGroupBox;
    btn_apikey_key: TcxButton;
    Ed_ApiKey: TEdit;
    Panel1: TPanel;
    WatchKodeGroupBox: TGroupBox;
    cxButton1: TcxButton;
    EdWatch: TEdit;
    GroupBox1: TGroupBox;
    btn_logpath_kaydet: TcxButton;
    EdLogPath: TEdit;
    GroupBox2: TGroupBox;
    kind: TLabeledEdit;
    etag: TLabeledEdit;
    pageInfo: TGroupBox;
    totalResults: TLabeledEdit;
    resultsPerPage: TLabeledEdit;
    items: TGroupBox;
    kind1: TLabeledEdit;
    etag1: TLabeledEdit;
    id: TLabeledEdit;
    snippet: TGroupBox;
    publishedAt: TLabeledEdit;
    channelId: TLabeledEdit;
    title: TLabeledEdit;
    channelTitle: TLabeledEdit;
    categoryId: TLabeledEdit;
    liveBroadcastContent: TLabeledEdit;
    defaultLanguage: TLabeledEdit;
    defaultAudioLanguage: TLabeledEdit;
    VImage: TImage;
    DBGrid1: TDBGrid;
    thumbnailsdata: TdxMemData;
    thumbnailsdataurl: TStringField;
    thumbnailsdatawidth: TIntegerField;
    thumbnailsdataheight: TIntegerField;
    thumbnailsdatasource: TDataSource;
    thumbnailsdataname: TStringField;
    Label1: TLabel;
    description: TMemo;
    thumbnails: TLabel;
    procedure Ed_ApiKeyClick(Sender: TObject);
    procedure cxButton1Click(Sender: TObject);

    procedure SetImage(image:TImage;watch:String);
    procedure EdWatchClick(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.cxButton1Click(Sender: TObject);
var
  Api    : TYoutubeV3;
  Result : VideoResult;
  i:integer;
begin
  Api := TYoutubeV3.Create;
  try
    Api.ApiKey          := Ed_ApiKey.Text;
    Api.LogPath         := EdLogPath.Text;
    Result              :=  Api.GetVideo(EdWatch.Text);
    kind.Text           := Result.kind;
    etag.Text           := Result.etag;
    totalResults.Text   := Result.pageInfo.totalResults.ToString;
    resultsPerPage.Text := Result.pageInfo.resultsPerPage.ToString;

    kind1.Text           := Result.items.kind;
    etag1.Text           := Result.items.etag;
    id.Text              := Result.items.id;

   publishedAt.Text               := Result.items.snippet.publishedAt;
   channelId.Text                 := Result.items.snippet.channelId;
   title.Text                     := Result.items.snippet.title;
   channelTitle.Text              := Result.items.snippet.channelTitle;
   categoryId.Text                := Result.items.snippet.categoryId;
   liveBroadcastContent.Text      := Result.items.snippet.liveBroadcastContent;
   defaultLanguage.Text           := Result.items.snippet.defaultLanguage;
   defaultAudioLanguage.Text      := Result.items.snippet.defaultAudioLanguage;
   description.Text               := Result.items.snippet.description;


   for I := 0 to Length(Result.items.snippet.thumbnails) - 1  do
   begin
    thumbnailsdata.Append;
    thumbnailsdata.FieldByName('name').AsString   := Result.items.snippet.thumbnails[i].name;
    thumbnailsdata.FieldByName('url').AsString    := Result.items.snippet.thumbnails[i].url;
    thumbnailsdata.FieldByName('width').AsString  := Result.items.snippet.thumbnails[i].width;
    thumbnailsdata.FieldByName('height').AsString := Result.items.snippet.thumbnails[i].height;
    thumbnailsdata.Post;
   end;

   SetImage(VImage,EdWatch.Text);
  finally
    Api.Free;
  end;
end;



procedure TForm1.EdWatchClick(Sender: TObject);
begin
  EdWatch.Text := Clipboard.AsText;
end;

procedure TForm1.Ed_ApiKeyClick(Sender: TObject);
begin
  Ed_ApiKey.Text := Clipboard.AsText;
end;

procedure TForm1.SetImage(image: TImage; watch: String);
var
  MS   : TMemoryStream;
  JPEG : TJPEGImage;
  Http : TclHttp;
begin
  MS   := TMemoryStream.Create;
  JPEG := TJPEGImage.Create;
  Http := TclHttp.Create(nil);
  try
    Http.get('https://img.youtube.com/vi/'+watch+'/hqdefault.jpg',MS);
    Ms.Seek(0,soFromBeginning);
    JPEG.LoadFromStream(MS);
    VImage.Picture.Assign(JPEG);
  finally
    FreeAndNil(JPEG);
    FreeAndNil(MS);
    FreeAndNil(Http);
  end;
end;

end.

 

 

 

yhackup

Site Kurucusu & Yöneticisi Yazılım Geliştiricisi

1 1 vote
Bu yazıya oy ver
Subscribe
Bildir
2 Yorum
En Yeniler
Eskiler Beğenilenler
Inline Feedbacks
View all comments
cuneyt
2 yıl önce

could not load SSL library hatası veriyor. Neden acaba?

2
0
Would love your thoughts, please comment.x
()
x