summaryrefslogtreecommitdiff
path: root/packages/googleapi/examples/generator/googleapiconv.pp
blob: 7d1ca5ab682a6b342c72ba3793072dfdfda45a9e (plain)
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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
{$mode objfpc}
{$h+}

{ $DEFINE USESYNAPSE}

{$IFDEF VER2_6}
{$DEFINE USESYNAPSE}
{$ENDIF}

program googleapiconv;

uses
  custapp, classes, sysutils, fpjson, jsonparser, fpwebclient,
{$IFDEF USESYNAPSE}
  ssl_openssl,
  synapsewebclient,
{$ELSE}
  fphttpwebclient,
{$ENDIF}
  googlediscoverytopas, googleservice, restbase, pascodegen, restcodegen;

Const
  BaseDiscoveryURL = 'https://www.googleapis.com/discovery/v1/apis/';


Type

  { TGoogleAPIConverter }

  { TAPIEntry }

  TAPIEntry = Class(TCollectionItem)
  private
    FAPIIcon: String;
    FAPIName: String;
    FAPIUnitName: String;
    FFileName: String;
  Public
    Property APIName : String Read FAPIName Write FAPIName;
    Property FileName : String Read FFileName Write FFileName;
    Property APIUnitName : String Read FAPIUnitName Write FAPIUnitName;
    Property APIIcon : String Read FAPIIcon Write FAPIIcon;
  end;

  { TAPIEntries }

  TAPIEntries = Class(TCollection)
  private
    function GetE(AIndex : Integer): TAPIEntry;
  Public
    Function AddEntry : TAPIEntry;
    Property Entries [AIndex : Integer] : TAPIEntry Read GetE; default;
  end;

  TGoogleAPIConverter = CLass(TCustomApplication)
  private
    FDownloadOnly: Boolean;
    FKeepJSON: Boolean;
    FUnitPrefix: String;
    FVerbose: Boolean;
    procedure ConversionLog(Sender: TObject; LogType: TCodegenLogType; const Msg: String);
    procedure CreateFPMake(FileName: String; L: TAPIEntries);
    procedure DoAll(LocalFile, URL, OFN: String; AllVersions: Boolean);
    Procedure DoConversion(JS: TStream; AEntry : TAPIEntry) ;
    procedure DownloadIcon(APIEntry: TAPIentry);
    function GetList(LocalFile, URL: String; AllVersions: Boolean): TJSONObject;
    Function HttpGetJSON(Const URL : String; Response : TStream) : Boolean;
    procedure RegisterUnit(FileName: String; L: TAPIEntries);
    procedure Usage(Msg: String);
  Public
    Constructor Create(AOwner: TComponent); override;
    Destructor Destroy; override;
    Procedure DoRun; override;
    Property KeepJSON : Boolean Read FKeepJSON Write FKeepJSON;
    Property Verbose : Boolean Read FVerbose Write FVerbose;
    Property DownloadOnly : Boolean Read FDownloadOnly Write FDownloadOnly;
    Property UnitPrefix : String Read FUnitPrefix Write FUnitPrefix;
  end;

{ TAPIEntries }

function TAPIEntries.GetE(AIndex : Integer): TAPIEntry;
begin
  Result:=Items[AIndex] as TAPIEntry;
end;

function TAPIEntries.AddEntry: TAPIEntry;
begin
  Result:=Add as TAPIEntry;
end;

Constructor TGoogleAPIConverter.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  StopOnException:=True;
  TDiscoveryJSONToPas.RegisterAllObjects;
  UnitPrefix:='google';
end;

Destructor TGoogleAPIConverter.Destroy;
begin
  inherited Destroy;
end;

Function TGoogleAPIConverter.HttpGetJSON(Const URL: String; Response: TStream
  ): Boolean;

Var
  Webclient : TAbstractWebClient;
  Req: TWebClientRequest;
  Resp : TWebClientResponse;

