nixWrapper.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. import sys
  2. import os
  3. import urllib3
  4. import shutil
  5. import zipfile
  6. import pathlib
  7. import json
  8. import getpass
  9. import chardet
  10. import base64
  11. #this is meant to be used as a startup script
  12. #all commands will be executed when python -m script -i is used
  13. #generic function to load library from gitlab
  14. def getSuitePath():
  15. installDir=os.path.join(os.path.expanduser('~'),'.labkey','software','src')
  16. if not os.path.isdir(installDir):
  17. os.makedirs(installDir)
  18. return installDir
  19. def buildGITURL(server,project,path,branch='master'):
  20. projectURL='%2f'.join(project)
  21. pathURL='%2f'.join(path)
  22. return server+'/api/v4/projects/'+projectURL+'/repository/files/'+pathURL+'?ref='+branch
  23. def getResources():
  24. server='http://wiscigt.powertheword.com'
  25. project=['labkey','nixsuite']
  26. path=['remoteResources','resources.json']
  27. remoteSourcesURL=buildGITURL(server,project,path)
  28. http = urllib3.PoolManager()
  29. r = http.request('GET', remoteSourcesURL)
  30. #returns a JSON
  31. encoding=chardet.detect(r.data)['encoding']
  32. jsonData=json.loads(r.data.decode(encoding))
  33. #we are interested in content, do looped way of decoding it
  34. b64_bytes=jsonData['content'].encode('ascii')
  35. m_bytes=base64.b64decode(b64_bytes)
  36. m=m_bytes.decode('ascii')
  37. return json.loads(m)
  38. def loadModule(slicer,qt,name,moduleName):
  39. loadLibrary(name)
  40. modulePath=os.path.join(getSuitePath(),name,'slicerModules',moduleName+'.py')
  41. factoryManager = slicer.app.moduleManager().factoryManager()
  42. factoryManager.registerModule(qt.QFileInfo(modulePath))
  43. factoryManager.loadModules([moduleName,])
  44. slicer.util.selectModule(moduleName)
  45. def loadLibrary(name,doReload=True):
  46. installDir=getSuitePath()
  47. finalName=os.path.join(installDir,name)
  48. if os.path.isdir(finalName):
  49. if not doReload:
  50. #1 keep existing copy, return
  51. sys.path.append(finalName)
  52. return
  53. else:
  54. #1 remove existing copy
  55. shutil.rmtree(finalName)
  56. #load library from git, store it at a default location and
  57. #add path to the python sys
  58. remoteSources=getResources()
  59. #two steps:
  60. #1 Download
  61. tempDir=os.path.join(os.path.expanduser('~'),'temp')
  62. if not os.path.isdir(tempDir):
  63. os.mkdir(tempDir)
  64. tempFile=os.path.join(tempDir,name+'.zip')
  65. http = urllib3.PoolManager()
  66. rsource=remoteSources[name]
  67. r = http.request('GET', rsource['url'], preload_content=False)
  68. chunk_size=65536
  69. with open(tempFile, 'wb') as out:
  70. while True:
  71. data = r.read(chunk_size)
  72. if not data:
  73. break
  74. out.write(data)
  75. r.release_conn()
  76. #2 Unzip
  77. with zipfile.ZipFile(tempFile,'r') as zip_ref:
  78. zip_ref.extractall(installDir)
  79. #cleanup
  80. os.remove(tempFile)
  81. #rename
  82. #this is the best guess of the relation between zip directory and name
  83. try:
  84. zipName=name.lower()+'-'+rsource['branch']
  85. os.rename(os.path.join(installDir,zipName),finalName)
  86. except FileNotFoundError:
  87. zipName=name+'-'+rsource['branch']
  88. os.rename(os.path.join(installDir,zipName),finalName)
  89. sys.path.append(finalName)
  90. def setConfig(labkeyUser,labkeyServer='https://merlin.fmf.uni-lj.si',\
  91. certificateZip=None):
  92. connectionConfig={}
  93. if certificateZip!=None:
  94. zpath=pathlib.Path(certificateZip)
  95. user=zpath.stem
  96. userDir=os.path.join(os.path.expanduser('~'),'.labkey',user)
  97. if not os.path.isdir(userDir):
  98. os.makedirs(userDir)
  99. caName=None
  100. with zipfile.ZipFile(certificateZip,'r') as zipObj:
  101. zipObj.extract(user+'.crt',userDir)
  102. zipObj.extract(user+'.key',userDir)
  103. zipList=zipObj.namelist()
  104. for f in zipList:
  105. if f.find('CA')>-1:
  106. caName=f
  107. zipObj.extract(f,userDir)
  108. #setup SSL
  109. sslSetup={}
  110. sslSetup['user']=os.path.join(userDir,user+'.crt')
  111. sslSetup['key']=os.path.join(userDir,user+'.key')
  112. sslSetup['ca']=os.path.join(userDir,caName)
  113. sslSetup['keyPwd']='notUsed'
  114. connectionConfig['SSL']=sslSetup
  115. connectionConfig["host"]=labkeyServer
  116. connectionConfig["context"]="labkey"
  117. labkeySetup={}
  118. labkeySetup['user']=labkeyUser
  119. labkeyPwd='guest'
  120. if not labkeyUser=='guest':
  121. labkeyPwd=getpass.getpass(prompt='Enter labkey password:')
  122. labkeySetup['password']=labkeyPwd
  123. connectionConfig['labkey']=labkeySetup
  124. orthancSetup={}
  125. if connectionConfig['host'].find('merlin')>-1:
  126. orthancSetup['server']='https://orthanc.fmf.uni-lj.si'
  127. if connectionConfig['host'].find('onko-nix')>-1:
  128. orthancSetup['server']='http://onko-nix.onko-i.si:8042'
  129. orthancSetup['user']='ask'
  130. orthancSetup['password']='askPassword'
  131. connectionConfig['orthanc']=orthancSetup
  132. net=labkeyInterface.labkeyInterface()
  133. net.connectionConfig=connectionConfig
  134. net.initRemote()
  135. print(net.getUserId())
  136. return net
  137. def testCertificate(certificateZip):
  138. return setConfig('guest',certificateZip=certificateZip)
  139. def testConnection(labkeyUser,labkeyServer='https://merlin.fmf.uni-lj.si',\
  140. certificateZip=None):
  141. return setConfig(labkeyUser,labkeyServer,certificateZip)
  142. def getDefaultConfig(configFile):
  143. #if configFile is None, this will set it to default and leave unchanged otherwise
  144. if configFile==None:
  145. return os.path.join(os.path.expanduser('~'),'.labkey','network.json')
  146. return configFile
  147. def storeConfig(net,configFile=None):
  148. #if configFile is None, this will set it to default and leave unchanged otherwise
  149. with open(getDefaultConfig(configFile),'w') as f:
  150. json.dump(net.connectionConfig,f,indent='\t')
  151. def getInterface(configFile=None):
  152. net=labkeyInterface.labkeyInterface()
  153. #if configFile is None, this will set it to default and leave unchanged otherwise
  154. net.init(getDefaultConfig(configFile))
  155. return net
  156. #loadLibrary('labkeyInterface')