locdownload.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. """
  2. @package startup.locdownload
  3. @brief GRASS Location Download Management
  4. Classes:
  5. - LocationDownloadPanel
  6. - LocationDownloadDialog
  7. - DownloadError
  8. (C) 2017 by Vaclav Petras the GRASS Development Team
  9. This program is free software under the GNU General Public License
  10. (>=v2). Read the file COPYING that comes with GRASS for details.
  11. @author Vaclav Petras <wenzeslaus gmail com>
  12. """
  13. from __future__ import print_function
  14. import os
  15. import sys
  16. import tempfile
  17. import shutil
  18. import time
  19. try:
  20. from urllib2 import HTTPError, URLError
  21. from urllib import urlopen, urlretrieve
  22. except ImportError:
  23. # there is also HTTPException, perhaps change to list
  24. from urllib.error import HTTPError, URLError
  25. from urllib.request import urlopen, urlretrieve
  26. import wx
  27. from wx.lib.newevent import NewEvent
  28. from grass.script import debug
  29. from grass.script.utils import try_rmdir
  30. from grass.script.setup import set_gui_path
  31. set_gui_path()
  32. from core.debug import Debug
  33. from core.utils import _
  34. from core.gthread import gThread
  35. from gui_core.wrap import Button
  36. # TODO: labels (and descriptions) translatable?
  37. LOCATIONS = [
  38. {
  39. "label": "Complete NC location",
  40. "url": "https://grass.osgeo.org/sampledata/north_carolina/nc_spm_08_grass7.tar.gz",
  41. },
  42. {
  43. "label": "Basic NC location",
  44. "url": "https://grass.osgeo.org/sampledata/north_carolina/nc_basic_spm_grass7.tar.gz",
  45. },
  46. {
  47. "label": "World location in LatLong/WGS84",
  48. "url": "https://grass.osgeo.org/sampledata/worldlocation.tar.gz",
  49. },
  50. {
  51. "label": "Spearfish (SD) location",
  52. "url": "https://grass.osgeo.org/sampledata/spearfish_grass70data-0.3.tar.gz",
  53. },
  54. {
  55. "label": "Piemonte, Italy data set",
  56. "url": "http://geodati.fmach.it/gfoss_geodata/libro_gfoss/grassdata_piemonte_utm32n_wgs84_grass7.tar.gz",
  57. },
  58. {
  59. "label": "Slovakia 3D precipitation voxel data set",
  60. "url": "https://grass.osgeo.org/uploads/grass/sampledata/slovakia3d_grass7.tar.gz",
  61. },
  62. {
  63. "label": "Fire simulation sample data",
  64. "url": "https://grass.osgeo.org/sampledata/fire_grass6data.tar.gz",
  65. },
  66. ]
  67. class DownloadError(Exception):
  68. """Error happened during download or when processing the file"""
  69. pass
  70. class RedirectText(object):
  71. def __init__(self, window):
  72. self.out = window
  73. def write(self, string):
  74. try:
  75. wx.CallAfter(self.out.SetLabel, string)
  76. except:
  77. # window closed -> PyDeadObjectError
  78. pass
  79. # copy from g.extension, potentially move to library
  80. def move_extracted_files(extract_dir, target_dir, files):
  81. """Fix state of extracted file by moving them to different diretcory
  82. When extracting, it is not clear what will be the root directory
  83. or if there will be one at all. So this function moves the files to
  84. a different directory in the way that if there was one directory extracted,
  85. the contained files are moved.
  86. """
  87. debug("move_extracted_files({0})".format(locals()))
  88. if len(files) == 1:
  89. shutil.copytree(os.path.join(extract_dir, files[0]), target_dir)
  90. else:
  91. if not os.path.exists(target_dir):
  92. os.mkdir(target_dir)
  93. for file_name in files:
  94. actual_file = os.path.join(extract_dir, file_name)
  95. if os.path.isdir(actual_file):
  96. # copy_tree() from distutils failed to create
  97. # directories before copying files time to time
  98. # (when copying to recently deleted directory)
  99. shutil.copytree(actual_file,
  100. os.path.join(target_dir, file_name))
  101. else:
  102. shutil.copy(actual_file, os.path.join(target_dir, file_name))
  103. # copy from g.extension, potentially move to library
  104. def extract_zip(name, directory, tmpdir):
  105. """Extract a ZIP file into a directory"""
  106. debug("extract_zip(name={name}, directory={directory},"
  107. " tmpdir={tmpdir})".format(name=name, directory=directory,
  108. tmpdir=tmpdir), 3)
  109. try:
  110. import zipfile
  111. zip_file = zipfile.ZipFile(name, mode='r')
  112. file_list = zip_file.namelist()
  113. # we suppose we can write to parent of the given dir
  114. # (supposing a tmp dir)
  115. extract_dir = os.path.join(tmpdir, 'extract_dir')
  116. os.mkdir(extract_dir)
  117. for subfile in file_list:
  118. # this should be safe in Python 2.7.4
  119. zip_file.extract(subfile, extract_dir)
  120. files = os.listdir(extract_dir)
  121. move_extracted_files(extract_dir=extract_dir,
  122. target_dir=directory, files=files)
  123. except zipfile.BadZipfile as error:
  124. raise DownloadError(_("ZIP file is unreadable: {0}").format(error))
  125. # copy from g.extension, potentially move to library
  126. def extract_tar(name, directory, tmpdir):
  127. """Extract a TAR or a similar file into a directory"""
  128. debug("extract_tar(name={name}, directory={directory},"
  129. " tmpdir={tmpdir})".format(name=name, directory=directory,
  130. tmpdir=tmpdir), 3)
  131. try:
  132. import tarfile # we don't need it anywhere else
  133. tar = tarfile.open(name)
  134. extract_dir = os.path.join(tmpdir, 'extract_dir')
  135. os.mkdir(extract_dir)
  136. tar.extractall(path=extract_dir)
  137. files = os.listdir(extract_dir)
  138. move_extracted_files(extract_dir=extract_dir,
  139. target_dir=directory, files=files)
  140. except tarfile.TarError as error:
  141. raise DownloadError(_("Archive file is unreadable: {0}").format(error))
  142. extract_tar.supported_formats = ['tar.gz', 'gz', 'bz2', 'tar', 'gzip', 'targz']
  143. # based on https://blog.shichao.io/2012/10/04/progress_speed_indicator_for_urlretrieve_in_python.html
  144. def reporthook(count, block_size, total_size):
  145. global start_time
  146. if count == 0:
  147. start_time = time.time()
  148. return
  149. duration = time.time() - start_time
  150. progress_size = int(count * block_size)
  151. speed = int(progress_size / (1024 * duration))
  152. percent = int(count * block_size * 100 / total_size)
  153. sys.stdout.write("Download in progress ...\n%d%%, %d MB, %d KB/s, %d seconds passed" %
  154. (percent, progress_size / (1024 * 1024), speed, duration))
  155. # based on g.extension, potentially move to library
  156. def download_end_extract(source):
  157. """Download a file (archive) from URL and uncompress it"""
  158. tmpdir = tempfile.mkdtemp()
  159. directory = os.path.join(tmpdir, 'location')
  160. if source.endswith('.zip'):
  161. archive_name = os.path.join(tmpdir, 'location.zip')
  162. filename, headers = urlretrieve(source, archive_name, reporthook)
  163. if headers.get('content-type', '') != 'application/zip':
  164. raise DownloadError(
  165. _("Download of <{url}> failed"
  166. " or file <{name}> is not a ZIP file").format(
  167. url=source, name=filename))
  168. extract_zip(name=archive_name, directory=directory, tmpdir=tmpdir)
  169. elif (source.endswith(".tar.gz") or
  170. source.rsplit('.', 1)[1] in extract_tar.supported_formats):
  171. if source.endswith(".tar.gz"):
  172. ext = "tar.gz"
  173. else:
  174. ext = source.rsplit('.', 1)[1]
  175. archive_name = os.path.join(tmpdir, 'extension.' + ext)
  176. urlretrieve(source, archive_name, reporthook)
  177. # TODO: error handling for urlretrieve
  178. extract_tar(name=archive_name, directory=directory, tmpdir=tmpdir)
  179. else:
  180. # probably programmer error
  181. raise DownloadError(_("Unknown format '{0}'.").format(source))
  182. assert os.path.isdir(directory)
  183. return directory
  184. def download_location(url, name, database):
  185. """Wrapper to return DownloadError by value
  186. It also moves the location directory to the database.
  187. """
  188. try:
  189. # TODO: the unpacking could go right to the path (but less
  190. # robust) or replace copytree here with move
  191. directory = download_end_extract(source=url)
  192. destination = os.path.join(database, name)
  193. if not is_location_valid(directory):
  194. return _("Downloaded location is not valid")
  195. shutil.copytree(src=directory, dst=destination)
  196. try_rmdir(directory)
  197. except DownloadError as error:
  198. return error
  199. return None
  200. # based on grass.py (to be moved to future "grass.init")
  201. def is_location_valid(location):
  202. """Return True if GRASS Location is valid
  203. :param location: path of a Location
  204. """
  205. # DEFAULT_WIND file should not be required until you do something
  206. # that actually uses them. The check is just a heuristic; a directory
  207. # containing a PERMANENT/DEFAULT_WIND file is probably a GRASS
  208. # location, while a directory lacking it probably isn't.
  209. # TODO: perhaps we can relax this and require only permanent
  210. return os.access(os.path.join(location,
  211. "PERMANENT", "DEFAULT_WIND"), os.F_OK)
  212. def location_name_from_url(url):
  213. """Create location name from URL"""
  214. return url.rsplit('/', 1)[1].split('.', 1)[0].replace("-", "_").replace(" ", "_")
  215. DownloadDoneEvent, EVT_DOWNLOAD_DONE = NewEvent()
  216. class LocationDownloadPanel(wx.Panel):
  217. """Panel to select and initiate downloads of locations.
  218. Has a place to report errors to user and also any potential problems
  219. before the user hits the button.
  220. In the future, it can potentially show also some details about what
  221. will be downloaded. The choice widget can be also replaced.
  222. For the future, there can be multiple panels with different methods
  223. or sources, e.g. direct input of URL. These can be in separate tabs
  224. of one panel (perhaps sharing the common background download and
  225. message logic).
  226. """
  227. def __init__(self, parent, database, locations=LOCATIONS):
  228. """
  229. :param database: directory with G database to download to
  230. :param locations: list of dictionaries with label and url
  231. """
  232. wx.Panel.__init__(self, parent=parent)
  233. self._last_downloaded_location_name = None
  234. self._download_in_progress = False
  235. self.database = database
  236. self.locations = locations
  237. self.label = wx.StaticText(
  238. parent=self,
  239. label=_("Select sample location to download:"))
  240. choices = []
  241. for item in self.locations:
  242. choices.append(item['label'])
  243. self.choice = wx.Choice(parent=self, choices=choices)
  244. self.choice.Bind(wx.EVT_CHOICE, self.OnChangeChoice)
  245. self.download_button = Button(parent=self, id=wx.ID_ANY,
  246. label=_("Do&wnload"))
  247. self.download_button.SetToolTip(_("Download selected location"))
  248. self.download_button.Bind(wx.EVT_BUTTON, self.OnDownload)
  249. # TODO: add button for a link to an associated website?
  250. # TODO: add thumbnail for each location?
  251. # TODO: messages copied from gis_set.py, need this as API?
  252. self.message = wx.StaticText(parent=self, size=(-1, 50))
  253. sys.stdout = RedirectText(self.message)
  254. # It is not clear if all wx versions supports color, so try-except.
  255. # The color itself may not be correct for all platforms/system settings
  256. # but in http://xoomer.virgilio.it/infinity77/wxPython/Widgets/wx.SystemSettings.html
  257. # there is no 'warning' color.
  258. try:
  259. self.message.SetForegroundColour(wx.Colour(255, 0, 0))
  260. except AttributeError:
  261. pass
  262. self._layout()
  263. default = 0
  264. self.choice.SetSelection(default)
  265. self.CheckItem(self.locations[default])
  266. self.thread = gThread()
  267. def _layout(self):
  268. """Create and layout sizers"""
  269. vertical = wx.BoxSizer(wx.VERTICAL)
  270. self.sizer = vertical
  271. vertical.Add(self.label, proportion=0,
  272. flag=wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border=10)
  273. vertical.Add(self.choice, proportion=0,
  274. flag=wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border=10)
  275. button_sizer = wx.BoxSizer(wx.HORIZONTAL)
  276. button_sizer.AddStretchSpacer()
  277. button_sizer.Add(self.download_button, proportion=0)
  278. vertical.Add(button_sizer, proportion=0,
  279. flag=wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT | wx.ALIGN_RIGHT, border=10)
  280. vertical.AddStretchSpacer()
  281. vertical.Add(self.message, proportion=0,
  282. flag=wx.ALIGN_CENTER_VERTICAL |
  283. wx.ALIGN_LEFT | wx.ALL | wx.EXPAND, border=10)
  284. self.SetSizer(vertical)
  285. vertical.Fit(self)
  286. self.Layout()
  287. self.SetMinSize(self.GetBestSize())
  288. def OnDownload(self, event):
  289. """Handle user-initiated action of download"""
  290. Debug.msg(1, "OnDownload")
  291. if self._download_in_progress:
  292. self._warning(_("Download in progress, wait until it is finished"))
  293. index = self.choice.GetSelection()
  294. self.DownloadItem(self.locations[index])
  295. def DownloadItem(self, item):
  296. """Download the selected item"""
  297. Debug.msg(1, "DownloadItem: %s" % item)
  298. # similar code as in CheckItem
  299. url = item['url']
  300. dirname = location_name_from_url(url)
  301. destination = os.path.join(self.database, dirname)
  302. if os.path.exists(destination):
  303. self._error(_("Location named <%s> already exists,"
  304. " download canceled") % dirname)
  305. return
  306. def download_complete_callback(event):
  307. self._download_in_progress = False
  308. errors = event.ret
  309. if errors:
  310. self._error(_("Download failed: %s") % errors)
  311. else:
  312. self._last_downloaded_location_name = dirname
  313. self._warning(_("Download completed"))
  314. self._download_in_progress = True
  315. self._warning(_("Download in progress..."))
  316. self.thread.Run(callable=download_location,
  317. url=url, name=dirname, database=self.database,
  318. ondone=download_complete_callback)
  319. def OnChangeChoice(self, event):
  320. """React to user changing the selection"""
  321. index = self.choice.GetSelection()
  322. self.CheckItem(self.locations[index])
  323. def CheckItem(self, item):
  324. """Check what user selected and report potential issues"""
  325. # similar code as in DownloadItem
  326. url = item['url']
  327. dirname = location_name_from_url(url)
  328. destination = os.path.join(self.database, dirname)
  329. if os.path.exists(destination):
  330. self._warning(_("Location named <%s> already exists,"
  331. " rename it first") % dirname)
  332. return
  333. else:
  334. self._clearMessage()
  335. def GetLocation(self):
  336. """Get the name of the last location downloaded by the user"""
  337. return self._last_downloaded_location_name
  338. def _warning(self, text):
  339. """Displays a warning, hint or info message to the user.
  340. This function can be used for all kinds of messages except for
  341. error messages.
  342. .. note::
  343. There is no cleaning procedure. You should call
  344. _clearMessage() when you know that there is everything
  345. correct.
  346. """
  347. self.message.SetLabel(text)
  348. self.sizer.Layout()
  349. def _error(self, text):
  350. """Displays a error message to the user.
  351. This function should be used only when something serious and unexpected
  352. happens, otherwise _showWarning should be used.
  353. .. note::
  354. There is no cleaning procedure. You should call
  355. _clearMessage() when you know that there is everything
  356. correct.
  357. """
  358. self.message.SetLabel(_("Error: {text}").format(text=text))
  359. self.sizer.Layout()
  360. def _clearMessage(self):
  361. """Clears/hides the error message."""
  362. # we do no hide widget
  363. # because we do not want the dialog to change the size
  364. self.message.SetLabel("")
  365. self.sizer.Layout()
  366. class LocationDownloadDialog(wx.Dialog):
  367. """Dialog for download of locations
  368. Contains the panel and Cancel button.
  369. """
  370. def __init__(self, parent, database,
  371. title=_("GRASS GIS Location Download")):
  372. """
  373. :param database: database to download the location to
  374. :param title: window title if the default is not appropriate
  375. """
  376. wx.Dialog.__init__(self, parent=parent, title=title)
  377. self.panel = LocationDownloadPanel(parent=self, database=database)
  378. close_button = Button(self, id=wx.ID_CLOSE)
  379. # TODO: terminate download process
  380. close_button.Bind(wx.EVT_BUTTON, lambda event: self.Close())
  381. sizer = wx.BoxSizer(wx.VERTICAL)
  382. sizer.Add(self.panel, proportion=1, flag=wx.EXPAND)
  383. button_sizer = wx.StdDialogButtonSizer()
  384. button_sizer.Add(close_button)
  385. button_sizer.Realize()
  386. sizer.Add(button_sizer, proportion=0,
  387. flag=wx.ALIGN_RIGHT | wx.BOTTOM, border=10)
  388. self.SetSizer(sizer)
  389. sizer.Fit(self)
  390. self.Layout()
  391. def GetLocation(self):
  392. """Get the name of the last location downloaded by the user"""
  393. return self.panel.GetLocation()
  394. def main():
  395. """Tests the download dialog"""
  396. if len(sys.argv) < 2:
  397. sys.exit("Provide a test directory")
  398. database = sys.argv[1]
  399. app = wx.App()
  400. if len(sys.argv) == 2 or sys.argv[2] == 'dialog':
  401. window = LocationDownloadDialog(parent=None, database=database)
  402. window.ShowModal()
  403. location = window.GetLocation()
  404. if location:
  405. print(location)
  406. window.Destroy()
  407. elif sys.argv[2] == 'panel':
  408. window = wx.Dialog(parent=None)
  409. panel = LocationDownloadPanel(parent=window, database=database)
  410. window.ShowModal()
  411. location = panel.GetLocation()
  412. if location:
  413. print(location)
  414. window.Destroy()
  415. else:
  416. print("Unknown settings: try dialog or panel")
  417. app.MainLoop()
  418. if __name__ == '__main__':
  419. main()