begin
  Result:=True;
  Req:=Nil;
  Resp:=Nil;
{$IFDEF USESYNAPSE}
  WebClient:=TSynapseWebClient.Create(Self);
{$ELSE}
  WebClient:=TFPHTTPWebClient.Create(Self);
{$ENDIF}
  try
    Req:=WebClient.CreateRequest;
    Req.ResponseContent:=Response;
    ConversionLog(Self,cltInfo,'Downloading: '+URL);
    Resp:=WebClient.ExecuteRequest('GET',URL,Req);
    Result:=(Resp<>Nil);
  finally
    Resp.Free;
    Req.Free;
    WebClient.Free;
  end;
end;

procedure TGoogleAPIConverter.Usage(Msg : String);

begin
  If (Msg<>'') then
    Writeln('Error : ',Msg);
  Writeln('Usage : ',ExeName,' [options] [inputfile] [outputfile]');
  Writeln('Where options is one of: ');
  Writeln('-a --all                   Download and generate code for all preferred services.');
  Writeln('-A --All                   Download and generate code for all services.');
  Writeln('if one of these options is given, then:');
  Writeln('   a) The service name will be appended to the output filename.');
  Writeln('   b) The --input will be used as a json which lists the services.');
  Writeln('-b --baseclass=classname   Class name to use as parent class for all classes.');
  Writeln('-b --baseclass=classname   Class name to use as parent class for all classes.');
  Writeln('-m --fpmake=filename       Generate fpmake program.');
  Writeln('-e --extraunits=units      comma separated list of units to add to uses clause.');
  Writeln('-h --help                  this message');
  Writeln('-i --input=file            input filename (overrides non-option inputfile)');
  Writeln('-I --icons                 Download service icon (size 16)');
  Writeln('-L --license=licensetext   Set license text to be added to the top of the unit.');
  Writeln('                           Use @filename to load license text from filename');
  Writeln('-o --output=file           output filename (overrides non-option outputfile)');
  Writeln('                           Default is to use input filename with extension .pp');
  Writeln('-p --classprefix=prefix    Prefix to use in class names for all classes.');
  Writeln('-r --resourcesuffix=suffix Suffix to use for resource names. Default is Resource.');
  Writeln('-R --register=unit         Register unit for Lazarus.');
  Writeln('-t --timestamp             Add timestamp to generated unit.');
  Writeln('-u --url=URL               URL to download the REST description from.');
  Writeln('-v --serviceversion=v      Service version to download the REST description for.');
  Writeln('-V --verbose               Write some diagnostic messages');
  Writeln('-k --keepjson              Keep the downloaded JSON files');
  Writeln('-d --onlydownload          Just download the files, do not actually convert.');
  Writeln('                           Only effective if -k or --keepjson is also specified.');
  Writeln('-f --unitprefix            Prefix for generated unit names. Default is "google"');
  Writeln('If the outputfilename is empty and cannot be determined, an error is returned');
  Halt(Ord(Msg<>''));
end;

function TGoogleAPIConverter.GetList(LocalFile, URL: String;
  AllVersions: Boolean): TJSONObject;

Var
  D : TJSONData;
  S : TStream;

begin
  if (LocalFile<>'') then
    S:=TFileStream.Create(LocalFile,fmOpenRead)
  else
    begin
    S:=TMemoryStream.Create;
    if (URL='') then
      URL:=BaseDiscoveryURL;
    If not AllVersions then
      URL:=URL+'?preferred=true';
    HTTPGetJSON(URL,S);
    S.Position:=0;
    end;
  try
    D:=GetJSON(S);
    if Not (D is TJSONObject) then
      begin
      D.Free;
      Raise Exception.CreateFmt('Source is not a valid JSON description',[LocalFile+URL]);
      end;
    Result:=D as TJSONObject;
  finally
    S.Free;
  end;
end;

procedure TGoogleAPIConverter.RegisterUnit(FileName :String; L : TAPIEntries);

Var
  I : Integer;
  UN,N,V : String;

