Skip to content

Commit

Permalink
fix: removed memory leak and added some try..except
Browse files Browse the repository at this point in the history
  • Loading branch information
salvadorbs committed Dec 2, 2023
1 parent a58be6f commit 1225f86
Show file tree
Hide file tree
Showing 4 changed files with 104 additions and 25 deletions.
3 changes: 0 additions & 3 deletions LidlToGrocy.lpi
Original file line number Diff line number Diff line change
Expand Up @@ -209,9 +209,6 @@
</CompilerOptions>
<Debugging>
<Exceptions>
<Item>
<Name Value="EHTTPClient"/>
</Item>
</Exceptions>
</Debugging>
</CONFIG>
36 changes: 36 additions & 0 deletions library/grocy.product.pas
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ TGrocyProduct = class(TSynAutoCreateFields)
FShouldNotBeFrozen: string;
FTreatOpenedAsOutOfStock: string;
public
constructor Create(Source: TGrocyProduct); overload;
procedure DefaultSetup();
published
property Active: string read FActive write FActive;
Expand Down Expand Up @@ -91,6 +92,41 @@ implementation

{ TGrocyProduct }

constructor TGrocyProduct.Create(Source: TGrocyProduct);
begin
FActive := Source.Active;
FCalories := Source.Calories;
FCumulateMinStockAmountOfSubProducts := Source.CumulateMinStockAmountOfSubProducts;
FDefaultBestBeforeDays := Source.DefaultBestBeforeDays;
FDefaultBestBeforeDaysAfterFreezing := Source.DefaultBestBeforeDaysAfterFreezing;
FDefaultBestBeforeDaysAfterOpen := Source.DefaultBestBeforeDaysAfterOpen;
FDefaultBestBeforeDaysAfterThawing := Source.DefaultBestBeforeDaysAfterThawing;
FDefaultConsumeLocationId := Source.DefaultConsumeLocationId;
FDescription := Source.Description;
FDueType := Source.DueType;
FEnableTareWeightHandling := Source.EnableTareWeightHandling;
FHideOnStockOverview := Source.HideOnStockOverview;
FId := Source.Id;
FLocationId := Source.LocationId;
FMinStockAmount := Source.MinStockAmount;
FMoveOnOpen := Source.MoveOnOpen;
FName := Source.Name;
FNoOwnStock := Source.NoOwnStock;
FNotCheckStockFulfillmentForRecipes := Source.NotCheckStockFulfillmentForRecipes;
FParentProductId := Source.ParentProductId;
FPictureFileName := Source.PictureFileName;
FProductGroupId := Source.ProductGroupId;
FQuIdConsume := Source.QuIdConsume;
FQuIdPrice := Source.QuIdPrice;
FQuIdPurchase := Source.QuIdPurchase;
FQuIdStock := Source.QuIdStock;
FQuickConsumeAmount := Source.QuickConsumeAmount;
FQuickOpenAmount := Source.QuickOpenAmount;
FShoppingLocationId := Source.ShoppingLocationId;
FShouldNotBeFrozen := Source.ShouldNotBeFrozen;
FTreatOpenedAsOutOfStock := Source.TreatOpenedAsOutOfStock
end;

procedure TGrocyProduct.DefaultSetup();
begin
FActive := '1';
Expand Down
27 changes: 18 additions & 9 deletions library/kernel.application.pas
Original file line number Diff line number Diff line change
Expand Up @@ -111,16 +111,25 @@ function TLidlToGrocy.InsertOFFImageInGrocy(OFFProductInfo: TOFFProductInfo): bo
function TLidlToGrocy.GetGrocyProduct(LidlProduct: TItemsLine): TGrocyProduct;
var
GrocyProduct: TGrocyProduct;

procedure InternalAddNewGrocyProduct;
begin
TLogger.Info('Not found!', []);
//In case of product doesn't exists in Grocy
GrocyProduct := AddNewGrocyProduct(LidlProduct);
end;

begin
TLogger.Info('Find product in Grocy', []);
GrocyProduct := nil;
try
GrocyProduct := FGrocyService.GetProductByBarcode(LidlProduct.CodeInput);
TLogger.Info('Found! Grocy Product ID = %d', [GrocyProduct.Id]);
if Assigned(GrocyProduct) then
TLogger.Info('Found! Grocy Product ID = %d', [GrocyProduct.Id])
else
InternalAddNewGrocyProduct;
except
TLogger.Info('Not found!', []);
//In case of product doesn't exists in Grocy
GrocyProduct := AddNewGrocyProduct(LidlProduct);
InternalAddNewGrocyProduct;
end;

Result := GrocyProduct;
Expand Down Expand Up @@ -151,8 +160,10 @@ function TLidlToGrocy.AddNewGrocyProduct(LidlProduct: TItemsLine): TGrocyProduct
if Assigned(GrocyProduct) then
GrocyBarcode := FGrocyService.AddBarcodeToProduct(GrocyProduct.Id, LidlProduct.CodeInput);
finally
OFFProductInfo.Free;
GrocyBarcode.Free;
if Assigned(OFFProductInfo) then
OFFProductInfo.Free;
if Assigned(GrocyBarcode) then
GrocyBarcode.Free;
end;
except
on E: Exception do
Expand Down Expand Up @@ -306,8 +317,6 @@ procedure TLidlToGrocy.DoRun;
FConfiguration.SaveConfig;

TLogger.InfoExit('Completed processing', []);

Sleep(30000);
end;

Terminate;
Expand Down Expand Up @@ -335,7 +344,7 @@ destructor TLidlToGrocy.Destroy;

