<commit_before>__author__ = "AstroPrint Product Team <<EMAIL>>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 3DaGoGo, Inc - Released under terms of the AGPLv3 License"

import logging
import os
import threading
import sarge
import pyudev
import time

from glob import glob

from octoprint.events import Events

from .base import ExternalDriveBase

#
# Thread to get some plugged usb drive
#
class ExternalDriveManager(ExternalDriveBase):
	ROOT_MOUNT_POINT = '/media/astrobox'

	def __init__(self):
		super(ExternalDriveManager, self).__init__()
		self.stopThread = False
		self._monitor = None
		self._monitorThread = threading.Thread(target=self._monitorLoop)
		self._monitorThread.daemon = True
		self._mountPoints = None
		self._logger = logging.getLogger(__name__)
		self._logger.info('Starting Linux ExternalDriveManager')
		self._monitorThread.start()

	def getRemovableDrives(self):
		return self.getDirContents('%s/*/*' % self.ROOT_MOUNT_POINT, 'usb')

	def _monitorLoop(self):
		context = pyudev.Context()

		#Check the status of the system right now
		# 1. Check if we have any drives connected
		for d in context.list_devices(subsystem='block', DEVTYPE='disk'):
			if d.attributes.asbool('removable'):
				#it's removable media, let's find the partitions
				partitions = list(context.list_devices(subsystem='block', DEVTYPE='partition', parent=d))
				for p in partitions:
					# we only analyze the first one, ignore other partitions
					#p = partitions[0]

					#check if the partition is mounted
					mountPoint = self._findMountPoint(p.device_node)
					if mountPoint:
						self._logger.info('Found mounted removable drive (%s) at %s' % (p.device_node, mountPoint))
					else:
						self._logger.info('Mounting inserted removable drive (%s)' % p.device_node)
						self._mountPartition(p.device_node, self._getDeviceMountDirectory(p))

		# 2. Check if there are left over directories with no drives mounted
		for f in glob('%s/*/*' % self.ROOT_MOUNT_POINT):
			if os.path.isdir(f) and not os.listdir(f):
				#empty directory found, let's see if it's mounted
				if not self._isMounted(f):
					#Not mounted and empty, delete directory.
					os.rmdir(f) #main dir
					os.rmdir('/'.join(f.split('/')[:-1])) #uuid dir

		self._mountPoints = None # We reset here since we don't need it anymore, it will be re-created on shutdown

		# Start listening for events
		self._monitor = pyudev.Monitor.from_netlink(context)
		self._monitor.filter_by(subsystem='block')

		for device in iter(self.monitor.poll, None):

			if self.stopThread:
				self._monitor.stop()
				return

			if device.device_type == 'partition':
				if device.action == 'add':
					devName = device.device_node
					self._logger.info('%s pluged in' % devName)<commit_msg>fix: missing _ in variable name<commit_after>__author__ = "AstroPrint Product Team <<EMAIL>>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 3DaGoGo, Inc - Released under terms of the AGPLv3 License"

import logging
import os
import threading
import sarge
import pyudev
import time

from glob import glob

from octoprint.events import Events

from .base import ExternalDriveBase

#
# Thread to get some plugged usb drive
#
class ExternalDriveManager(ExternalDriveBase):
	ROOT_MOUNT_POINT = '/media/astrobox'

	def __init__(self):
		super(ExternalDriveManager, self).__init__()
		self.stopThread = False
		self._monitor = None
		self._monitorThread = threading.Thread(target=self._monitorLoop)
		self._monitorThread.daemon = True
		self._mountPoints = None
		self._logger = logging.getLogger(__name__)
		self._logger.info('Starting Linux ExternalDriveManager')
		self._monitorThread.start()

	def getRemovableDrives(self):
		return self.getDirContents('%s/*/*' % self.ROOT_MOUNT_POINT, 'usb')

	def _monitorLoop(self):
		context = pyudev.Context()

		#Check the status of the system right now
		# 1. Check if we have any drives connected
		for d in context.list_devices(subsystem='block', DEVTYPE='disk'):
			if d.attributes.asbool('removable'):
				#it's removable media, let's find the partitions
				partitions = list(context.list_devices(subsystem='block', DEVTYPE='partition', parent=d))
				for p in partitions:
					# we only analyze the first one, ignore other partitions
					#p = partitions[0]

					#check if the partition is mounted
					mountPoint = self._findMountPoint(p.device_node)
					if mountPoint:
						self._logger.info('Found mounted removable drive (%s) at %s' % (p.device_node, mountPoint))
					else:
						self._logger.info('Mounting inserted removable drive (%s)' % p.device_node)
						self._mountPartition(p.device_node, self._getDeviceMountDirectory(p))

		# 2. Check if there are left over directories with no drives mounted
		for f in glob('%s/*/*' % self.ROOT_MOUNT_POINT):
			if os.path.isdir(f) and not os.listdir(f):
				#empty directory found, let's see if it's mounted
				if not self._isMounted(f):
					#Not mounted and empty, delete directory.
					os.rmdir(f) #main dir
					os.rmdir('/'.join(f.split('/')[:-1])) #uuid dir

		self._mountPoints = None # We reset here since we don't need it anymore, it will be re-created on shutdown

		# Start listening for events
		self._monitor = pyudev.Monitor.from_netlink(context)
		self._monitor.filter_by(subsystem='block')

		for device in iter(self._monitor.poll, None):

			if self.stopThread:
				self._monitor.stop()
				return

			if device.device_type == 'partition':
				if device.action == 'add':
					devName = device.device_node
					self._logger.info('%s pluged in' % devName)
{'fraction_non_alphanumeric': 0.10794153900334566, 'fraction_numerical': 0.0035217467864060575, 'mean_word_length': 4.144927536231884, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '959308', 'n_tokens_mistral': 2051, 'n_tokens_neox': 1721, 'n_words': 517}