nixWrapper.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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):
  46. #load library from git, store it at a default location and
  47. #add path to the python sys
  48. remoteSources=getResources()
  49. #two steps:
  50. #1 Download
  51. tempDir=os.path.join(os.path.expanduser('~'),'temp')
  52. if not os.path.isdir(tempDir):
  53. os.mkdir(tempDir)
  54. tempFile=os.path.join(tempDir,name+'.zip')
  55. http = urllib3.PoolManager()
  56. rsource=remoteSources[name]
  57. r = http.request('GET', rsource['url'], preload_content=False)
  58. chunk_size=65536
  59. with open(tempFile, 'wb') as out:
  60. while True:
  61. data = r.read(chunk_size)
  62. if not data:
  63. break
  64. out.write(data)
  65. r.release_conn()
  66. #2 Unzip
  67. installDir=getSuitePath()
  68. #3 remove existing copy
  69. finalName=os.path.join(installDir,name)
  70. if os.path.isdir(finalName):
  71. shutil.rmtree(finalName)
  72. #unzip
  73. with zipfile.ZipFile(tempFile,'r') as zip_ref:
  74. zip_ref.extractall(installDir)
  75. #cleanup
  76. os.remove(tempFile)
  77. #rename
  78. #this is the best guess of the relation between zip directory and name
  79. zipName=name.lower()+'-'+rsource['branch']
  80. os.rename(os.path.join(installDir,zipName),finalName)
  81. sys.path.append(finalName)
  82. def setConfig(labkeyUser,labkeyServer='https://merlin.fmf.uni-lj.si',\
  83. certificateZip=None):
  84. connectionConfig={}
  85. if certificateZip!=None:
  86. zpath=pathlib.Path(certificateZip)
  87. user=zpath.stem
  88. userDir=os.path.join(os.path.expanduser('~'),'.labkey',user)
  89. if not os.path.isdir(userDir):
  90. os.makedirs(userDir)
  91. caName=None
  92. with zipfile.ZipFile(certificateZip,'r') as zipObj:
  93. zipObj.extract(user+'.crt',userDir)
  94. zipObj.extract(user+'.key',userDir)
  95. zipList=zipObj.namelist()
  96. for f in zipList:
  97. if f.find('CA')>-1:
  98. caName=f
  99. zipObj.extract(f,userDir)
  100. #setup SSL
  101. sslSetup={}
  102. sslSetup['user']=os.path.join(userDir,user+'.crt')
  103. sslSetup['key']=os.path.join(userDir,user+'.key')
  104. sslSetup['ca']=os.path.join(userDir,caName)
  105. sslSetup['keyPwd']='notUsed'
  106. connectionConfig['SSL']=sslSetup
  107. connectionConfig["host"]=labkeyServer
  108. connectionConfig["context"]="labkey"
  109. labkeySetup={}
  110. labkeySetup['user']=labkeyUser
  111. labkeyPwd='guest'
  112. if not labkeyUser=='guest':
  113. labkeyPwd=getpass.getpass(prompt='Enter labkey password:')
  114. labkeySetup['password']=labkeyPwd
  115. connectionConfig['labkey']=labkeySetup
  116. orthancSetup={}
  117. if connectionConfig['host'].find('merlin')>-1:
  118. orthancSetup['server']='https://orthanc.fmf.uni-lj.si'
  119. if connectionConfig['host'].find('onko-nix')>-1:
  120. orthancSetup['server']='http://onko-nix.onko-i.si:8042'
  121. orthancSetup['user']='ask'
  122. orthancSetup['password']='askPassword'
  123. connectionConfig['orthanc']=orthancSetup
  124. net=labkeyInterface.labkeyInterface()
  125. net.connectionConfig=connectionConfig
  126. net.initRemote()
  127. print(net.getUserId())
  128. return net
  129. def testCertificate(certificateZip):
  130. return setConfig('guest',certificateZip=certificateZip)
  131. def testConnection(labkeyUser,labkeyServer='https://merlin.fmf.uni-lj.si',\
  132. certificateZip=None):
  133. return setConfig(labkeyUser,labkeyServer,certificateZip)
  134. def getDefaultConfig(configFile):
  135. #if configFile is None, this will set it to default and leave unchanged otherwise
  136. if configFile==None:
  137. return os.path.join(os.path.expanduser('~'),'.labkey','network.json')
  138. return configFile
  139. def storeConfig(net,configFile=None):
  140. #if configFile is None, this will set it to default and leave unchanged otherwise
  141. with open(getDefaultConfig(configFile),'w') as f:
  142. json.dump(net.connectionConfig,f,indent='\t')
  143. def getInterface(configFile=None):
  144. net=labkeyInterface.labkeyInterface()
  145. #if configFile is None, this will set it to default and leave unchanged otherwise
  146. net.init(getDefaultConfig(configFile))
  147. return net
  148. #loadLibrary('labkeyInterface')