begin
  UN:=ChangeFileext(ExtractFileName(FileName),'');
  With TStringList.Create do
    try
      Add(Format('unit %s;',[un]));
      Add('');
      Add('interface');
      Add('');
      Add('{$mode objfpc}{$h+}');
      Add('');
      Add('uses sysutils,classes;');
      Add('');
      Add('procedure register;');
      Add('');
      Add('implementation');
      Add('');
      Add('uses');
      if Hasoption('I','icon') then
        Add('  lazres,');
      Add('  restbase,');
      Add('  googleservice,');
      Add('  googlebase,');
      Add('  googleclient,');
      For I:=0 to L.Count-1 do
        begin
        N:=L[i].APIUnitName;
        if I<L.Count-1 then
          Add('  '+N+',')
        else
          Add('  '+N+';')
        end;
      Add('');
      Add('');
      Add('procedure register;');
      Add('');
      Add('begin');
      if Hasoption('I','icon') then
        Add('{$i '+un+'.inc}');
      Add('  RegisterComponents(''Google API'',[');
      Add('    TGoogleClient,');
      For I:=0 to L.Count-1 do
        begin
        N:=L[i].APIName;
        if I<L.Count-1 then
          Add('    '+N+',')
        else
          Add('    '+N)
        end;
      Add('   ]);');
      Add('end;');
      Add('');
      Add('end.');
      SaveToFile(FileName);
    finally
      Free;
    end;
end;

procedure TGoogleAPIConverter.ConversionLog(Sender: TObject;
  LogType: TCodegenLogType; const Msg: String);
begin
  if Verbose then
    Writeln(StdErr,Msg);
end;

procedure TGoogleAPIConverter.CreateFPMake(FileName :String; L : TAPIEntries);

Var
  I : Integer;
  UN,N,V : String;

begin
  UN:=ChangeFileext(ExtractFileName(FileName),'');
  With TStringList.Create do
    try
      Add('program fpmake;');
      Add('');
      Add('{$mode objfpc}{$h+}');
      Add('');
      Add('uses sysutils,classes, fpmkunit;');
      Add('');
      Add('');
      Add('function StdDep(T : TTarget) : TTarget;');
      Add('begin');
      Add('  T.Dependencies.AddUnit(''googlebase'');');
      Add('  T.Dependencies.AddUnit(''googleservice'');');
      Add('  Result:=T;');
      Add('end;');
      Add('');
      Add('Procedure AddGoogle;');
      Add('');
      Add('Var');
      Add('  P : TPackage;');
      Add('  T : TTarget;');
      Add('');
      Add('begin');
      Add('  With Installer do');
      Add('    begin');
      Add('    P:=AddPackage(''googleapis'');');
      Add('    P.ShortName:=''googleap'';');
      Add('    T:=P.Targets.AddUnit(''googlebase.pp'');');
      Add('    T:=P.Targets.AddUnit(''googleclient.pp'');');
      Add('    T:=P.Targets.AddUnit(''googleservice.pp'');');
      Add('    T.Dependencies.AddUnit(''googleclient'');');
      Add('    T.Dependencies.AddUnit(''googlebase'');');
      For I:=0 to L.Count-1 do
        begin
        N:=L[i].APIUnitName;
        Add(Format('    T:=StdDep(P.Targets.AddUnit(''%s''));',[ExtractFileName(L[i].FAPIUnitName)]));
        end;
      Add('    end;');
      Add('end;');
      Add('');
      Add('{$ifndef ALLPACKAGES}');
      Add('begin');
      Add('  AddGoogle;');
      Add('  Installer.Run;');
      Add('end.');
      Add('{$endif ALLPACKAGES}');
      Add('');
      Add('procedure register;');
      Add('');
      Add('begin');
      SaveToFile(FileName);
    finally
      Free;
    end;
end;


procedure TGoogleAPIConverter.DoAll(LocalFile, URL, OFN : String; AllVersions : Boolean);

Var
  D,O : TJSONObject;
  RS : TStringStream;
  A : TJSONArray;
  S : TJSONEnum;
  LFN,RU,E : String;
  UL : TAPIEntries;
  U : TAPIEntry;
  I : Integer;