if Assigned(FLidlTickets) then
begin
for I := 0 to length(FLidlTickets) - 1 do
for I := 0 to Length(FLidlTickets) - 1 do
FLidlTickets[I].Free;
SetLength(FLidlTickets, 0);
end;
Expand Down
63 changes: 50 additions & 13 deletions service/grocy.service.pas
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
interface

uses
Classes, SysUtils, Grocy.Product, mormot.core.json, fphttpclient, base64,
Classes, SysUtils, Grocy.Product, mormot.core.json, fphttpclient, base64, ssockets,
opensslsockets, mormot.core.os, mormot.core.Text, mormot.core.base,
Grocy.Barcode, Grocy.ProductStock, OpenFoodFacts.ProductInfo, Kernel.Configuration;

Expand Down Expand Up @@ -187,24 +187,24 @@ function TGrocyService.CreateProduct(OFFProductInfo: TOFFProductInfo): TGrocyPro
end
else if (FClient.ResponseStatusCode = 400) then
begin
FreeRequestBody;

GrocyError := TGrocyError.Create;
try
LoadJson(GrocyError, Response, TypeInfo(TGrocyError));
if GrocyError.isErrorIntegrityUnique() then
begin
TLogger.Error('Failed to add a new product in Grocy due to violation of the uniqueness of the product name %s',
[GrocyProduct.Name]);
FreeRequestBody;

TLogger.Info('Finding Grocy product with same name "%s"', [GrocyProduct.Name]);
Result := GetProductByName(GrocyProduct.Name);
if Assigned(Result) then
TLogger.Info('Found! Grocy Product ID = %d', [Result.Id]);

// Now GrocyProduct doesn't need anymore
GrocyProduct.Free;
GrocyProduct := nil;
end;
// Now GrocyProduct doesn't need anymore
GrocyProduct.Free;
GrocyProduct := nil;
finally
GrocyError.Free;
end;
Expand All @@ -230,7 +230,9 @@ function TGrocyService.AddBarcodeToProduct(const ProductId: integer; const Barco
begin
GrocyBarcode.Id := GetIdFromJsonGrocy(Response, 'created_object_id');
Result := GrocyBarcode;
end;
end
else
GrocyBarcode.Free;

FreeRequestBody;
end;
Expand All @@ -243,7 +245,12 @@ function TGrocyService.GetProductByBarcode(Barcode: string): TGrocyProduct;
Result := nil;

try
Response := FClient.Get(Format(Self.BaseURL + UrlProductByBarcode, [Barcode]));
try
Response := FClient.Get(Format(Self.BaseURL + UrlProductByBarcode, [Barcode]));
except
on E: ESocketError do
TLogger.Exception(E);
end;
finally
if (FClient.ResponseStatusCode = 200) then
Result := GetGrocyProductFromJson(Response);
Expand All @@ -256,7 +263,12 @@ function TGrocyService.AddProductInStock(GrocyProductId: integer; ProductStock:

try
FClient.RequestBody := TRawByteStringStream.Create(ObjectToJson(ProductStock));
FClient.Post(Format(Self.BaseURL + UrlAddProductStock, [GrocyProductId]));
try
FClient.Post(Format(Self.BaseURL + UrlAddProductStock, [GrocyProductId]));
except
on E: ESocketError do
TLogger.Exception(E);
end;
finally
Result := (FClient.ResponseStatusCode = 200);

Expand All @@ -268,16 +280,31 @@ function TGrocyService.GetProductByName(Name: string): TGrocyProduct;
var
Response: string;
GrocyProducts: TGrocyProductArray;
I: integer;
begin
Result := nil;
GrocyProducts := nil;
try
Response := FClient.Get(Format(Self.BaseURL + UrlProductByName, [EncodeURLElement(Name)]));
try
Response := FClient.Get(Format(Self.BaseURL + UrlProductByName, [EncodeURLElement(Name)]));
except
on E: ESocketError do
TLogger.Exception(E);
end;
finally
if (FClient.ResponseStatusCode = 200) then
begin
DynArrayLoadJson(GrocyProducts, Response, TypeInfo(TGrocyProductArray));

if Length(GrocyProducts) = 1 then
Result := GrocyProducts[0];
Result := TGrocyProduct.Create(GrocyProducts[0]);

if Assigned(GrocyProducts) then
begin
for I := 0 to Length(GrocyProducts) - 1 do
GrocyProducts[I].Free;
SetLength(GrocyProducts, 0);
end;
end;
end;
end;
Expand All @@ -294,7 +321,12 @@ function TGrocyService.ConsumeByBarcode(Barcode: string; Amount: integer): boole

try
FClient.RequestBody := TRawByteStringStream.Create(jObject.AsJSON);
FClient.Post(Format(Self.BaseURL + UrlConsumeByBarcode, [Barcode]));
try
FClient.Post(Format(Self.BaseURL + UrlConsumeByBarcode, [Barcode]));
except
on E: ESocketError do
TLogger.Exception(E);
end;
finally
Result := (FClient.ResponseStatusCode = 200);
FreeRequestBody;
Expand All @@ -311,7 +343,12 @@ function TGrocyService.UploadImageFile(ImageStream: TStream; FileName: string):
FClient.AddHeader('Content-Type', 'application/octet-stream');
ImageStream.Position := 0;
FClient.RequestBody := ImageStream;
FClient.Put(Format(Self.BaseURL + UrlUploadFile, [FileName]));
try
FClient.Put(Format(Self.BaseURL + UrlUploadFile, [FileName]));
except
on E: ESocketError do
TLogger.Exception(E);
end;
finally
Result := (FClient.ResponseStatusCode = 204);
FClient.AddHeader('Content-Type', 'application/json');
Expand Down

0 comments on commit 1225f86

Please sign in to comment.