11import json
2- import os
32from pathlib import Path
43from typing import List , Dict , Optional
5- from datetime import datetime # Import spécifique de la classe datetime
64import logging
75import uuid
86
97from sqlalchemy .orm import Session
108
119from rescue_api .models import Asset , Rescue , Rescuer
10+ from rescue_api .models .mvp_downloader_library import MvpDownloaderLibrary
11+
1212from .payload import AssetModel
1313from .priorizer_client import PriorizerClient
1414
@@ -78,6 +78,14 @@ def _load_json(self, file: Path) -> List[Dict]:
7878 def _save_json (file : Path , data : List [Dict ]):
7979 file .write_text (json .dumps (data , indent = 2 ))
8080
81+ @staticmethod
82+ def _sort_helper (asset : Dict ) -> tuple :
83+ """Helper function to sort by priority (desc) and size (asc)"""
84+ return (
85+ asset ['priority' ],
86+ asset .get ('size' , float ('inf' )) if asset .get ('size' ) is not None else float ('inf' )
87+ )
88+
8189 async def get_available_assets (self ) -> List [Dict ]:
8290 """
8391 Retrieve all assets (without filtering by allocation).
@@ -109,12 +117,12 @@ async def allocate_assets(self, free_space_mb: float, node_id: str = None) -> Di
109117 remaining_space = free_space_mb
110118
111119 # Tri par priorité (desc) puis taille (asc)
112- for asset in sorted (available , key = lambda x : ( x [ 'priority' ], x [ 'size_mb' ]) ):
120+ for asset in sorted (available , key = self . _sort_helper ):
113121 # Asset size may not be known yet
114- if asset ['size_mb ' ] is None or asset ['size_mb ' ] <= remaining_space :
122+ if asset ['size ' ] is None or asset ['size ' ] <= remaining_space :
115123 selected .append (asset )
116- if asset ['size_mb ' ] is not None :
117- remaining_space -= asset ['size_mb ' ]
124+ if asset ['size ' ] is not None :
125+ remaining_space -= asset ['size ' ]
118126
119127 if not selected :
120128 return None
@@ -130,7 +138,7 @@ async def allocate_assets(self, free_space_mb: float, node_id: str = None) -> Di
130138 "res_id" : a ['res_id' ],
131139 "asset_id" : a ['asset_id' ],
132140 "name" : a ['name' ],
133- "size_mb " : float (a ['size_mb ' ]) if a ['size_mb ' ] is not None else None ,
141+ "size " : float (a ['size ' ]) if a ['size ' ] is not None else None ,
134142 "priority" : int (a ['priority' ]),
135143 "url" : a ['url' ]
136144 } for a in selected ]
@@ -140,7 +148,7 @@ async def allocate_assets(self, free_space_mb: float, node_id: str = None) -> Di
140148
141149 return {
142150 "node_id" : node_id ,
143- "allocated_size_mb " : sum (a ['size_mb ' ] for a in selected if a ['size_mb ' ] is not None ),
151+ "allocated_size " : sum (a ['size ' ] for a in selected if a ['size ' ] is not None ),
144152 "assets" : selected ,
145153 "allocation_id" : str (uuid .uuid4 ())
146154 }
@@ -180,6 +188,11 @@ def upsert_rescues_to_db(self, rescuer_id: int, assets: List[AssetModel], db: Se
180188 rescue .magnet_link = asset .magnet_link
181189 rescue .status = asset .status .value .lower ()
182190
191+ # Updating MVP downloader library table with file size
192+ db .query (MvpDownloaderLibrary ) \
193+ .filter (MvpDownloaderLibrary .resource_id == asset .res_id ) \
194+ .update ({'deeplink_file_size' : asset .size })
195+
183196 try :
184197 db .commit ()
185198 except Exception as e :
@@ -212,6 +225,49 @@ def upsert_rescues_to_db(self, rescuer_id: int, assets: List[AssetModel], db: Se
212225 }
213226
214227
228+ def update_mvp_resource_link_as_defective (self , rescuer_id : int , resource_id : int , db : Session ) -> bool :
229+ result = False
230+
231+ if not self ._rescuer_exists (rescuer_id = rescuer_id , db = db ):
232+ logger .error (f"Rescuer with id={ rescuer_id } doesn't exist in the database." )
233+ return False
234+
235+ db .query (MvpDownloaderLibrary ) \
236+ .filter (MvpDownloaderLibrary .resource_id == resource_id ) \
237+ .update ({'defective_link_flag' : True })
238+
239+ # @todo Log update in some table : rescuer, resource, defective, created_at
240+
241+ try :
242+ db .commit ()
243+ result = True
244+ except Exception as e :
245+ print (f'Error while updating res { resource_id } with defective link in MVP Downloader Library' , e )
246+
247+ return result
248+
249+
250+ def update_mvp_resource_link_size (self , rescuer_id : int , resource_id : int , size : int , db : Session ) -> bool :
251+ result = False
252+
253+ if not self ._rescuer_exists (rescuer_id = rescuer_id , db = db ):
254+ logger .error (f"Rescuer with id={ rescuer_id } doesn't exist in the database." )
255+ return False
256+
257+ db .query (MvpDownloaderLibrary ) \
258+ .filter (MvpDownloaderLibrary .resource_id == resource_id ) \
259+ .update ({'deeplink_file_size' : size })
260+
261+ # @todo Log update in some table : rescuer, resource, size, created_at
262+
263+ try :
264+ db .commit ()
265+ result = True
266+ except Exception as e :
267+ print (f'Error while updating res { resource_id } with size { size } in MVP Downloader Library' , e )
268+
269+ return result
270+
215271 @staticmethod
216272 def _rescuer_exists (rescuer_id : int , db : Session ) -> bool :
217273 rescuer = db .query (Rescuer ).filter (Rescuer .id == rescuer_id ).first ()
0 commit comments