Changeset 6645
- Timestamp:
- Jan 18, 2018, 1:34:53 PM (3 years ago)
- Location:
- lliurex-store/trunk/fuentes
- Files:
-
- 1 added
- 10 edited
Legend:
- Unmodified
- Added
- Removed
-
lliurex-store/trunk/fuentes/lliurex-store-cli/usr/share/lliurex-store/lliurex-store-cli.py
r6458 r6645 55 55 else: 56 56 msg=_('available') 57 if data['updatable']: 58 msg +=_(' (updatable)') 57 59 print(_(u'Status')+': '+msg) 58 60 print(_(u'Summary')+': '+data['summary']) … … 66 68 print("") 67 69 except Exception as e: 68 print(e) 69 pass 70 print("CLI: Error printing key %s"%e) 70 71 elif action=='search': 71 72 #Only print name and summary … … 114 115 actions=[] 115 116 parms={} 116 dbg=None 117 bundles=None 117 dbg=False 118 appimage=False 119 snap=False 118 120 args=process_Args(sys.argv) 119 if 'debug' in args: 120 dbg=1 121 122 # if args.bundles: 123 # bundles=1 124 125 ''' if args.debug: 126 actions.append('debug') 127 store.set_debug(args.debug) 128 parms['debug']=args.debug''' 121 if args.debug: 122 dbg=True 123 if args.appimage: 124 appimage=True 125 if args.snap: 126 snap=True 129 127 if args.view: 130 128 actions.append('info') … … 139 137 actions.append('remove') 140 138 parms['remove']=args.remove 139 # if args.list: 140 # actions.append('list') 141 # parms['list']=args.list 141 142 142 143 actionList={'search':False,'info':False,'pkgInfo':False,'install':False,'remove':False,'list':False,'list-sections':False} 143 144 start_time=time.time() 144 store=storeManager.StoreManager( [bundles,dbg])145 store=storeManager.StoreManager(appimage=appimage,snap=snap,dbg=dbg,cli=True) 145 146 for action in actions: 146 147 store.execute_action(action,parms[action]) … … 175 176 parser.add_argument('-i','--install',metavar='Package',help=(_(u"Install a package"))) 176 177 parser.add_argument('-r','--remove',metavar='Package',help=(_(u"Remove a package"))) 177 # parser.add_argument('--debug',action='store_true',help=(_(u"Prints debug information"))) 178 # parser.add_argument('--bundles',action='store_true',help=(_(u"Load app bundles catalog"))) 178 parser.add_argument('--debug',action='store_true',help=(_(u"Prints debug information"))) 179 parser.add_argument('--appimage',action='store_true',help=(_(u"Load appimage catalog"))) 180 parser.add_argument('--snap',action='store_true',help=(_(u"Load snap catalog"))) 181 # parser.add_argument('--list',metavar='list',nargs='?',help=(_(u"List category"))) 179 182 180 183 args=parser.parse_args() -
lliurex-store/trunk/fuentes/python3-lliurex-store.install/usr/share/lliurexstore/plugins/appImageManager.py
r5675 r6645 10 10 import random 11 11 import time 12 import gi 13 from gi.repository import Gio 14 gi.require_version('AppStreamGlib', '1.0') 15 from gi.repository import AppStreamGlib as appstream 16 12 17 class appimagemanager: 13 18 def __init__(self): 14 self.dbg= 019 self.dbg=False 15 20 self.progress=0 21 self.partial_progress=0 16 22 #This dict defines wich package_type relies on what action 17 23 #action=example 18 24 #package='*' (in this case all packages) 19 self.plugin Info={'install':'appimage','remove':'appimage','pkginfo':'appimage'}25 self.plugin_actions={'install':'appimage','remove':'appimage','pkginfo':'appimage','load':'appimage'} 20 26 self.result={} 21 27 self.result['data']={} 22 28 self.result['status']={} 23 self.appImageFolder='/opt/bundles/appimg' 24 self.repoPage='https://dl.bintray.com/probono/AppImages' 29 self.bundles_dir="/var/lib/lliurexstore/bundles" 30 self.bundle_types=['appimg'] 31 self.appimage_dir='/opt/bundles/appimg' 32 self.repository_url='https://dl.bintray.com/probono/AppImages' 25 33 #To get the description of an app we must go to a specific url. 26 34 #$(appname) we'll be replaced with the appname so the url matches the right one. 27 35 #If other site has other url naming convention it'll be mandatory to define it with the appropiate replacements 28 self.infoPage='https://bintray.com/probono/AppImages/$(appname)' 36 self.info_url='https://bintray.com/probono/AppImages/$(appname)' 37 self.disabled=False 29 38 self.count=0 30 self.disabled=True31 39 #def __init__ 32 40 33 def set_debug(self,dbg= '1'):34 self.dbg= int(dbg)41 def set_debug(self,dbg=True): 42 self.dbg=dbg 35 43 self._debug ("Debug enabled") 36 44 #def set_debug 37 45 38 46 def _debug(self,msg=''): 39 if self.dbg ==1:40 print ('DEBUG app Img: '+msg)47 if self.dbg: 48 print ('DEBUG appimage: '+msg) 41 49 #def debug 42 50 43 51 def register(self): 44 return(self.pluginInfo) 45 46 def execute_action(self,action,applist=None): 47 self._chk_installDir() 52 return(self.plugin_actions) 53 54 def enable(self,state=False): 55 self.disable=state 56 57 def execute_action(self,action,applist=None,store=None): 58 if store: 59 self.store=store 60 else: 61 self.store=appstream.Store() 48 62 self.progress=0 49 63 self.result['status']={'status':-1,'msg':''} 50 self.result['data']= list(applist)64 self.result['data']='' 51 65 dataList=[] 52 66 if self.disabled: 53 67 self._set_status(9) 68 self.result['data']=self.store 54 69 else: 55 for appInfo in applist: 56 if action=='install': 57 dataList.append(self._install_appImg(appInfo)) 58 if action=='remove': 59 dataList.append(self._remove_appImg(appInfo)) 60 if action=='pkginfo': 61 dataList.append(self._get_info(appInfo)) 62 self.result['data']=list(dataList) 70 self._chk_installDir() 71 if action=='load': 72 self.result['data']=self._load_appimage_store(self.store) 73 else: 74 for app_info in applist: 75 self.partial_progress=0 76 if action=='install': 77 dataList.append(self._install_appimage(app_info)) 78 if action=='remove': 79 dataList.append(self._remove_appimage(app_info)) 80 if action=='pkginfo': 81 dataList.append(self._get_info(app_info)) 82 self.progress+=int(self.partial_progress/len(applist)) 83 self.result['data']=list(dataList) 63 84 self.progress=100 64 85 return(self.result) … … 83 104 def _chk_installDir(self): 84 105 msg_status=True 85 if not os.path.isdir(self.app ImageFolder):86 try: 87 os.makedirs(self.app ImageFolder)106 if not os.path.isdir(self.appimage_dir): 107 try: 108 os.makedirs(self.appimage_dir) 88 109 except: 89 110 msg_status=False 90 111 return msg_status 91 112 92 def _install_app Img(self,appInfo):93 app Info=self._get_info(appInfo)94 if app Info['state']=='installed':113 def _install_appimage(self,app_info): 114 app_info=self._get_info(app_info) 115 if app_info['state']=='installed': 95 116 self._set_status(4) 96 117 else: 97 app ImgUrl=self.repoPage+'/'+appInfo['appImage']98 self._debug("Downloading "+app ImgUrl)99 dest_path=self.app ImageFolder+'/'+appInfo['appImage']100 if app ImgUrl:118 appimage_url=self.repository_url+'/'+app_info['package'] 119 self._debug("Downloading "+appimage_url) 120 dest_path=self.appimage_dir+'/'+app_info['package'] 121 if appimage_url: 101 122 try: 102 with urllib.request.urlopen(app ImgUrl) as response, open(dest_path, 'wb') as out_file:123 with urllib.request.urlopen(appimage_url) as response, open(dest_path, 'wb') as out_file: 103 124 bf=16*1024 104 125 acumbf=0 105 app Size=int(response.info()['Content-Length'])126 app_size=int(response.info()['Content-Length']) 106 127 while True: 107 if acumbf>=app Size:128 if acumbf>=app_size: 108 129 break 109 130 shutil.copyfileobj(response, out_file,bf) 110 131 acumbf=acumbf+bf 111 self._callback(acumbf,app Size)132 self._callback(acumbf,app_size) 112 133 st = os.stat(dest_path) 113 134 os.chmod(dest_path, st.st_mode | 0o111) … … 117 138 else: 118 139 self._set_status(12) 119 return app Info120 #def _install_app Img121 122 def _remove_app Img(self,appInfo):123 self._debug("Removing "+app Info['appImage'])124 if os.path.isfile(self.app ImageFolder+'/'+appInfo['appImage']):125 try: 126 call([self.app ImageFolder+"/"+appInfo['appImage'], "--remove-appimage-desktop-integration"])140 return app_info 141 #def _install_appimage 142 143 def _remove_appimage(self,app_info): 144 self._debug("Removing "+app_info['package']) 145 if os.path.isfile(self.appimage_dir+'/'+app_info['package']): 146 try: 147 call([self.appimage_dir+"/"+app_info['package'], "--remove-appimage-desktop-integration"]) 127 148 except: 128 149 pass 129 150 try: 130 os.remove(self.app ImageFolder+"/"+appInfo['appImage'])151 os.remove(self.appimage_dir+"/"+app_info['package']) 131 152 self._set_status(0) 132 153 except: 133 154 self._set_status(6) 134 return(appInfo) 135 #def _remove_appImg 136 137 def _get_info(self,appInfo): 138 appInfo['state']='available' 139 if os.path.isfile(self.appImageFolder+'/'+appInfo['appImage']): 140 appInfo['state']='installed' 155 return(app_info) 156 #def _remove_appimage 157 158 def _get_info(self,app_info): 159 app_info['state']='available' 160 if os.path.isfile(self.appimage_dir+'/'+app_info['package']): 161 app_info['state']='installed' 162 #Get size 163 appimage_url=self.repository_url+'/'+app_info['package'] 164 dest_path=self.appimage_dir+'/'+app_info['package'] 165 if appimage_url: 166 try: 167 with urllib.request.urlopen(appimage_url) as response: 168 app_info['size']=(response.info()['Content-Length']) 169 except: 170 app_info['size']=0 141 171 self._set_status(0) 142 return(appInfo) 172 self.partial_progress=100 173 return(app_info) 143 174 #def _get_info 144 175 176 def _load_appimage_store(self,store): 177 self._download_bundles_catalogue() 178 if os.path.exists(self.bundles_dir): 179 for bundle_type in self.bundle_types: 180 self._debug("Loading %s catalog"%bundle_type) 181 store=self._generic_file_load(self.bundles_dir+'/'+bundle_type,store) 182 return(store) 183 #def load_bundles_catalog(self) 184 185 def _generic_file_load(self,target_path,store): 186 icon_path='/usr/share/icons/hicolor/128x128' 187 if not os.path.isdir(target_path): 188 os.makedirs(target_path) 189 files=os.listdir(target_path) 190 for target_file in os.listdir(target_path): 191 if target_file.endswith('appdata.xml'): 192 store_path=Gio.File.new_for_path(target_path+'/'+target_file) 193 self._debug("Adding file "+target_path+'/'+target_file) 194 try: 195 store.from_file(store_path,icon_path,None) 196 except Exception as e: 197 self._debug("Couldn't add file "+target_file+" to store") 198 self._debug("Reason: "+str(e)) 199 return(store) 200 #def _generic_file_load 201 202 def _download_bundles_catalogue(self): 203 CURSOR_UP='\033[F' 204 ERASE_LINE='\033[K' 205 content='' 206 applist=[] 207 progress_bar="#" 208 repositories_list={'appimg':['https://dl.bintray.com/probono/AppImages']} 209 #For get the description of an app we must go to a specific url. 210 #$(appname) we'll be replaced with the appname so the url matches the right one. 211 #If other site has other url naming convention it'll be mandatory to define it with the appropiate replacements 212 info_list={'appimg':'https://bintray.com/probono/AppImages/$(appname)'} 213 self.descriptions_dict={} 214 215 for repo_type,repo_types in repositories_list.items(): 216 info_url=info_list[repo_type] 217 outdir=self.bundles_dir+'/'+repo_type+'/' 218 if self._chk_bundle_dir(outdir): 219 for repo in repo_types: 220 self._debug(("Fetching repo %s")%(repo)) 221 # print (("Fetching %s catalogue: "+progress_bar)%repo_type,end="\r") 222 # progress_bar=progress_bar+"#" 223 # print (("Fetching %s catalogue: "+progress_bar)%repo_type,end="\r") 224 applist=self._generate_applist(self._fetch_repo(repo)) 225 # progress_bar=progress_bar+"##" 226 # print (("Fetching %s catalogue: "+progress_bar)%repo_type,end="\r") 227 self._debug("Processing info...") 228 self._th_generate_xml_catalog(applist,outdir,info_url,repo_type,progress_bar) 229 self._debug("Fetched repo "+repo) 230 # print (("Removing old entries...")) 231 self._clean_bundle_catalogue(applist,outdir) 232 else: 233 self._debug("appImage catalogue could not be fetched: Permission denied") 234 return(True) 235 #def _download_bundles_catalogue 236 237 def _chk_bundle_dir(self,outdir): 238 msg_status=True 239 if not os.path.isdir(outdir): 240 try: 241 os.makedirs(outdir) 242 except: 243 msg_status=False 244 return(os.access(outdir,os.W_OK|os.R_OK|os.X_OK|os.F_OK)) 245 #def _chk_bundle_dir 246 247 def _fetch_repo(self,repo): 248 with urllib.request.urlopen(repo) as f: 249 content=(f.read().decode('utf-8')) 250 return(content) 251 #def _fetch_repo 252 253 def _generate_applist(self,content): 254 garbage_list=[] 255 applist=[] 256 garbage_list=content.split(' ') 257 for garbage_line in garbage_list: 258 if garbage_line.endswith('AppImage"'): 259 app=garbage_line.replace('href=":','') 260 applist.append(app.replace('"','')) 261 return(applist) 262 #def _generate_applist 263 264 def _th_generate_xml_catalog(self,applist,outdir,info_url,repo_type,progress_bar=''): 265 CURSOR_UP='\033[F' 266 ERASE_LINE='\033[K' 267 maxconnections = 10 268 semaphore = threading.BoundedSemaphore(value=maxconnections) 269 random_applist = list(applist) 270 random.shuffle(random_applist) 271 len_applist=len(random_applist) 272 inc=30/len_applist 273 # print (CURSOR_UP) 274 for app in random_applist: 275 th=threading.Thread(target=self._th_write_xml, args = (app,outdir,info_url,semaphore,inc)) 276 th.start() 277 # os.system('setterm -cursor off') 278 while threading.active_count()>2: #Discard both main and own threads 279 for i in range(len(progress_bar),int(self.progress)): 280 progress_bar='#'+progress_bar 281 # print (CURSOR_UP) 282 # print (("Fetching %s catalogue: "+progress_bar)%repo_type,end="\r") 283 # os.system('setterm -cursor on') 284 #def _th_generate_xml_catalog 285 286 def _th_write_xml(self,app,outdir,info_url,semaphore,inc): 287 semaphore.acquire() 288 lock=threading.Lock() 289 name_splitted=app.split('-') 290 name=name_splitted[0] 291 version=name_splitted[1] 292 arch=name_splitted[2] 293 filename=outdir+app.lower().replace('appimage',"appdata.xml") 294 self._debug("checking if we need to download "+filename) 295 if not os.path.isfile(filename): 296 self._write_xml_file(filename,app,name,version,info_url,lock) 297 with lock: 298 self.progress=self.progress+inc 299 semaphore.release() 300 #def _th_write_xml 301 302 def _write_xml_file(self,filename,app,name,version,info_url,lock): 303 self._debug("Generating "+app+" xml") 304 f=open(filename,'w') 305 f.write('<?xml version="1.0" encoding="UTF-8"?>'+"\n") 306 f.write("<components version=\"0.10\">\n") 307 f.write("<component type=\"desktop-application\">\n") 308 f.write(" <id>"+app.lower()+"</id>\n") 309 f.write(" <pkgname>"+app+"</pkgname>\n") 310 f.write(" <name>"+name+"</name>\n") 311 f.write(" <metadata_license>CC0-1.0</metadata_license>\n") 312 f.write(" <provides><binary>"+app+"</binary></provides>\n") 313 f.write(" <releases>\n") 314 f.write(" <release version=\""+version+"\" timestamp=\"1408573857\"></release>\n") 315 f.write(" </releases>\n") 316 f.write(" <launchable type=\"desktop-id\">"+name+".desktop</launchable>\n") 317 with lock: 318 try: 319 if name in self.descriptions_dict.keys(): 320 description=self.descriptions_dict[name] 321 else: 322 description=self._get_description(name,info_url) 323 self.descriptions_dict.update({name:description}) 324 except: 325 description='' 326 summary=' '.join(list(description.split(' ')[:8])) 327 description="This is an AppImage bundle of app "+name+". It hasn't been tested by our developers and comes from a 3rd party dev team. Please use it carefully." 328 if not summary: 329 summary=' '.join(list(description.split(' ')[:8])) 330 f.write(" <description><p></p><p>"+description+"</p></description>\n") 331 f.write(" <summary>"+summary+"...</summary>\n") 332 f.write(" <bundle type=\"appimage\">"+app+"</bundle>\n") 333 f.write(" <keywords>\n") 334 f.write(" <keyword>"+name+"</keyword>\n") 335 f.write(" <keyword>appimage</keyword>\n") 336 f.write(" </keywords>\n") 337 f.write(" <categories>\n") 338 f.write(" <category>AppImage</category>\n") 339 # f.write(" <category>GTK</category>\n") 340 f.write(" </categories>\n") 341 f.write("<icon type=\"cached\">"+name+"_"+name+".png</icon>\n") 342 f.write("</component>\n") 343 f.write("</components>\n") 344 f.close() 345 #def _write_xml_file 346 347 def _get_description(self,app_name,info_url): 348 desc='' 349 if '$(appname)' in info_url: 350 info_url=info_url.replace('$(appname)',app_name) 351 self._debug("Getting description from "+info_url) 352 try: 353 with urllib.request.urlopen(info_url) as f: 354 content=(f.read().decode('utf-8')) 355 soup=BeautifulSoup(content,"html.parser") 356 description_div=soup.findAll('div', attrs={ "class" : "description-text"}) 357 if len(description_div)>0: 358 desc=description_div[0].text 359 desc=desc.replace(':','.') 360 desc=desc.replace('&','&') 361 except Exception as e: 362 print("Can't get description from "+info_url) 363 print(str(e)) 364 pass 365 return(desc) 366 #def _get_description 367 368 def _clean_bundle_catalogue(self,applist,outdir): 369 xml_files_list=[] 370 applist=[item.lower() for item in applist] 371 for xml_file in os.listdir(outdir): 372 if xml_file.endswith('appdata.xml'): 373 xml_files_list.append(xml_file.lower().replace('appdata.xml','appimage')) 374 375 if xml_files_list: 376 xml_discard_list=list(set(xml_files_list).difference(applist)) 377 for discarded_file in xml_discard_list: 378 os.remove(outdir+'/'+discarded_file.replace('appimage','appdata.xml')) 379 #def _clean_bunlde_catalogue 380 -
lliurex-store/trunk/fuentes/python3-lliurex-store.install/usr/share/lliurexstore/plugins/debManager.py
r5187 r6645 6 6 def __init__(self): 7 7 self.installer='' 8 self.dbg= 08 self.dbg=False 9 9 self.pkgList=[] 10 10 self.result=[] 11 11 self.progress=0 12 self.partialProgress=0 13 #self.pluginInfo=['install','deb','remove','deb','pkginfo','deb','remove','zmd'] 14 self.pluginInfo={'install':'deb','remove':'deb','pkginfo':'deb'} 12 self.partial_progress=0 13 self.plugin_actions={'install':'deb','remove':'deb','pkginfo':'deb'} 15 14 self.result={} 16 15 self.result['data']={} … … 19 18 #def __init__ 20 19 21 def set_debug(self,dbg= '1'):22 self.dbg= int(dbg)20 def set_debug(self,dbg=True): 21 self.dbg=dbg 23 22 self._debug ("Debug enabled") 24 23 #def set_debug 25 24 26 25 def _debug(self,msg=''): 27 if self.dbg ==1:26 if self.dbg: 28 27 print ('DEBUG Deb: '+str(msg)) 29 28 #def debug … … 35 34 36 35 def register(self): 37 return(self.plugin Info)36 return(self.plugin_actions) 38 37 #def register 39 38 … … 47 46 processedPkg=[] 48 47 #1.- If the app doesn't exist cancel the action 49 for app Info in applist:50 if app Info['package'] not in processedPkg:51 processedPkg.append(app Info['package'])48 for app_info in applist: 49 if app_info['package'] not in processedPkg: 50 processedPkg.append(app_info['package']) 52 51 filters=1 53 52 if action=='remove': 54 53 filters=2 55 app=self._resolve_App(app Info['package'],filters)54 app=self._resolve_App(app_info['package'],filters) 56 55 if app: 57 56 if action=='install': 58 self._log("Installing "+app Info['package'])57 self._log("Installing "+app_info['package']) 59 58 self._install_App(app) 60 self.result['data'].append({'package':app Info['package']})59 self.result['data'].append({'package':app_info['package']}) 61 60 if action=='remove': 62 self._log("Removing "+app Info['package'])61 self._log("Removing "+app_info['package']) 63 62 self._remove_App(app) 64 self.result['data'].append({'package':app Info['package']})63 self.result['data'].append({'package':app_info['package']}) 65 64 if action=='pkginfo': 66 self._log("Looking "+app Info['package'])67 self.result['data'].append(self._get_App_Extended_Info(app Info,app))68 self.progress=self.progress+(self.partial Progress/self.count)65 self._log("Looking "+app_info['package']) 66 self.result['data'].append(self._get_App_Extended_Info(app_info,app)) 67 self.progress=self.progress+(self.partial_progress/self.count) 69 68 self.progress=100 70 69 return(self.result) … … 79 78 80 79 def _callback(self,status,typ,data=None): 81 self.partial Progress=status.props.percentage82 self.progress=self.partial Progress/self.count80 self.partial_progress=status.props.percentage 81 self.progress=self.partial_progress/self.count 83 82 #def _callback 84 83 … … 95 94 err=e.code 96 95 finally: 97 self.partial Progress=10096 self.partial_progress=100 98 97 self._set_status(err) 99 98 return err … … 109 108 self._set_status(e.code) 110 109 finally: 111 self.partial Progress=100110 self.partial_progress=100 112 111 #def _remove_App 113 112 114 def _get_App_Extended_Info(self,app Info,app):113 def _get_App_Extended_Info(self,app_info,app): 115 114 self._debug("Getting dependencies for "+app.get_id()) 116 115 pkTask=packagekit.Task() … … 125 124 pass 126 125 if (results): 127 app Info['version']=app.get_version()128 app Info['arch']=app.get_id().split(';')[2]126 app_info['version']=app.get_version() 127 app_info['arch']=app.get_id().split(';')[2] 129 128 for related_app in results.get_package_array(): 130 129 dependsList.append(related_app.get_id()) 131 app Info['depends']=dependsList130 app_info['depends']=dependsList 132 131 #app.get_version() 133 132 try: … … 135 134 except Exception as e: 136 135 # self._set_status(1) 137 print ( str(e))136 print ("ERROR %s"%e) 138 137 pass 139 138 if(results): 140 139 for app_detail in results.get_details_array(): 141 app Info['size']=str(app_detail.get_size())140 app_info['size']=str(app_detail.get_size()) 142 141 break 143 142 try: 144 143 info=app.get_info() 145 appInfo['state']=info.to_string(info) 146 self._debug("State: "+appInfo['state']) 147 except: 144 state=info.to_string(info) 145 if state!=app_info['state'] and app_info['state']=='installed': 146 app_info['updatable']=1 147 else: 148 app_info['state']=state 149 self._debug("State: "+app_info['state']) 150 except Exception as e: 148 151 self._debug("State: not available") 149 pass150 152 151 return(app Info)153 return(app_info) 152 154 #def _get_App_Extended_Info 153 155 154 def _get_App_Info(self,appInfo,app,appsCount=0): #DEPRECATED 155 try: 156 info=app.get_info() 157 appInfo['status']=info.to_string(info) 158 self._debug("Status: "+appInfo['status']) 159 except: 160 self._debug("Status: not available") 161 pass 162 #Only search dependencies if there's only one package on the package queue 163 if appsCount==1: 164 self._debug("loading extended info") 165 appInfo=self._get_App_Extended_Info(appInfo,app) 166 self.partialProgress=100 167 self.result.append(appInfo) 168 # self.result['data'].update({appInfo['package']:appInfo}) 169 self._set_status(0) 170 return(appInfo) 171 #def _get_App_Info 172 173 def _resolve_App(self,appName,filters=False): 174 self._debug("Resolving "+appName) 156 def _resolve_App(self,app_name,filters=1): 157 self._debug("Resolving "+app_name) 175 158 app=None 176 159 resolvelist=[] 177 160 self.return_msg=False 178 if not filters:179 filters=1180 161 try: 181 162 self._debug("Filter for resolver: "+str(filters)) 182 result=self.installer.resolve(filters,[app Name,],None,self._fake_callback, None)163 result=self.installer.resolve(filters,[app_name,],None,self._fake_callback, None) 183 164 resolvelist=result.get_package_array() 184 resolvedApp=resolvelist[0]165 app_resolved=resolvelist[0] 185 166 #resolver bug: filters not work so if we want to remove an app first we must get the installed version... 186 167 if filters==2: 187 168 for app in resolvelist: 188 169 if (str(app.get_info()).find('PK_INFO_ENUM_INSTALLED')!=-1): 189 resolvedApp=app190 if resolvedApp:191 self._debug("Application "+ resolvedApp.get_name()+" resolved succesfully")192 app= resolvedApp170 app_resolved=app 171 if app_resolved: 172 self._debug("Application "+app_resolved.get_name()+" resolved succesfully") 173 app=app_resolved 193 174 except Exception as e: 194 self._debug("Couldn't resolve "+app Name)175 self._debug("Couldn't resolve "+app_name) 195 176 self._debug("Reason: "+str(e)) 196 177 finally: 197 self.partial Progress=100178 self.partial_progress=100 198 179 return(app) 199 180 #def _resolve_App 200 181 -
lliurex-store/trunk/fuentes/python3-lliurex-store.install/usr/share/lliurexstore/plugins/example.py
r5133 r6645 5 5 class example: 6 6 def __init__(self): 7 self.dbg= 07 self.dbg=False 8 8 self.progress=0 9 9 #This dict defines wich package_type relies on what action … … 12 12 #action=example 13 13 #package='*' (in this case all package_types. It could be "deb", "zmd" or whatever package type) 14 self.pluginInfo={'example':'*'} 14 self.plugin_actions={'example':'*'} 15 #This switch enables cli_mode for the plugin, just in case some function difers from the gui mode 16 self.cli_mode=False 17 #This one controls if the plugin is enabled or not 18 #It could be activated from two ways: 19 # - storeManager having a parameter with name=package_type (simply add it to the arg list passed when invoking storeManager) 20 # - Internal failure controls (see zmdManager for an example) 21 #This example plugin is disabled by default 22 self.disabled=True 15 23 #def __init__ 16 24 17 #public function that sets the debug mode. If we execute storeManager in debug mode all plugins will be launched in this mode .18 def set_debug(self,dbg= '1'):25 #public function that sets the debug mode. If we execute storeManager in debug mode all plugins will be launched in this mode if propaate_debug==True 26 def set_debug(self,dbg=True): 19 27 self.dbg=int(dbg) 20 28 self.debug ("Debug enabled") … … 22 30 23 31 def _debug(self,msg=''): 24 if self.dbg ==1:32 if self.dbg: 25 33 print ('DEBUG Example: '+msg) 26 34 #def debug 27 35 28 #public function accessed by s otremanager in order to register the plugin and its actions36 #public function accessed by storemanager in order to register the plugin and its actions 29 37 def register(self): 30 38 #This function MUST return the dict with the action:package_type pair 31 #In this example it returns nothing 32 self.pluginInfo={} 33 return(self.pluginInfo) 39 return(self.plugin_actions) 34 40 35 41 #storeManager calls this method when launchs an action. … … 42 48 self.result['status']={'status':-1,'msg':''} 43 49 self.result['data']='' 44 for app in applist: 45 if action=='example': 46 datalist.append(self._exec_example(app)) 47 self.result['data']=list(dataList) 48 self.progress=100 #When all actions are launched we must assure that progress=100. 50 if self.disabled: 51 self._set_status(9) 52 else: 53 for app in applist: 54 if action=='example': 55 datalist.append(self._exec_example(app)) 56 self.result['data']=list(dataList) 57 self.progress=100 #When all actions are launched we must assure that progress=100. 49 58 return(self.result) 50 59 -
lliurex-store/trunk/fuentes/python3-lliurex-store.install/usr/share/lliurexstore/plugins/infoManager.py
r5674 r6645 3 3 class infomanager: 4 4 def __init__(self): 5 self.dbg= 05 self.dbg=True 6 6 self.pluginInfo={'get_info':'*'} 7 7 # self.pluginInfo={'info':'*','get_info':'*'} … … 14 14 #def __init__ 15 15 16 def set_debug(self,dbg= '1'):17 self.dbg= int(dbg)16 def set_debug(self,dbg=True): 17 self.dbg=dbg 18 18 self._debug ("Debug enabled") 19 19 #def set__debug 20 20 21 21 def _debug(self,msg=''): 22 if self.dbg ==1:22 if self.dbg: 23 23 print ('DEBUG Info: '+str(msg)) 24 24 #def _debug … … 48 48 def _set_locale(self): 49 49 if locale.getdefaultlocale()[0]=="ca_ES": 50 self.locale=['ca_ES@valencia','ca@valencia','qcv','ca','ca_ES','es_ES','es','en_US','en ','C']50 self.locale=['ca_ES@valencia','ca@valencia','qcv','ca','ca_ES','es_ES','es','en_US','en_GB','en','C'] 51 51 else: 52 52 if locale.getdefaultlocale()[0]=="es_ES": 53 self.locale=['es_ES','es','ca_ES@valencia','ca@valencia','qcv','ca','ca_ES','en_US','en ','C']54 else: 55 self.locale=[locale.getlocale()[0],'en_US','en ','ca_ES@valencia','ca@valencia','qcv','ca','es_ES','es','C']53 self.locale=['es_ES','es','ca_ES@valencia','ca@valencia','qcv','ca','ca_ES','en_US','en_GB','en','C'] 54 else: 55 self.locale=[locale.getlocale()[0],'en_US','en_GB','en','ca_ES@valencia','ca@valencia','qcv','ca','es_ES','es','C'] 56 56 #def _set_locale 57 57 … … 64 64 if app.get_id(): 65 65 appInfo['id']=app.get_id() 66 if not appInfo['id'].endswith('desktop'):67 appInfo['id']+='.desktop'68 66 for localeItem in self.locale: 69 67 if app.get_name(localeItem): … … 81 79 appInfo['license']=app.get_project_license() 82 80 else: 81 appInfo['license']='other/restricted' 83 82 orig=app.get_origin() 84 83 if orig: 85 84 if '-main' in orig or '-universe' in orig: 86 85 appInfo['license']='open source' 87 else:88 appInfo['license']='propietary/restricted'89 86 for localeItem in self.locale: 90 87 if app.get_comment(localeItem): … … 156 153 if 'embed' not in appInfo['video']: 157 154 appInfo['video']=appInfo['video'].replace('watch?v=','embed/') 155 #F***g appstream returns unknown for all the possible types 156 # if app.get_bundle_default(): 157 # appInfo['bundle']=app.get_bundle_default().get_kind() 158 #Fix F***g appstream returns unknown for all the possible types 159 #ID must contain bundle type as last field 158 160 for bundle in app.get_bundles(): 159 161 if bundle.get_kind()==0: 160 #F***g appstream returns unknown for all the possible types 161 if bundle.get_id().endswith('AppImage'): 162 appInfo['appImage']=bundle.get_id() 163 else: 162 kind=bundle.get_id().split('.')[-1] 163 appInfo['bundle']=kind.lower() 164 if kind.lower=='sh': 164 165 appInfo['installerUrl']=bundle.get_id() 165 if bundle.get_kind()==6:166 appInfo['appImage']=bundle.get_id()167 166 applistInfo.append(appInfo) 168 167 self._callback_progress() … … 193 192 'extraInfo':'',\ 194 193 'size':'',\ 195 'appImage':'',\ 194 'bundle':'',\ 195 'updatable':'',\ 196 196 } 197 197 return(appInfo) -
lliurex-store/trunk/fuentes/python3-lliurex-store.install/usr/share/lliurexstore/plugins/loadStore.py
r6547 r6645 17 17 class loadstore: 18 18 def __init__(self): 19 self.dbg= 020 self.plugin Info={'load':'*','load_bundles':'*'}19 self.dbg=False 20 self.plugin_actions={'load':'*'} 21 21 self.store='' 22 22 self.progress=0 23 23 self.error=0 24 self.bundleDir="/var/lib/lliurexstore/bundles" 25 self.bundleTypes=['appimg'] 26 self.zmdCatalogueDir='/var/lib/lliurexstore/zmds' 24 self.zmd_store_dir='/var/lib/lliurexstore/zmds' 25 self.result={} 26 self.result['data']={} 27 self.result['status']={} 27 28 #def __init__ 28 29 29 def set_debug(self,dbg= '1'):30 self.dbg= int(dbg)30 def set_debug(self,dbg=True): 31 self.dbg=dbg 31 32 self._debug ("Debug enabled") 32 33 #def set_debug 33 34 34 35 def _debug(self,msg=''): 35 if self.dbg ==1:36 if self.dbg: 36 37 print ('DEBUG Load: '+str(msg)) 37 38 #def _debug 38 39 39 40 def register(self): 40 return(self.plugin Info)41 return(self.plugin_actions) 41 42 #def register 42 43 … … 51 52 if action=='load_bundles': 52 53 self._load_store(self.store,loadBundles=True) 54 # self.progress=100 55 self.result['data']=self.store 53 56 self.progress=100 54 return (self.store) 57 return(self.result) 58 # return (self.store) 55 59 #def execute_action 56 60 … … 60 64 61 65 def _load_store(self,store,loadBundles=False): 62 icon Path='/usr/share/icons/hicolor/128x128'66 icon_dir='/usr/share/icons/hicolor/128x128' 63 67 flags=[appstream.StoreLoadFlags.APP_INFO_SYSTEM,appstream.StoreLoadFlags.APP_INSTALL,appstream.StoreLoadFlags.APP_INFO_USER,appstream.StoreLoadFlags.DESKTOP,appstream.StoreLoadFlags.APPDATA,appstream.StoreLoadFlags.ALLOW_VETO] 64 68 for flag in flags: … … 71 75 store=self.load_zmds_catalog(store) 72 76 store=self._sanitize_store(store) 73 if loadBundles:74 if self._download_bundles_catalogue():75 store=self.load_bundles_catalog(store)76 77 self.store=store 77 78 return(store) 78 79 #def load_store 79 80 80 def load_bundles_catalog(self,store):81 if os.path.exists(self.bundleDir):82 for bundleType in self.bundleTypes:83 store=self._generic_file_load(self.bundleDir+'/'+bundleType,store)84 return(store)85 #def load_bundles_catalog(self)86 87 81 def load_zmds_catalog(self,store): 88 if os.path.exists(self.zmd CatalogueDir):89 store=self._generic_file_load(self.zmd CatalogueDir,store)82 if os.path.exists(self.zmd_store_dir): 83 store=self._generic_file_load(self.zmd_store_dir,store) 90 84 return(store) 91 85 #def load_zmds_catalog(self) 92 86 93 def _generic_file_load(self, filesDir,store):94 icon Path='/usr/share/icons/hicolor/128x128'95 files=os.listdir( filesDir)96 for appFile in os.listdir(filesDir):97 if appFile.endswith('appdata.xml'):98 store Path=Gio.File.new_for_path(filesDir+'/'+appFile)99 self._debug("Adding file "+ filesDir+'/'+appFile)87 def _generic_file_load(self,target_dir,store): 88 icon_dir='/usr/share/icons/hicolor/128x128' 89 files=os.listdir(target_dir) 90 for target_file in os.listdir(target_dir): 91 if target_file.endswith('appdata.xml'): 92 store_file=Gio.File.new_for_path(target_dir+'/'+target_file) 93 self._debug("Adding file "+target_dir+'/'+target_file) 100 94 try: 101 store.from_file(store Path,iconPath,None)95 store.from_file(store_file,icon_dir,None) 102 96 except Exception as e: 103 self._debug("Couldn't add file "+ appFile+" to store")97 self._debug("Couldn't add file "+target_file+" to store") 104 98 self._debug("Reason: "+str(e)) 105 99 return(store) 106 100 107 101 def _parse_desktop(self,store): #DEPRECATED. Loads the apps from the available desktop files 108 desktop Dir='/usr/share/applications'102 desktop_dir='/usr/share/applications' 109 103 applist=[] 110 for desktop File in os.listdir(desktopDir):111 if desktop File.endswith('desktop'):104 for desktop_file in os.listdir(desktop_dir): 105 if desktop_file.endswith('desktop'): 112 106 a=appstream.App() 113 107 try: 114 a.parse_file(desktop Dir+'/'+desktopFile,16)108 a.parse_file(desktop_dir+'/'+desktop_file,16) 115 109 a.set_priority(0) 116 110 for veto in a.get_vetos(): 117 111 a.remove_veto(veto) 118 112 store.add_app(a) 119 self._debug("Adding app from desktop "+desktop File)113 self._debug("Adding app from desktop "+desktop_file) 120 114 except: 121 115 pass … … 125 119 def _sanitize_store(self,store): 126 120 applist=store.get_apps() 127 uniqDict={}128 lliurex Apps={}129 zmd List=[]121 tmp_store_apps={} 122 lliurex_apps={} 123 zmd_apps=[] 130 124 for app in applist: 131 125 #Zomandos get max priority … … 133 127 self._debug("Prioritize zmd "+str(app.get_id())) 134 128 app.set_priority(400) 135 lliurex Apps.update({app.get_id_filename():app})136 id =str(app.get_id_filename()).replace('zero-lliurex-','')137 zmd List.append(id)129 lliurex_apps.update({app.get_id_filename():app}) 130 id_app=str(app.get_id_filename()).replace('zero-lliurex-','') 131 zmd_apps.append(id_app) 138 132 #Prioritize Lliurex apps 139 133 elif app.has_category('Lliurex'): 140 134 self._debug("Prioritize app "+str(app.get_id())) 141 135 app.set_priority(200) 142 lliurex Apps.update({app.get_id_filename():app})136 lliurex_apps.update({app.get_id_filename():app}) 143 137 elif str(app.get_origin()).find('lliurex')>=0: 144 138 self._debug("Prioritize app "+app.get_id()) 145 139 app.set_priority(100) 146 lliurex Apps.update({app.get_id_filename():app})140 lliurex_apps.update({app.get_id_filename():app}) 147 141 else: 148 142 app.set_priority(0) 149 if app.get_id_filename() in lliurex Apps.keys():143 if app.get_id_filename() in lliurex_apps.keys(): 150 144 self._debug("Mergin app "+str(app.get_id())+" as is in Lliurex") 151 lliurex Apps[app.get_id_filename()].subsume_full(app,appstream.AppSubsumeFlags.BOTH_WAYS)145 lliurex_apps[app.get_id_filename()].subsume_full(app,appstream.AppSubsumeFlags.BOTH_WAYS) 152 146 store.remove_app(app) 153 147 #Remove apps whitout pkgname … … 161 155 #Unlike gnome-store we'll try to compare the info of the package in order of discard only the "part-of" packages 162 156 pkg=app.get_pkgname_default() 163 if pkg in uniqDict.keys():157 if pkg in tmp_store_apps.keys(): 164 158 fn=app.get_id_no_prefix() 165 self._debug("Comparing "+fn+" with "+ uniqDict[pkg]['fn'])166 if fn != uniqDict[pkg]['fn']:159 self._debug("Comparing "+fn+" with "+tmp_store_apps[pkg]['fn']) 160 if fn != tmp_store_apps[pkg]['fn']: 167 161 if fn != pkg and ".desktop" not in fn: 168 162 self._debug("Removed duplicated "+app.get_id()) 169 163 store.remove_app(app) 170 164 else: 171 self._debug("Removed duplicated "+ uniqDict[pkg]['app'].get_id())172 store.remove_app( uniqDict[pkg]['app'])173 uniqDict.update({pkg:{'fn':app.get_id_no_prefix(),'app':app}})165 self._debug("Removed duplicated "+tmp_store_apps[pkg]['app'].get_id()) 166 store.remove_app(tmp_store_apps[pkg]['app']) 167 tmp_store_apps.update({pkg:{'fn':app.get_id_no_prefix(),'app':app}}) 174 168 elif pkg: 175 169 # self._debug("Adding "+app.get_id_filename()+" to uniq dict") 176 uniqDict.update({pkg:{'fn':app.get_id_filename(),'app':app}})170 tmp_store_apps.update({pkg:{'fn':app.get_id_filename(),'app':app}}) 177 171 #Delete zomando-related debs 178 store=self._purge_zomandos(zmd List,store)172 store=self._purge_zomandos(zmd_apps,store) 179 173 #Check the blacklist 180 174 store=self._apply_blacklist(store) … … 182 176 #def _sanitize_store 183 177 184 def _purge_zomandos(self,zmd List,store):185 for appId in zmdList:186 self._debug("Searching debs related to "+ appId)187 purge List=store.get_apps_by_id(appId)188 purge List.extend(store.get_apps_by_id(appId+".desktop"))189 for purge App in purgeList:190 if purge App:191 if not purge App.has_category('Zomando'):192 self._debug("Removed related zomando app "+str(purge App.get_id()))193 store.remove_app(purge App)178 def _purge_zomandos(self,zmd_apps,store): 179 for zmd_id in zmd_apps: 180 self._debug("Searching debs related to "+zmd_id) 181 purge_list=store.get_apps_by_id(zmd_id) 182 purge_list.extend(store.get_apps_by_id(zmd_id+".desktop")) 183 for purge_app in purge_list: 184 if purge_app: 185 if not purge_app.has_category('Zomando'): 186 self._debug("Removed related zomando app "+str(purge_app.get_id())) 187 store.remove_app(purge_app) 194 188 return(store) 195 189 #def _purge_zomandos … … 209 203 blFile=open('/usr/share/lliurex-store/files/blacklist.json').read() 210 204 blacklist=json.loads(blFile) 211 bl Apps=[]205 blacklist_apps=[] 212 206 if flavour in blacklist: 213 bl Apps=blacklist[flavour]207 blacklist_apps=blacklist[flavour] 214 208 if "all" in blacklist: 215 bl Apps.extend(blacklist["all"])216 bl RegEx=[]217 for bl App in blApps:218 self._debug("Blacklisted app: "+bl App)219 re sultRe=re.search('([^a-zA-Z0-9_-])',blApp)220 if re sultRe:221 if bl App[0]=='*':222 bl App='.'+blApp223 bl RegEx.append("("+blApp+")")209 blacklist_apps.extend(blacklist["all"]) 210 blacklist_re=[] 211 for blacklist_app in blacklist_apps: 212 self._debug("Blacklisted app: "+blacklist_app) 213 re_result=re.search('([^a-zA-Z0-9_-])',blacklist_app) 214 if re_result: 215 if blacklist_app[0]=='*': 216 blacklist_app='.'+blacklist_app 217 blacklist_re.append("("+blacklist_app+")") 224 218 else: 225 app=store.get_app_by_pkgname(bl App)219 app=store.get_app_by_pkgname(blacklist_app) 226 220 if app: 227 221 self._debug("Removed "+str(app)) 228 222 store.remove_app(app) 229 223 else: 230 self._debug("App "+bl App+" from blacklist not found in store. Assigned to RE blacklist")231 bl RegEx.append("("+blApp+")")232 if bl RegEx:224 self._debug("App "+blacklist_app+" from blacklist not found in store. Assigned to RE blacklist") 225 blacklist_re.append("("+blacklist_app+")") 226 if blacklist_re: 233 227 self._debug("Attempting to remove apps by RE match") 234 228 for app in store.get_apps(): 235 for bl App in blRegEx:236 re sultRe=re.search(blApp,app.get_id())237 if re sultRe:229 for blacklist_app in blacklist_re: 230 re_result=re.search(blacklist_app,app.get_id()) 231 if re_result: 238 232 store.remove_app(app) 239 self._debug("Removed "+str(app.get_id()) +" as matches with "+bl App)233 self._debug("Removed "+str(app.get_id()) +" as matches with "+blacklist_app) 240 234 else: 241 235 self._debug('No blacklist to check') … … 246 240 #def _apply_blacklist 247 241 248 def _download_bundles_catalogue(self):249 CURSOR_UP='\033[F'250 ERASE_LINE='\033[K'251 content=''252 applist=[]253 progressBar="#"254 repoList={'appimg':['https://dl.bintray.com/probono/AppImages']}255 #For get the description of an app we must go to a specific url.256 #$(appname) we'll be replaced with the appname so the url matches the right one.257 #If other site has other url naming convention it'll be mandatory to define it with the appropiate replacements258 infoList={'appimg':'https://bintray.com/probono/AppImages/$(appname)'}259 self.descDict={}260 261 for repoType,repoTypeList in repoList.items():262 infoPage=infoList[repoType]263 outdir=self.bundleDir+'/'+repoType+'/'264 if self._chk_bundle_dir(outdir):265 for repo in repoTypeList:266 self._debug(("Fetching repo %s")%(repo))267 # print (("Fetching %s catalogue: "+progressBar)%repoType,end="\r")268 # progressBar=progressBar+"#"269 # print (("Fetching %s catalogue: "+progressBar)%repoType,end="\r")270 applist=self._generate_applist(self._fetch_repo(repo))271 # progressBar=progressBar+"##"272 # print (("Fetching %s catalogue: "+progressBar)%repoType,end="\r")273 self._debug("Processing info...")274 self._th_generate_xml_catalog(applist,outdir,infoPage,repoType,progressBar)275 self._debug("Fetched repo "+repo)276 # print (("Removing old entries..."))277 self._clean_bundle_catalogue(applist,outdir)278 else:279 print("permission denied")280 return(True)281 282 def _chk_bundle_dir(self,outdir):283 msg_status=True284 if not os.path.isdir(outdir):285 try:286 os.makedirs(outdir)287 except:288 msg_status=False289 return(os.access(outdir,os.W_OK|os.R_OK|os.X_OK|os.F_OK))290 291 def _fetch_repo(self,repo):292 with urllib.request.urlopen(repo) as f:293 content=(f.read().decode('utf-8'))294 return(content)295 296 def _generate_applist(self,content):297 garbageList=[]298 applist=[]299 garbageList=content.split(' ')300 for garbageLine in garbageList:301 if garbageLine.endswith('AppImage"'):302 app=garbageLine.replace('href=":','')303 applist.append(app.replace('"',''))304 return(applist)305 306 def _th_generate_xml_catalog(self,applist,outdir,infoPage,repoType,progressBar=''):307 CURSOR_UP='\033[F'308 ERASE_LINE='\033[K'309 oldName=''310 oldDesc=''311 maxconnections = 10312 semaphore = threading.BoundedSemaphore(value=maxconnections)313 randomList = list(applist)314 random.shuffle(randomList)315 lenAppList=len(randomList)316 inc=30/lenAppList317 # print (CURSOR_UP)318 for app in randomList:319 th=threading.Thread(target=self._th_write_xml, args = (app,outdir,infoPage,semaphore,inc))320 th.start()321 os.system('setterm -cursor off')322 while threading.active_count()>2: #Discard both main and own threads323 for i in range(len(progressBar),int(self.progress)):324 progressBar='#'+progressBar325 # print (CURSOR_UP)326 # print (("Fetching %s catalogue: "+progressBar)%repoType,end="\r")327 os.system('setterm -cursor on')328 print('')329 330 def _th_write_xml(self,app,outdir,infoPage,semaphore,inc):331 semaphore.acquire()332 lock=threading.Lock()333 nameSplitted=app.split('-')334 name=nameSplitted[0]335 version=nameSplitted[1]336 arch=nameSplitted[2]337 filename=outdir+app.lower().replace('appimage',"appdata.xml")338 self._debug("checking if we need to download "+filename)339 if not os.path.isfile(filename):340 self._debug("Generating "+app+" xml")341 f=open(filename,'w')342 f.write('<?xml version="1.0" encoding="UTF-8"?>'+"\n")343 f.write("<components version=\"0.10\">\n")344 f.write("<component type=\"desktop-application\">\n")345 f.write(" <id>"+app.lower()+"</id>\n")346 f.write(" <pkgname>"+app+"</pkgname>\n")347 f.write(" <name>"+name+"</name>\n")348 f.write(" <metadata_license>CC0-1.0</metadata_license>\n")349 f.write(" <provides><binary>"+app+"</binary></provides>\n")350 f.write(" <releases>\n")351 f.write(" <release version=\""+version+"\" timestamp=\"1408573857\"></release>\n")352 f.write(" </releases>\n")353 f.write(" <launchable type=\"desktop-id\">"+name+".desktop</launchable>\n")354 with lock:355 if name in self.descDict.keys():356 description=self.descDict[name]357 else:358 description=self._get_description(name,infoPage)359 self.descDict.update({name:description})360 summary=' '.join(list(description.split(' ')[:8]))361 description="This is an AppImage bundle of app "+name+". It hasn't been tested by our developers and comes from a 3rd party dev team. Please use it carefully."362 if not summary:363 summary=' '.join(list(description.split(' ')[:8]))364 f.write(" <description><p></p><p>"+description+"</p></description>\n")365 f.write(" <summary>"+summary+"...</summary>\n")366 f.write(" <bundle type=\"appimage\">"+app+"</bundle>\n")367 f.write(" <keywords>\n")368 f.write(" <keyword>"+name+"</keyword>\n")369 f.write(" <keyword>appimage</keyword>\n")370 f.write(" </keywords>\n")371 f.write(" <categories>\n")372 f.write(" <category>AppImage</category>\n")373 f.write(" <category>GTK</category>\n")374 f.write(" </categories>\n")375 f.write("<icon type=\"cached\">"+name+"_"+name+".png</icon>\n")376 f.write("</component>\n")377 f.write("</components>\n")378 f.close()379 with lock:380 self.progress=self.progress+inc381 semaphore.release()382 383 def _get_description(self,appName,infoPage):384 desc=''385 if '$(appname)' in infoPage:386 infoPage=infoPage.replace('$(appname)',appName)387 self._debug("Getting description from "+infoPage)388 try:389 with urllib.request.urlopen(infoPage) as f:390 content=(f.read().decode('utf-8'))391 soup=BeautifulSoup(content,"html.parser")392 descDiv=soup.findAll('div', attrs={ "class" : "description-text"})393 if len(descDiv)>0:394 desc=descDiv[0].text395 desc=desc.replace(':','.')396 desc=desc.replace('&','&')397 except Exception as e:398 print("Can't get description from "+infoPage)399 print(str(e))400 pass401 return(desc)402 403 def _clean_bundle_catalogue(self,applist,outdir):404 xmlList=[]405 applist=[item.lower() for item in applist]406 for xmlFile in os.listdir(outdir):407 if xmlFile.endswith('appdata.xml'):408 xmlList.append(xmlFile.lower().replace('appdata.xml','appimage'))409 410 if xmlList:411 discardList=list(set(xmlList).difference(applist))412 for discardFile in discardList:413 os.remove(outdir+'/'+discardFile.replace('appimage','appdata.xml'))414 #def _clean_appImg_repo415 -
lliurex-store/trunk/fuentes/python3-lliurex-store.install/usr/share/lliurexstore/plugins/searchManager.py
r6547 r6645 7 7 def __init__(self): 8 8 self.locale=locale.getlocale()[0] 9 self.dbg= 09 self.dbg=False 10 10 self.store='' 11 self.plugin Info={'search':'*','list':'*','list_sections':'*','info':'*'}12 self.precision=1 011 self.plugin_actions={'search':'*','list':'*','list_sections':'*','info':'*'} 12 self.precision=1 13 13 self.applist=[] 14 14 self.progress=0 … … 21 21 return (self.applist) 22 22 23 def set_debug(self,dbg ='1'):24 self.dbg= int(dbg)23 def set_debug(self,dbg): 24 self.dbg=dbg 25 25 self._debug ("Debug enabled") 26 26 #def set__debug 27 27 28 28 def _debug(self,msg=''): 29 if self.dbg ==1:29 if self.dbg: 30 30 print ('DEBUG Search: '+msg) 31 31 #def _debug 32 32 33 33 def register(self): 34 return(self.plugin Info)35 36 def execute_action(self,appstreamStore,action,tokens,exact_match_for_search=False ):34 return(self.plugin_actions) 35 36 def execute_action(self,appstreamStore,action,tokens,exact_match_for_search=False,max_results=0): 37 37 self.progress=0 38 38 if not type(tokens) is str: … … 57 57 if self.store: 58 58 if action=='list': 59 self._list_category(tokens )59 self._list_category(tokens,max_results) 60 60 if action=='list_sections': 61 61 self._list_sections() … … 96 96 def _list_sections(self): 97 97 applist=[] 98 cat Dict={}98 categories={} 99 99 for app in self.store.get_apps(): 100 100 for cat in app.get_categories(): 101 if cat not in cat Dict.keys():102 cat Dict[cat]=1101 if cat not in categories.keys(): 102 categories[cat]=1 103 103 else: 104 cat Dict[cat]=catDict[cat]+1105 for section in cat Dict:106 applist.append({str(section):cat Dict[section]})104 categories[cat]=categories[cat]+1 105 for section in categories: 106 applist.append({str(section):categories[section]}) 107 107 self.result['data']=applist 108 108 if len(applist): … … 112 112 return(applist) 113 113 114 def _list_category(self,tokens=[] ):114 def _list_category(self,tokens=[],max_results=0): 115 115 applist=[] 116 116 self._debug("tokens: "+str(tokens)) 117 self._debug("Max results: %s"%max_results) 117 118 if len(tokens)>=1: 118 119 self._debug("Searching category "+str(tokens)) 119 setCategories=set(tokens)120 categories_set=set(tokens) 120 121 apps_in_store=self.store.get_apps() 121 122 count_apps=len(apps_in_store) … … 124 125 for app in apps_in_store: 125 126 self.progress=self.progress+inc 126 if ' setCategories' in locals():127 if 'categories_set' in locals(): 127 128 try: 128 app Categories=[cat.lower() for cat in app.get_categories()]129 app_categories=[cat.lower() for cat in app.get_categories()] 129 130 except: 130 131 pass 131 setAppCategories=set(appCategories)132 if setCategories.issubset(setAppCategories):132 app_categories_set=set(app_categories) 133 if categories_set.issubset(app_categories_set): 133 134 self._debug("Found "+app.get_id()) 134 135 applist.append(app) … … 136 137 self._debug("Loading all apps in store") 137 138 applist=self.store.get_apps() 139 categories_set=set(['snap','appimage']) 140 applist_2=[] 141 for app in applist: 142 if 'categories_set' in locals(): 143 try: 144 app_categories=[cat.lower() for cat in app.get_categories()] 145 except: 146 pass 147 app_categories_set=set(app_categories) 148 if not categories_set.issubset(app_categories_set): 149 applist_2.append(app) 150 else: 151 print("*************") 152 print("Removing %s"%app.get_pkgname()) 153 print("*************") 154 applist=applist_2 138 155 # for app in applist: 139 156 # self._debug("Added "+app.get_id()) 157 if max_results: 158 applist=applist[0:max_results] 159 #List only valid categories 160 140 161 self.result['data']=applist 141 162 if len(applist): … … 145 166 return(applist) 146 167 147 def _app_exists(self,app Name):148 self._debug("Trying direct match for "+app Name)168 def _app_exists(self,app_name): 169 self._debug("Trying direct match for "+app_name) 149 170 app=None 150 171 #1.- Try exact match 151 app=self.store.get_app_by_id(app Name)172 app=self.store.get_app_by_id(app_name) 152 173 if not app: 153 174 #2.- Try exact match with zero-lliurex- for the zomandos 154 app=self.store.get_app_by_id("zero-lliurex-"+appName) 155 if not app: 156 #2.- Try exact match with .desktop 157 app=self.store.get_app_by_id(appName+".desktop") 175 app=self.store.get_app_by_id("zero-lliurex-"+app_name) 176 if not app: 177 #3.- Try exact match with .desktop 178 app=self.store.get_app_by_id(app_name+".desktop") 179 if not app: 180 #4.- Try exact match by pkgname 181 app=self.store.get_app_by_pkgname(app_name) 182 self._debug("App found %s"%app) 158 183 return(app) 159 184 … … 162 187 self._debug("Searching app by fuzzy match") 163 188 if not applist: 164 insertPosition=1165 else: 166 insertPosition=len(applist)+1189 position=1 190 else: 191 position=len(applist)+1 167 192 apps_in_store=self.store.get_apps() 168 193 if apps_in_store: 169 auxDict={}194 tmp_app_dict={} 170 195 count_apps=len(apps_in_store) 171 196 self.progress=0 … … 179 204 if "appimage" in app.get_id().lower(): 180 205 score=1 181 if score in auxDict:182 auxDict[score].append(app)206 if score in tmp_app_dict: 207 tmp_app_dict[score].append(app) 183 208 else: 184 auxDict[score]=[app]185 for match in sorted( auxDict):186 for app in auxDict[match]:209 tmp_app_dict[score]=[app] 210 for match in sorted(tmp_app_dict): 211 for app in tmp_app_dict[match]: 187 212 if app not in applist: 188 213 self._debug("Adding app "+app.get_id() + " with score: "+str(match)) … … 192 217 def _get_app_by_pkgname(self,tokens,applist=[]): 193 218 if not applist: 194 insertPosition=1195 else: 196 insertPosition=len(applist)+1219 position=1 220 else: 221 position=len(applist)+1 197 222 apps_in_store=self.store.get_apps() 198 223 if apps_in_store: -
lliurex-store/trunk/fuentes/python3-lliurex-store.install/usr/share/lliurexstore/plugins/shManager.py
r4811 r6645 12 12 def __init__(self): 13 13 self.locale=locale.getlocale()[0] 14 self.dbg= 015 self.plugin Info={'install':'sh','pkginfo':'sh'}14 self.dbg=False 15 self.plugin_actions={'install':'sh','pkginfo':'sh'} 16 16 self.progress=0 17 17 self.result={} … … 21 21 #def __init__ 22 22 23 def set_debug(self,dbg ='1'):24 self.dbg= int(dbg)23 def set_debug(self,dbg): 24 self.dbg=dbg 25 25 self._debug ("Debug enabled") 26 26 #def set_debug 27 27 28 28 def _debug(self,msg=''): 29 if self.dbg ==1:29 if self.dbg: 30 30 print ('DEBUG Sh: '+msg) 31 31 #def debug 32 32 33 33 def register(self): 34 return(self.plugin Info)34 return(self.plugin_actions) 35 35 #def register 36 36 … … 40 40 count=len(applist) 41 41 if (action): 42 for app Info in applist:43 self._debug("Executing action "+action+" for "+str(app Info))42 for app_info in applist: 43 self._debug("Executing action "+action+" for "+str(app_info)) 44 44 if action=='install': 45 self.result['data'].append(self._install_App(app Info))45 self.result['data'].append(self._install_App(app_info)) 46 46 if action=='pkginfo': 47 self.result['data'].append(self._get_Sh_Info(app Info))47 self.result['data'].append(self._get_Sh_Info(app_info)) 48 48 self.progress=100 49 49 return(self.result) … … 53 53 self.result['status']={'status':status,'msg':msg} 54 54 55 def _callback(self,partial Size=0,totalSize=0):55 def _callback(self,partial_size=0,total_size=0): 56 56 limit=99 57 if partial Size!=0 and totalSize!=0:58 inc=round(partial Size/totalSize,2)*10057 if partial_size!=0 and total_size!=0: 58 inc=round(partial_size/total_size,2)*100 59 59 self.progress=inc 60 60 else: … … 67 67 #def _callback 68 68 69 def _install_App(self,app Info):69 def _install_App(self,app_info): 70 70 return_msg=False 71 app Url=appInfo['installerUrl']72 self._debug("Checking availabilty for "+app Url)73 tmp Dir=tempfile.mkdtemp(None,None,'/tmp')74 file Name=appUrl.split('/')[-1]75 dest_path=tmp Dir+'/'+fileName76 if self._download_App(app Url,dest_path):77 os.chdir(tmp Dir)71 app_url=app_info['installerUrl'] 72 self._debug("Checking availabilty for "+app_url) 73 tmp_dir=tempfile.mkdtemp(None,None,'/tmp') 74 file_name=app_url.split('/')[-1] 75 dest_path=tmp_dir+'/'+file_name 76 if self._download_App(app_url,dest_path): 77 os.chdir(tmp_dir) 78 78 os.chmod(dest_path, stat.S_IRUSR|stat.S_IWUSR|stat.S_IXUSR) 79 79 err=0 80 80 try: 81 cmdsudo=['gksudo',dest_path]82 self._debug("executing "+str( cmdsudo))83 cmdCmd=subprocess.Popen(cmdsudo,stdout=subprocess.PIPE,stdin=subprocess.PIPE,stderr=subprocess.PIPE)84 # cmdCmd=subprocess.check_output(cmdsudo)85 cmd Launcher=os.path.basename(dest_path)86 cmd Launcher=os.path.splitext(cmdLauncher)[0]87 while cmdCmd.poll() is None:81 sudo_cmd=['gksudo',dest_path] 82 self._debug("executing "+str(sudo_cmd)) 83 launched_cmd=subprocess.Popen(sudo_cmd,stdout=subprocess.PIPE,stdin=subprocess.PIPE,stderr=subprocess.PIPE) 84 # launched_cmd=subprocess.check_output(sudo_cmd) 85 cmd_launcher=os.path.basename(dest_path) 86 cmd_launcher=os.path.splitext(cmd_launcher)[0] 87 while launched_cmd.poll() is None: 88 88 self._callback() 89 89 time.sleep(0.4) 90 if cmdCmd.poll():91 if cmdCmd.poll()==255:90 if launched_cmd.poll(): 91 if launched_cmd.poll()==255: 92 92 err=303 93 93 else: 94 err= cmdCmd.poll()94 err=launched_cmd.poll() 95 95 err=3 #Force "package not installed" error 96 cmd Result=cmdCmd.stdout.read()97 cmd Error=cmdCmd.stderr.read()98 self._debug("Error: "+str(cmd Error))99 self._debug("Result: "+str(cmd Result))96 cmd_status=launched_cmd.stdout.read() 97 cmd_err=launched_cmd.stderr.read() 98 self._debug("Error: "+str(cmd_err)) 99 self._debug("Result: "+str(cmd_status)) 100 100 except subprocess.CalledProcessError as callError: 101 101 # err=callError.returncode … … 108 108 err=11 109 109 self._set_status(err) 110 return app Info110 return app_info 111 111 #def install_App 112 112 113 def _download_App(self,app Url,dest_path=None):114 app Url.strip()113 def _download_App(self,app_url,dest_path=None): 114 app_url.strip() 115 115 if not dest_path: 116 tmp Dir=tempfile.mkdtemp(None,None,'/tmp')117 dest_path=tmp Dir+'/'+appUrl.split('/')[-1]118 self._debug("Downloading "+app Url+" to "+dest_path)116 tmp_dir=tempfile.mkdtemp(None,None,'/tmp') 117 dest_path=tmp_dir+'/'+app_url.split('/')[-1] 118 self._debug("Downloading "+app_url+" to "+dest_path) 119 119 try: 120 # urllib.request.urlretrieve(app Url,dest_path)121 with urllib.request.urlopen(app Url) as response, open(dest_path, 'wb') as out_file:120 # urllib.request.urlretrieve(app_url,dest_path) 121 with urllib.request.urlopen(app_url) as response, open(dest_path, 'wb') as out_file: 122 122 bf=16*1024 123 123 acumbf=0 124 sh Size=int(response.info()['Content-Length'])124 sh_size=int(response.info()['Content-Length']) 125 125 while True: 126 if acumbf>=sh Size:126 if acumbf>=sh_size: 127 127 break 128 128 shutil.copyfileobj(response, out_file,bf) 129 129 acumbf=acumbf+bf 130 self._callback(acumbf,sh Size)130 self._callback(acumbf,sh_size) 131 131 return_msg=True 132 132 except Exception as e: … … 136 136 #def _download_App 137 137 138 def _get_Sh_Info(self,app Info):139 app Url=appInfo['installerUrl']140 self._debug("Connecting to "+app Url)141 app Url.strip()138 def _get_Sh_Info(self,app_info): 139 app_url=app_info['installerUrl'] 140 self._debug("Connecting to "+app_url) 141 app_url.strip() 142 142 try: 143 info=urllib.request.urlopen(app Url)144 app Info['size']=info.info()['Content-Length']143 info=urllib.request.urlopen(app_url) 144 app_info['size']=info.info()['Content-Length'] 145 145 err=0 146 146 except: 147 147 err=11 148 148 self._set_status(err) 149 return(app Info)149 return(app_info) 150 150 151 151 #def _get_info -
lliurex-store/trunk/fuentes/python3-lliurex-store.install/usr/share/lliurexstore/plugins/zmdManager.py
r6057 r6645 15 15 def __init__(self): 16 16 self.locale=locale.getlocale()[0] 17 self.dbg= 018 self.zmd Path='/usr/share/zero-center/zmds'17 self.dbg=False 18 self.zmd_folder='/usr/share/zero-center/zmds' 19 19 self.disabled=False 20 if hasattr(sys,'last_value') or not (os.path.exists(self.zmd Path)):20 if hasattr(sys,'last_value') or not (os.path.exists(self.zmd_folder)): 21 21 #If there's an error at this point it only could be an importError caused by xmlrpc 22 22 self.disabled=True 23 self.plugin Info={'install':'zmd','pkginfo':'zmd','remove':'zmd'}23 self.plugin_actions={'install':'zmd','pkginfo':'zmd','remove':'zmd'} 24 24 self.progress=0 25 25 self.n4dclient='' … … 30 30 #def __init__ 31 31 32 def set_debug(self,dbg= '1'):33 self.dbg= int(dbg)32 def set_debug(self,dbg=True): 33 self.dbg=dbg 34 34 self._debug ("Debug enabled") 35 35 #def set__debug 36 36 37 37 def _debug(self,msg=''): 38 if self.dbg ==1:38 if self.dbg: 39 39 print ('DEBUG Zmd: '+str(msg)) 40 40 #def _debug 41 41 42 42 def register(self): 43 return(self.plugin Info)43 return(self.plugin_actions) 44 44 #def register 45 45 … … 55 55 try: 56 56 self.n4dclient=self._n4d_connect() 57 for app Info in applist:57 for app_info in applist: 58 58 if (action): 59 59 if action=='install': 60 dataList.append(self._install_Zmd(app Info))60 dataList.append(self._install_Zmd(app_info)) 61 61 if action=='remove': 62 dataList.append(self._remove_Zmd(app Info))62 dataList.append(self._remove_Zmd(app_info)) 63 63 if action=='pkginfo': 64 dataList.append(self._get_Zmd_Info(app Info))64 dataList.append(self._get_Zmd_Info(app_info)) 65 65 self.result['data']=list(dataList) 66 66 except: … … 75 75 # dataList['status']={'status':status,'msg':msg} 76 76 77 def _callback(self,zmd Launcher):77 def _callback(self,zmd_launcher): 78 78 inc=1 79 79 limit=99 80 80 n4dvars=self.n4dclient.get_variable("","VariablesManager","ZEROCENTER") 81 if zmd Launcher in n4dvars.keys():82 if n4dvars[zmd Launcher]['pulsating']:81 if zmd_launcher in n4dvars.keys(): 82 if n4dvars[zmd_launcher]['pulsating']: 83 83 margin=limit-self.progress 84 84 inc=round(margin/limit,3) … … 86 86 #def _callback 87 87 88 def _install_Zmd(self,app Info):89 zmd=self.zmd Path+'/'+appInfo['package']+'.zmd'88 def _install_Zmd(self,app_info): 89 zmd=self.zmd_folder+'/'+app_info['package']+'.zmd' 90 90 self._debug("Installing "+str(zmd)) 91 app Info=self._get_Zmd_Info(appInfo)92 if app Info['state']=='installed':91 app_info=self._get_Zmd_Info(app_info) 92 if app_info['state']=='installed': 93 93 err=4 94 94 else: … … 96 96 err=0 97 97 try: 98 # zmd sudo=['gksudo',zmd]99 zmd sudo=['pe',zmd]100 self._debug("executing "+str(zmd sudo))101 zmdCmd=subprocess.Popen(zmdsudo,stdout=subprocess.PIPE,stdin=subprocess.PIPE,stderr=subprocess.PIPE)102 zmd Launcher=os.path.basename(zmd)103 zmd Launcher=os.path.splitext(zmdLauncher)[0]104 while zmdCmd.poll() is None:105 self._callback(zmd Launcher)98 # zmd_sudo=['gksudo',zmd] 99 zmd_sudo=['pe',zmd] 100 self._debug("executing "+str(zmd_sudo)) 101 launched_zmd=subprocess.Popen(zmd_sudo,stdout=subprocess.PIPE,stdin=subprocess.PIPE,stderr=subprocess.PIPE) 102 zmd_launcher=os.path.basename(zmd) 103 zmd_launcher=os.path.splitext(zmd_launcher)[0] 104 while launched_zmd.poll() is None: 105 self._callback(zmd_launcher) 106 106 time.sleep(0.4) 107 zmd Result=zmdCmd.stdout.read()108 zmd Error=zmdCmd.stderr.read()109 self._debug("Error: "+str(zmd Error))110 self._debug("Result: "+str(zmd Result))107 zmd_status=launched_zmd.stdout.read() 108 zmd_err=launched_zmd.stderr.read() 109 self._debug("Error: "+str(zmd_err)) 110 self._debug("Result: "+str(zmd_status)) 111 111 except Exception as e: 112 112 self._debug(str(e)) 113 113 finally: 114 app Info=self._get_Zmd_Info(appInfo)115 if app Info['state']!='installed':114 app_info=self._get_Zmd_Info(app_info) 115 if app_info['state']!='installed': 116 116 err=5 117 117 else: 118 118 err=8 119 119 self._set_status(err) 120 return(app Info)120 return(app_info) 121 121 #def _install_Zmd 122 122 123 def _remove_Zmd(self,app Info):124 zmd=app Info['package']+'.zmd'123 def _remove_Zmd(self,app_info): 124 zmd=app_info['package']+'.zmd' 125 125 self._debug("Removing "+str(zmd)) 126 os.chdir(self.zmd Path)126 os.chdir(self.zmd_folder) 127 127 sw_continue=False 128 128 err=0 129 129 try: 130 remove Packages=[]130 remove_packages=[] 131 131 f=open(zmd,'r') 132 132 for line in f: … … 144 144 pkg=pkg.replace('"','') 145 145 self._debug("Append to remove list: "+pkg) 146 remove Packages.append(pkg)146 remove_packages.append(pkg) 147 147 f2.close() 148 148 f.close() … … 151 151 print(str(e)) 152 152 if sw_continue: 153 z eroScript='/tmp/zeroScript'154 f3=open(z eroScript,'w')153 zmd_script='/tmp/zmd_script' 154 f3=open(zmd_script,'w') 155 155 f3.write('#!/bin/bash'+"\n") 156 for pkg in remove Packages:156 for pkg in remove_packages: 157 157 f3.write('/usr/bin/zero-installer remove '+pkg+"\n") 158 f3.write ("zero-center set-non-configured "+app Info['package']+"\n")158 f3.write ("zero-center set-non-configured "+app_info['package']+"\n") 159 159 f3.close() 160 os.chmod(z eroScript,stat.S_IEXEC|stat.S_IREAD|stat.S_IWRITE|stat.S_IROTH|stat.S_IWOTH|stat.S_IXOTH|stat.S_IRGRP|stat.S_IWGRP|stat.S_IXGRP)161 zmd sudo=['gksudo',zeroScript]160 os.chmod(zmd_script,stat.S_IEXEC|stat.S_IREAD|stat.S_IWRITE|stat.S_IROTH|stat.S_IWOTH|stat.S_IXOTH|stat.S_IRGRP|stat.S_IWGRP|stat.S_IXGRP) 161 zmd_sudo=['gksudo',zmd_script] 162 162 try: 163 self._debug("Executing "+str(zmd sudo))164 zmd Launcher=os.path.basename(zmd)165 zmd Launcher=os.path.splitext(zmdLauncher)[0]166 zmdCmd=subprocess.Popen(zmdsudo,stdout=subprocess.PIPE,stdin=subprocess.PIPE,stderr=subprocess.PIPE)163 self._debug("Executing "+str(zmd_sudo)) 164 zmd_launcher=os.path.basename(zmd) 165 zmd_launcher=os.path.splitext(zmd_launcher)[0] 166 launched_zmd=subprocess.Popen(zmd_sudo,stdout=subprocess.PIPE,stdin=subprocess.PIPE,stderr=subprocess.PIPE) 167 167 self._debug("Launched") 168 while zmdCmd.poll() is None:169 self._callback(zmd Launcher)168 while launched_zmd.poll() is None: 169 self._callback(zmd_launcher) 170 170 time.sleep(0.2) 171 zmd Result=zmdCmd.stdout.read()172 zmd Error=zmdCmd.stderr.read()171 zmd_status=launched_zmd.stdout.read() 172 zmd_err=launched_zmd.stderr.read() 173 173 except Exception as e: 174 174 err=6 175 175 self._debug(str(e)) 176 self._debug("Error: "+str(zmd Error))177 self._debug("Result: "+str(zmd Result))178 app Info=self._get_Zmd_Info(appInfo)179 if app Info['state']=='installed':176 self._debug("Error: "+str(zmd_err)) 177 self._debug("Result: "+str(zmd_status)) 178 app_info=self._get_Zmd_Info(app_info) 179 if app_info['state']=='installed': 180 180 err=6 181 os.remove(z eroScript)181 os.remove(zmd_script) 182 182 else: 183 183 err=6 184 184 self._set_status(err) 185 return(app Info)185 return(app_info) 186 186 #def _remove_Zmd 187 187 188 def _get_Zmd_Info(self,app Info):189 zmd=app Info['package']190 app Info['state']='Available'188 def _get_Zmd_Info(self,app_info): 189 zmd=app_info['package'] 190 app_info['state']='Available' 191 191 try: 192 192 n4dvars=self.n4dclient.get_variable("","VariablesManager","ZEROCENTER") … … 197 197 if 'state' in n4dvars[key]: 198 198 if n4dvars[key]['state']==1: 199 app Info['state']='installed'199 app_info['state']='installed' 200 200 else: 201 201 self._set_status(2) 202 202 except Exception as e: 203 203 self._set_status(10) 204 # self.result['data'].append(appInfo) 205 # self.result.append(appInfo) 206 if appInfo['state']!='installed': 207 #There're some zomandos that may be unregistered, so we check again 208 zmdApp='/usr/share/zero-center/applications/'+zmd+".app" 209 if os.path.isfile(zmdApp): 210 f=open(zmdApp,'r') 211 fileContent=f.readlines() 212 f.close 213 sw_service=False 214 for line in fileContent: 215 if line.startswith('Service'): 216 sw_service=True 217 if 'True' not in line: 218 print(line) 219 appInfo['state']='installed' 220 if sw_service==False: 221 appInfo['state']='installed' 222 223 return(appInfo) 204 # self.result['data'].append(app_info) 205 # self.result.append(app_info) 206 return(app_info) 224 207 #def _get_Zmd_Info 225 208 -
lliurex-store/trunk/fuentes/python3-lliurex-store.install/usr/share/lliurexstore/storeManager.py
r6547 r6645 15 15 ##### 16 16 17 class StoreManager: 18 def __init__(self,args=()): 19 self.dbg=0 20 self._propagate_dbg=0 17 class StoreManager(): 18 # def __init__(self,snap=False,appimage=False,dbg=False): 19 def __init__(self,**kwargs): 20 self.dbg=False 21 if 'dbg' in kwargs.keys(): 22 self.dbg=kwargs['dbg'] 23 self._propagate_dbg=False 21 24 self.store=None 22 self.related Actions={25 self.related_actions={ 23 26 'load':['load'], 24 27 'search':['search','get_info','pkginfo'], … … 29 32 'remove':['search','get_info','pkginfo','remove'] 30 33 } 31 self.loadBundles=False 32 if args: 33 if args[0]==1: 34 self.loadBundles=True 35 if args[1]==1: 36 self.dbg=args 34 self.cli_mode=[] #List that controls cli_mode for plugins 37 35 self.threads={} #Dict that stores the functions that must execute each action 38 self.threads Progress={} #"" "" "" the progress for each launched thread39 self. threadsRunning={} #"" "" "" the running threads40 self. registeredPlugins={} #Dict that have the relation between plugins and actions41 self.register ProcessProgress={} #Dict that stores the progress for each function/parentAction pair42 self. progressActions={} #Progress of global actions based on average progress of individual processes43 self.extra Actions={} #Dict that have the actions managed by plugins and no defined on the main class as relatedActions36 self.threads_progress={} #"" "" "" the progress for each launched thread 37 self.running_threads={} #"" "" "" the running threads 38 self.plugins_registered={} #Dict that have the relation between plugins and actions 39 self.register_action_progress={} #Dict that stores the progress for each function/parent_action pair 40 self.action_progress={} #Progress of global actions based on average progress of individual processes 41 self.extra_actions={} #Dict that have the actions managed by plugins and no defined on the main class as related_actions 44 42 self.result={} #Result of the actions 45 43 self.lock=threading.Lock() #locker for functions related to threads (get_progress, is_action_running...) 46 self.main( )44 self.main(kwargs) 47 45 #def __init__ 48 46 49 def main(self ):47 def main(self,args={}): 50 48 self._define_functions_for_threads() #Function that loads the dictionary self.threads 51 self.__init_plugins__() #Function that loads the plugins 52 self._debug("Load bundles %s"%self.loadBundles) 53 if self.loadBundles: 54 self.execute_action('load_bundles') #Initial load of the store 55 else: 56 self.execute_action('load') #Initial load of the store 49 self.__init_plugins__(args) #Function that loads the plugins 50 self.execute_action('load') #Initial load of the store 57 51 #def main 58 52 … … 60 54 #Load and register the plugins from plugin dir 61 55 #### 62 def __init_plugins__(self ):56 def __init_plugins__(self,args={}): 63 57 package=plugins 64 58 for importer, mod, ispkg in pkgutil.walk_packages(path=package.__path__, prefix=package.__name__+'.',onerror=lambda x: None): 65 strImport='from '+mod+' import *'59 import_mod='from '+mod+' import *' 66 60 try: 67 61 self._debug("Importing "+str(mod)) 68 exec ( strImport)62 exec (import_mod) 69 63 except Exception as e: 70 64 print(str(e)) … … 72 66 for mod in (sys.modules.keys()): 73 67 if 'plugins.' in mod: 74 definedActions={} 75 pluginNameUp=mod.split('.')[-1] 76 pluginName=pluginNameUp.lower() 77 self._debug("Initializing "+str(pluginName)) 68 class_actions={} 69 plugin_name_up=mod.split('.')[-1] 70 plugin_name=plugin_name_up.lower() 71 self._debug("Initializing "+str(plugin_name)) 72 sw_cli_mode=False 78 73 try: 79 loadedClass=eval(pluginName)() 80 definedActions=loadedClass.register() 74 target_class=eval(plugin_name)() 75 class_actions=target_class.register() 76 if 'disabled' in target_class.__dict__.keys(): 77 if target_class.disabled==True: 78 self._debug("Disabling plugin %s"%plugin_name) 79 continue 80 #Time to check if plugin is disabled or enabled by parm 81 #Values for the plugins_registered dict must be the same as the parm name that enables the plugin 82 for key,value in class_actions.items(): 83 val=value 84 break 85 if val in args.keys(): 86 if args[val]==True: 87 if target_class.disabled: 88 self._debug("Disabling plugin %s"%plugin_name) 89 continue 90 else: 91 self._debug("Disabling plugin %s"%plugin_name) 92 continue 93 else: 94 self._debug("Disabling plugin %s"%plugin_name) 95 continue 96 if 'cli_mode' in target_class.__dict__.keys(): 97 if 'cli' in args.keys(): 98 sw_cli_mode=True 99 self._debug("Enabling cli mode for %s"%plugin_name) 81 100 except Exception as e: 82 print ("Can't initialize "+str(mod)+' '+str( loadedClass))101 print ("Can't initialize "+str(mod)+' '+str(target_class)) 83 102 print ("Reason: "+str(e)) 84 103 pass 85 104 86 for action in definedActions.keys(): 87 if action not in self.registeredPlugins: 88 self.registeredPlugins[action]={} 89 self.registeredPlugins[action].update({definedActions[action]:'plugins.'+pluginNameUp+'.'+pluginName}) 90 self._debug(str(self.registeredPlugins)) 105 for action in class_actions.keys(): 106 if action not in self.plugins_registered: 107 self.plugins_registered[action]={} 108 full_module_name='plugins.'+plugin_name_up+'.'+plugin_name 109 self.plugins_registered[action].update({class_actions[action]:full_module_name}) 110 if sw_cli_mode: 111 self.cli_mode.append(full_module_name) 112 113 self._debug(str(self.plugins_registered)) 91 114 #def __init_plugins__ 92 115 93 def set_debug(self,dbg= '1'):94 self.dbg= int(dbg)116 def set_debug(self,dbg=True): 117 self.dbg=dbg 95 118 self._debug ("Debug enabled") 96 119 #def set_debug … … 111 134 def _define_functions_for_threads(self): 112 135 self.threads['load']="threading.Thread(target=self._load_Store)" 113 self.threads['load_bundles']="threading.Thread(target=self._load_Store)"136 # self.threads['load_bundles']="threading.Thread(target=self._load_Store)" 114 137 self.threads['get_info']="threading.Thread(target=self._get_App_Info,args=[args])" 115 138 self.threads['pkginfo']="threading.Thread(target=self._get_Extended_App_Info,args=[args])" … … 132 155 if self.is_action_running('load'): 133 156 self._join_action('load') 134 if self.is_action_running('load_bundles'): 135 self._join_action('load_bundles') 136 sw_withoutStatus=False 157 self._debug("Resumed action %s"%action) 158 sw_track_status=False 137 159 if action not in self.threads.keys(): 138 160 #Attempt to add a new action managed by a plugin 139 161 self._debug("Attempting to find a plugin for action "+action) 140 if action in self. registeredPlugins.keys():141 for package Type,plugin in self.registeredPlugins[action].items():142 self. progressActions[action]=0143 self.threads[action]='threading.Thread(target=self._execute_class_method(action,package Type,action).execute_action,args=[action])'162 if action in self.plugins_registered.keys(): 163 for package_type,plugin in self.plugins_registered[action].items(): 164 self.action_progress[action]=0 165 self.threads[action]='threading.Thread(target=self._execute_class_method(action,package_type,action).execute_action,args=[action])' 144 166 break 145 self._debug('Plugin for '+action+' found: '+str(self. registeredPlugins[action]))146 self.related Actions.update({action:[action]})147 sw_ withoutStatus=True167 self._debug('Plugin for '+action+' found: '+str(self.plugins_registered[action])) 168 self.related_actions.update({action:[action]}) 169 sw_track_status=True 148 170 if action in self.threads.keys(): 149 171 if self.is_action_running(action): 150 172 #join thread if we're performing the same action 151 173 self._debug("Waiting for current action "+action+" to end") 152 self. threadsRunning[action].join()174 self.running_threads[action].join() 153 175 try: 154 if action in self. progressActions.keys():155 self. progressActions[action]=0156 self. progressActions[action]=0176 if action in self.action_progress.keys(): 177 self.action_progress[action]=0 178 self.action_progress[action]=0 157 179 self.result[action]={} 158 self. threadsRunning[action]=eval(self.threads[action])159 self. threadsRunning[action].start()160 if sw_ withoutStatus:180 self.running_threads[action]=eval(self.threads[action]) 181 self.running_threads[action].start() 182 if sw_track_status: 161 183 self.result[action]['status']={'status':0,'msg':''} 162 184 else: 163 185 self.result[action]['status']={'status':-1,'msg':''} 164 self._debug("Thread "+str(self. threadsRunning[action])+" for action "+action+" launched")186 self._debug("Thread "+str(self.running_threads[action])+" for action "+action+" launched") 165 187 166 188 except Exception as e: … … 182 204 #### 183 205 def _execute_class_method(self,action,parms=None,launchedby=None): 184 exe Function=None206 exe_function=None 185 207 if not parms: 186 208 parms="*" 187 if action in self. registeredPlugins:188 self._debug("Plugin for "+action+": "+self. registeredPlugins[action][parms])189 exe Function=eval(self.registeredPlugins[action][parms]+"()")209 if action in self.plugins_registered: 210 self._debug("Plugin for "+action+": "+self.plugins_registered[action][parms]) 211 exe_function=eval(self.plugins_registered[action][parms]+"()") 190 212 if self._propagate_dbg: 191 exeFunction.set_debug(1) 192 self._registerProcessProgress(action,exeFunction,launchedby) 213 exe_function.set_debug() 214 if self.plugins_registered[action][parms] in self.cli_mode: 215 exe_function.cli_mode=True 216 self._register_action_progress(action,exe_function,launchedby) 193 217 else: 194 218 self._debug("No plugin for action: "+action) 195 219 196 return (exe Function)220 return (exe_function) 197 221 #def _execute_class_method 198 222 … … 204 228 # - status true/false 205 229 ### 206 def is_action_running(self, actionSearched=None):230 def is_action_running(self,searched_action=None): 207 231 status=False 208 action List=[]209 if actionSearched:210 action List.append(actionSearched)211 else: 212 action List=self.relatedActions.keys()213 214 for action in action List:215 if action in self. threadsRunning.keys():216 if self. threadsRunning[action].is_alive():232 action_list=[] 233 if searched_action: 234 action_list.append(searched_action) 235 else: 236 action_list=self.related_actions.keys() 237 238 for action in action_list: 239 if action in self.running_threads.keys(): 240 if self.running_threads[action].is_alive(): 217 241 status=True 218 242 break 219 243 else: 220 if action in self.related Actions.keys():221 for related Action in self.relatedActions[action]:222 if related Action in self.threadsRunning.keys():223 if self. threadsRunning[relatedAction].is_alive():244 if action in self.related_actions.keys(): 245 for related_action in self.related_actions[action]: 246 if related_action in self.running_threads.keys(): 247 if self.running_threads[related_action].is_alive(): 224 248 status=True 225 249 break … … 235 259 self._debug("Joining action: "+action) 236 260 try: 237 self. threadsRunning[action].join()261 self.running_threads[action].join() 238 262 except Exception as e: 239 263 self._debug("Unable to join thread for: "+action) 240 264 self._debug("Reason: "+ str(e)) 241 265 finally: 242 if action in self. threadsRunning.keys():243 del(self. threadsRunning[action])266 if action in self.running_threads.keys(): 267 del(self.running_threads[action]) 244 268 #def _join_action 245 269 246 270 #### 247 #Register the method and action/parent Action pair in the progress dict271 #Register the method and action/parent_action pair in the progress dict 248 272 #Input: 249 273 # - action launched 250 274 # - function (a reference to the function) 251 # - parent Action that owns the action (if any)252 #### 253 def _register ProcessProgress(self,action,function,parentAction=None):254 if action in self.register ProcessProgress.keys():275 # - parent_action that owns the action (if any) 276 #### 277 def _register_action_progress(self,action,function,parent_action=None): 278 if action in self.register_action_progress.keys(): 255 279 self._debug("Appended process for action: "+action +" and function: "+str(function)) 256 self.register ProcessProgress[action].append(function)280 self.register_action_progress[action].append(function) 257 281 else: 258 282 self._debug("Registered process for action: "+action+" and function: "+str(function)) 259 self.register ProcessProgress[action]=[function]260 if parent Action:261 self._debug("Registered process for Parent Action: "+action+"-"+parent Action+" and function: "+str(function))262 if parent Action in self.threadsProgress.keys():263 self.threads Progress[parentAction].update({action:function})283 self.register_action_progress[action]=[function] 284 if parent_action: 285 self._debug("Registered process for Parent Action: "+action+"-"+parent_action+" and function: "+str(function)) 286 if parent_action in self.threads_progress.keys(): 287 self.threads_progress[parent_action].update({action:function}) 264 288 else: 265 self.threads Progress[parentAction]={action:function}266 #def _register ProcessProgress289 self.threads_progress[parent_action]={action:function} 290 #def _register_action_progress 267 291 268 292 #### … … 275 299 def get_progress(self,action=None): 276 300 progress={'search':0,'list':0,'install':0,'remove':0,'load':0,'list_sections':0} 277 action List=[]278 if action and action in self.register ProcessProgress:279 action List=[action]280 else: 281 action List=self.registerProcessProgress.keys()301 action_list=[] 302 if action and action in self.register_action_progress: 303 action_list=[action] 304 else: 305 action_list=self.register_action_progress.keys() 282 306 self.lock.acquire() #prevent that any thread attempts to change the iterator 283 for parent Action in self.relatedActions.keys():284 if self.is_action_running(parent Action):285 for action in action List:286 if parent Action in self.threadsProgress.keys():287 acum Progress=0288 for threadfunction,function in self.threads Progress[parentAction].items():289 acum Progress=acumProgress+function.progress307 for parent_action in self.related_actions.keys(): 308 if self.is_action_running(parent_action): 309 for action in action_list: 310 if parent_action in self.threads_progress.keys(): 311 acum_progress=0 312 for threadfunction,function in self.threads_progress[parent_action].items(): 313 acum_progress=acum_progress+function.progress 290 314 291 count=len(self.related Actions[parentAction])292 self. progressActions[parentAction]=round(acumProgress/count,0)293 progress[parent Action]=self.progressActions[parentAction]315 count=len(self.related_actions[parent_action]) 316 self.action_progress[parent_action]=round(acum_progress/count,0) 317 progress[parent_action]=self.action_progress[parent_action] 294 318 else: 295 319 #put a 100% just in case 296 if parent Action in self.progressActions.keys():297 self. progressActions[parentAction]=100320 if parent_action in self.action_progress.keys(): 321 self.action_progress[parent_action]=100 298 322 self.lock.release() 299 return(self. progressActions)323 return(self.action_progress) 300 324 #def get_progress 301 325 … … 328 352 result[action]=[] 329 353 self.lock.release() 330 if action in self.extra Actions.keys():354 if action in self.extra_actions.keys(): 331 355 self._load_Store() 332 356 return(result) … … 347 371 result=self.result[action]['status'] 348 372 try: 349 err orFile=open('/usr/share/lliurex-store/files/error.json').read()350 err orCodes=json.loads(errorFile)351 err Code=str(result['status'])352 if err Code in errorCodes:353 result['msg']=err orCodes[errCode]373 err_file=open('/usr/share/lliurex-store/files/error.json').read() 374 err_codes=json.loads(err_file) 375 err_code=str(result['status']) 376 if err_code in err_codes: 377 result['msg']=err_codes[err_code] 354 378 else: 355 379 result['msg']=u"Unknown error" … … 364 388 #### 365 389 def _load_Store(self): 366 if self.loadBundles: 367 action='load_bundles' 368 else: 369 action='load' 370 loadFunction=self._execute_class_method(action,None,None) 371 self.store=loadFunction.execute_action(action,self.store,self.loadBundles) 390 action='load' 391 for package_type in self.plugins_registered[action]: 392 load_function=self._execute_class_method(action,package_type,None) 393 self.store=load_function.execute_action(action=action,store=self.store)['data'] 372 394 #def _load_Store 373 395 … … 381 403 def _get_App_Info(self,applist,launchedby=None): 382 404 action='get_info' 383 info Function=self._execute_class_method(action,None,launchedby)384 applistInfo=infoFunction.execute_action(self.store,action,applist)385 return( applistInfo)405 info_function=self._execute_class_method(action,None,launchedby) 406 info_applist=info_function.execute_action(self.store,action,applist) 407 return(info_applist) 386 408 #def _get_App_Info 387 409 … … 393 415 # - Dict with the related info 394 416 #### 395 def _get_Extended_App_Info(self, applistInfo,launchedby=None,fullsearch=True):417 def _get_Extended_App_Info(self,info_applist,launchedby=None,fullsearch=True): 396 418 #Check if there's any plugin for the distinct type of packages 397 419 action='pkginfo' 398 type Dict={}420 types_dict={} 399 421 result={} 400 422 result['data']=[] 401 423 result['status']={'status':0,'msg':''} 402 for app Info in applistInfo:403 # result['data'].append(app Info)404 package_type=self._check_package_type(app Info)405 if package_type in type Dict:406 type Dict[package_type].append(appInfo)424 for app_info in info_applist: 425 # result['data'].append(app_info) 426 package_type=self._check_package_type(app_info) 427 if package_type in types_dict: 428 types_dict[package_type].append(app_info) 407 429 else: 408 type Dict[package_type]=[appInfo]409 for package_type in type Dict:430 types_dict[package_type]=[app_info] 431 for package_type in types_dict: 410 432 self._debug("Checking plugin for "+action+ " "+package_type) 411 if package_type in self. registeredPlugins[action]:433 if package_type in self.plugins_registered[action]: 412 434 # result['data']=[] 413 435 #Only search full info if it's required 414 436 if (fullsearch==False and package_type=='deb'): 415 result['data'].extend(type Dict[package_type])437 result['data'].extend(types_dict[package_type]) 416 438 continue 417 self._debug("Retrieving info for "+str(type Dict[package_type]))418 pkgInfoFunction=self._execute_class_method(action,package_type,launchedby)419 # result.update( pkgInfoFunction.execute_action(action,typeDict[package_type]))420 result['data'].extend( pkgInfoFunction.execute_action(action,typeDict[package_type])['data'])421 # result['status']= pkgInfoFunction.execute_action(action,typeDict[package_type])['status']422 # result= pkgInfoFunction.execute_action(action,typeDict[package_type])439 self._debug("Retrieving info for "+str(types_dict[package_type])) 440 info_function=self._execute_class_method(action,package_type,launchedby) 441 # result.update(info_function.execute_action(action,types_dict[package_type])) 442 result['data'].extend(info_function.execute_action(action,types_dict[package_type])['data']) 443 # result['status']=info_function.execute_action(action,types_dict[package_type])['status'] 444 # result=info_function.execute_action(action,types_dict[package_type]) 423 445 else: 424 result['data'].append(app Info)446 result['data'].append(app_info) 425 447 return(result) 426 448 #def _get_Extended_App_Info … … 431 453 data={} 432 454 status={} 433 if action in self. registeredPlugins.keys():434 self._debug("Plugin for generic search: "+self. registeredPlugins[action]['*'])435 finder=self. registeredPlugins[action][('*')]436 search Function=eval(finder+"()")437 result=search Function.execute_action(self.store,action,searchItem)455 if action in self.plugins_registered.keys(): 456 self._debug("Plugin for generic search: "+self.plugins_registered[action]['*']) 457 finder=self.plugins_registered[action][('*')] 458 search_function=eval(finder+"()") 459 result=search_function.execute_action(self.store,action,searchItem) 438 460 status=result['status'] 439 461 data=result['data'] … … 452 474 # - List of dicts with all the info 453 475 #### 454 def _search_Store(self,searchItem='',action='search',fullsearch=False,launchedby=None): 476 def _search_Store(self,search_item='',action='search',fullsearch=False,launchedby=None,max_results=0): 477 if type(search_item[-1])==type(1): 478 max_results=search_item[-1] 479 search_item=search_item[:-1] 455 480 applist={} 456 481 result={} … … 458 483 if action=='list': 459 484 try: 460 search Item=' '.join(searchItem)485 search_item=' '.join(search_item) 461 486 except: 462 search Item=''487 search_item='' 463 488 elif action=='list_sections': 464 search Item=''489 search_item='' 465 490 elif action=='info': 466 491 fullsearch=True … … 471 496 if (launchedby=='search'): 472 497 exact_match=False 473 searchFunction=self._execute_class_method(action,'*',launchedby) 474 result=searchFunction.execute_action(self.store,action,searchItem,exact_match) 498 for package_type in self.plugins_registered[action]: 499 search_function=self._execute_class_method(action,'*',launchedby) 500 result.update(search_function.execute_action(self.store,action,search_item,exact_match,max_results)) 475 501 aux_applist=result['data'] 476 502 status=result['status'] … … 478 504 if status['status']==0: 479 505 #1.- Get appstream metadata (faster) 480 partialAction='get_info'481 self.result[ partialAction]={}506 subordinate_action='get_info' 507 self.result[subordinate_action]={} 482 508 result=self._get_App_Info(aux_applist,launchedby) 483 self._debug("Add result for "+ partialAction)484 self.result[ partialAction]=result509 self._debug("Add result for "+subordinate_action) 510 self.result[subordinate_action]=result 485 511 #2.- Get rest of metadata (slower) 486 partialAction='pkginfo'512 subordinate_action='pkginfo' 487 513 result=self._get_Extended_App_Info(result['data'],launchedby,fullsearch) 488 514 if launchedby: … … 514 540 return_msg=False 515 541 if (self._search_Store(appName,'search',True,action)): 516 applistInfo=self.result[action]['data']517 type Dict={}542 info_applist=self.result[action]['data'] 543 types_dict={} 518 544 #Check if package is installed if we want to remove it or vice versa 519 for app Info in applistInfo:545 for app_info in info_applist: 520 546 #Appstream doesn't get the right status in all cases so we rely on the mechanisms given by the different plugins. 521 if (action=='install' and app Info['state']=='installed') or (action=='remove' and appInfo['state']=='available'):522 if (action=='remove' and app Info['state']=='available'):523 self.result[action]['status']={app Info['package']:3}547 if (action=='install' and app_info['state']=='installed') or (action=='remove' and app_info['state']=='available'): 548 if (action=='remove' and app_info['state']=='available'): 549 self.result[action]['status']={app_info['package']:3} 524 550 self.result[action]['status']={'status':3} 525 551 else: 526 self.result[action]['status']={app Info['package']:4}552 self.result[action]['status']={app_info['package']:4} 527 553 self.result[action]['status']={'status':4} 528 554 pass 529 555 return_msg=False 530 type Dict={}556 types_dict={} 531 557 break 532 558 533 package_type=self._check_package_type(app Info)534 if package_type in type Dict:535 type Dict[package_type].append(appInfo)559 package_type=self._check_package_type(app_info) 560 if package_type in types_dict: 561 types_dict[package_type].append(app_info) 536 562 else: 537 type Dict[package_type]=[appInfo]538 539 for package_type in type Dict:563 types_dict[package_type]=[app_info] 564 565 for package_type in types_dict: 540 566 self._debug("Checking plugin for "+action+ " "+package_type) 541 if package_type in self. registeredPlugins[action]:542 install Function=self._execute_class_method(action,package_type,action)567 if package_type in self.plugins_registered[action]: 568 install_function=self._execute_class_method(action,package_type,action) 543 569 if package_type=='zmd': 544 570 #If it's a zmd the zomando must be present in the system 545 zmd AppInfo=[]546 for zmd Package in typeDict[package_type]:571 zmd_info=[] 572 for zmd_bundle in types_dict[package_type]: 547 573 zmdInfo={} 548 self._debug("Cheking presence of zmd "+ zmd Package['package'])549 zmd='/usr/share/zero-center/zmds/'+app Info['package']+'.zmd'574 self._debug("Cheking presence of zmd "+ zmd_bundle['package']) 575 zmd='/usr/share/zero-center/zmds/'+app_info['package']+'.zmd' 550 576 if not os.path.exists(zmd): 551 zmdInfo['package']=zmd Package['package']552 zmd AppInfo.append(zmdInfo)553 if zmd AppInfo:577 zmdInfo['package']=zmd_bundle['package'] 578 zmd_info.append(zmdInfo) 579 if zmd_info: 554 580 self._debug("Installing needed packages") 555 install AuxFunction=self._execute_class_method(action,"deb",action)556 result=install AuxFunction.execute_action(action,zmdAppInfo)581 install_depends_function=self._execute_class_method(action,"deb",action) 582 result=install_depends_function.execute_action(action,zmd_info) 557 583 558 result=install Function.execute_action(action,typeDict[package_type])584 result=install_function.execute_action(action,types_dict[package_type]) 559 585 self.result[action]=result 560 586 if result['status']['status']==0: 561 587 #Mark the apps as installed or available 562 for app in type Dict[package_type]:588 for app in types_dict[package_type]: 563 589 if action=='install': 564 590 app['appstream_id'].set_state(1) … … 579 605 # - String with the type (deb, sh, zmd...) 580 606 #### 581 def _check_package_type(self,app Info):607 def _check_package_type(self,app_info): 582 608 #Standalone installers must have the subcategory "installer" 583 609 #Zomandos must have the subcategory "Zomando" 584 self._debug("Checking package type for app "+app Info['name'])585 if "Zomando" in app Info['categories']:610 self._debug("Checking package type for app "+app_info['name']) 611 if "Zomando" in app_info['categories']: 586 612 return_msg="zmd" 587 613 else: 588 614 #Standalone installers must have an installerUrl field loaded from a bundle type=script description 589 if app Info['installerUrl']!='':615 if app_info['installerUrl']!='': 590 616 return_msg="sh" 591 elif app Info['appImage']!='':592 return_msg= "appimage"617 elif app_info['bundle']!='': 618 return_msg=app_info['bundle'] 593 619 else: 594 620 return_msg="deb"
Note: See TracChangeset
for help on using the changeset viewer.