begin
  E:=ExtractFileExt(OFN);
  if (E='') then
    E:='.pp';
  UL:=Nil;
  D:=GetList(LocalFile,URL,ALlVersions);
  try
    UL:=TAPIEntries.Create(TAPIEntry);
    A:=D.Get('items',TJSONArray(Nil));
    For S in A do
      begin
      O:=S.Value as TJSONObject;
      if AllVersions or O.Get('preferred',false) then
        begin
        RU:=O.get('discoveryRestUrl');
        LFN:=UnitPrefix+O.get('name');
        if AllVersions then
          LFN:=LFN+'_'+StringReplace(O.get('version'),'.','',[rfReplaceAll]);
        if (OFN='') then
          LFN:=LFN+E
        else
          LFN:=ChangeFileExt(OFN,LFN+E);
        RS:=TStringStream.Create('');
        try
          if not HttpGetJSON(RU,RS) then
            Raise Exception.Create('Could not download rest description from URL: '+RU);
          ConversionLog(Self,cltInfo,Format('Converting service "%s" to unit: %s',[O.get('name'),LFN]));
          if KeepJSON then
            With TFIleStream.Create(ChangeFileExt(LFN,'.json'),fmCreate) do
              try
                CopyFrom(RS,0);
              finally
                Free;
              end;
          RS.Position:=0;
          U:=UL.AddEntry;
          U.FileName:=LFN;
          if not DownloadOnly then
            DoConversion(RS,U);
        finally
          RS.Free;
        end;
        end;
      end;
    if not DownloadOnly then
      begin
      if HasOption('R','register') then
        RegisterUnit(GetOptionValue('R','register'),UL);
      if HasOption('m','fpmake') then
        CreateFpMake(GetOptionValue('m','fpmake'),UL);
      end;
    if HasOption('I','icon') then
      For I:=0 to UL.Count-1 do
        DownloadIcon(UL[i]);
  finally
    UL.Free;
    D.Free;
  end;
end;

Procedure TGoogleAPIConverter.DoRun;

Const
  MyO : Array[1..21] of ansistring
      =  ('help','input:','output:','extraunits:','baseclass:','classprefix:',
          'url:','service:','serviceversion:','resourcesuffix:','license:',
          'All','all','register','icon','fpmake:','timestamp','verbose','keepjson',
          'onlydownload','unitprefix');

Var
  O,NonOpts : TStrings;
  URL, S, IFN, OFN : AnsiString;
  JS : TStream;
  DoAllServices : Boolean;
  APIEntry : TAPIEntry;

begin
  JS:=Nil;
  O:=Nil;
  NonOpts:=TStringList.Create;
  try
    O:=TStringList.Create;
    For S in MyO do O.Add(S);
    S:=Checkoptions('hi:o:e:b:p:u:s:v:r:L:aAR:Im:tVkdf',O,TStrings(Nil),NonOpts,True);
    if NonOpts.Count>0 then
      IFN:=NonOpts[0];
    if NonOpts.Count>1 then
      OFN:=NonOpts[1];
  finally
    O.Free;
    NonOpts.Free;
  end;
  FVerbose:=HasOption('V','verbose');
  FKeepJSON:=HasOption('k','keepjson');
  if HasOption('f','unitprefix') then
    UnitPrefix:=GetOptionValue('f','unitprefix');
  If FKeepJSON Then
    FDownLoadOnly:=HasOption('d','onlydownload');
  if (S<>'') or HasOption('h','help') then
    Usage(S);
  DoAllServices:=HasOption('a','all') or HasOption('A','All');
  if HasOption('i','input') then
    IFN:=GetOptionValue('i','input');
  if HasOption('o','output') then
    OFN:=GetOptionValue('o','output');
  if HasOption('u','url') then
    URL:=GetOptionValue('u','url')
  else if hasOption('s','service') then
    begin
    URL:=BaseDiscoveryURL+getOptionValue('s','service');
    if (pos('/',getOptionValue('s','service'))= 0) and
       HasOption('v','serviceversion') then
       URL:=URL+getOptionValue('v','serviceversion');
    if (URL[Length(URL)]<>'/') then
      URL:=URL+'/';
    URL:=URL+'rest';
    end;
  if (not DoAllServices) and (IFN='') and (URL='') then
    Usage('Need an input filename or URL');
  if (OFN='') then
    if (IFN<>'') then
      OFN:=ChangeFileExt(IFN,'.pp')
    else if getOptionValue('s','service')<>'' then
      OFN:=UnitPrefix+getOptionValue('s','service')+'.pp';
  if (OFN='') and Not DoAllServices then
    Usage('Need an output filename');
  if DoAllServices then
    DoAll(IFN,URL,OFN,HasOption('A','All'))
  else
    begin
    APIEntry:=Nil;
    if (IFN='') and (URL<>'') then
      begin
      JS:=TMemoryStream.Create;
      if not HttpGetJSON(URL,JS) then
        Raise Exception.Create('Could not download from URL: '+URL);
      if KeepJSON then
        With TFIleStream.Create(ChangeFileExt(OFN,'.json'),fmCreate) do
          try
            CopyFrom(JS,0);
          finally
            Free;
          end;
      JS.POsition:=0;
      end
    else
      JS:=TFileStream.Create(IFN,fmOpenRead or fmShareDenyWrite);
    try
      if not DownLoadOnly then
        APIEntry:=TAPIEntry.Create(Nil);
        try
          APIEntry.FileName:=OFN;
          DoConversion(JS,APIEntry);
          if HasOption('I','icon') then
            DownloadIcon(APIEntry);
        finally
          APIEntry.Free;
        end;
    finally
      JS.Free;
    end;
    end;
  Terminate;
end;

procedure TGoogleAPIConverter.DownloadIcon(APIEntry : TAPIentry);

Var
  FN : String;
  FS : TFileStream;

begin
  if (APIEntry.APIIcon<>'') then
    begin
    FN:=ExtractFilePath(APIEntry.FileName)+APIEntry.APIName+ExtractFileExt(APIEntry.APIIcon);
    FS:=TFileStream.Create(FN,fmCreate);
    try
      if HasOption('V','verbose') then
        Writeln(Format('Downloading icon %s to %s',[APIEntry.APIIcon,FN]));
      HttpGetJSON(APIEntry.APIIcon,FS);
    finally
      FS.Free;
    end;
    end;
end;

Procedure TGoogleAPIConverter.DoConversion(JS: TStream; AEntry: TAPIEntry);

Var
  L: String;
  O : TGoogleIcons;

begin
  With TDiscoveryJSONToPas.Create(Nil) do
    try
      L:=GetOptionValue('L','license');
      if (L<>'') then
        begin
        if (L[1]<>'@') then
          LicenseText.Text:=L
        else
          begin
          Delete(L,1,1);
          LicenseText.LoadFromFile(L);
          end;
        end;
      OnLog:=@ConversionLog;
      ExtraUnits:=GetOptionValue('e','extraunits');
      if HasOption('b','baseclass') then
        BaseClassName:=GetOptionValue('b','baseclass');
      if HasOption('p','classprefix') then
        ClassPrefix:=GetOptionValue('p','classprefix');
      if HasOption('r','resourcesuffix') then
        ResourceSuffix:=GetOptionValue('r','resourcesuffix');
      AddTimeStamp:=HasOption('t','timestamp');
      LoadFromStream(JS);
      AEntry.APIUnitName:=ChangeFileExt(ExtractFileName(AEntry.FileName),'');
      AEntry.APIName:=APIClassName;
      O:=Description.icons;
      if Assigned(O) then
        AEntry.APIIcon:=O.x16;
      SaveToFile(AEntry.FileName);
    finally
      Free;
    end;
end;

Var
  Application : TGoogleAPIConverter;
begin
  {$if declared(Heaptrc)}
  printleakedblock:=true;
  printfaultyblock:=true;
  add_tail:=true;
  SetHeapTraceOutput('heaptrc.txt');
  {$endif}
  Application:=TGoogleAPIConverter.Create(Nil);
  Application.Initialize;
  Application.Run;
end.