<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 subprocess
import os
import threading
import time

from sys import platform

from astroprint.printer.manager import printerManager

from octoprint.events import eventManager, Events
from octoprint.settings import settings

class FilesSystemReadyWorker(threading.Thread):

	def __init__(self, device, action):
		super(FilesSystemReadyWorker,self).__init__()
		self.daemon = True

		self.device = device

		self.action = action

		path = settings().getBaseFolder('storageLocation').replace('//','/')

		self.previousStorages = printerManager().fileManager.getLocalStorageLocations()


	def run(self):
		newStorageFound = False

		while not newStorageFound:
			time.sleep(0.5)
			currentStorages = printerManager().fileManager.getLocalStorageLocations()
			newStorageFound = (self.previousStorages != printerManager().fileManager.getLocalStorageLocations())

		if action == 'PLUG IN':

			eventManager().fire(
				Events.EXTERNAL_DRIVE_PLUGGED, {
					"device": self.device.sys_name
				}
			)

		else if action == 'EJECTION':

			eventManager().fire(
				Events.EXTERNAL_DRIVE_EJECTED, {
					"device": self.device.sys_name
				}
			)

		else:#action = 'REMOVED'

			eventManager().fire(
				Events.EXTERNAL_DRIVE_PHISICALLY_REMOVED, {
					"device": self.device.sys_name
				}
			)

# singleton
_instance = None

def externalDriveManager():
	global _instance

	if _instance is None:
		if platform == "linux" or platform == "linux2":
			_instance = ExternalDriveManager(True)

		elif platform == "darwin":
			_instance = ExternalDriveManager(False)
			logger = logging.getLogger(__name__)
			logger.info('darwin platform is not able to watch external drives plugging...')

	return _instance


import pyudev

#
# Thread to get some plugged usb drive
#
class ExternalDriveManager(threading.Thread):
	def __init__(self, enablingPluggedEvent):
		super(ExternalDriveManager, self).__init__()
		self.daemon = True
		self.stopThread = False
		self.enablingPluggedEvent = enablingPluggedEvent

		if enablingPluggedEvent:
			self.context = pyudev.Context()
			self.monitor = pyudev.Monitor.from_netlink(self.context)
			self.monitor.filter_by(subsystem='usb')

		self._logger = logging.getLogger(__name__)

	def run(self):
		if self.enablingPluggedEvent:
			for device in iter(self.monitor.poll, None):
				if self.stopThread:
					self.monitor.stop()
					return

				if device.device_type == 'usb_device':
					if device.action == 'add':
						self._logger.info('{} connected'.format(device))
						FilesSystemReadyWorker(device,'PLUG IN').start()

					if device.action == 'remove':
						self._logger.info('{} disconnected'.format(device))
						FilesSystemReadyWorker(device,'REMOVED').start()


	def shutdown(self):
		self._logger.info('Shutting Down ExternalDriveManager')

		if self.enablingPluggedEvent:
			self.stopThread = True

		global _instance
		_instance = None


	def _cleanFileLocation(self, location):
		locationParsed = location.replace('//','/')
		return locationParsed


	def eject(self, drive):
		args = ['eject', settings().getBaseFolder('storageLocation').replace('//','/') + drive]

		try:
			ejectProccess = subprocess.Popen(
				args,
				stdout=subprocess.PIPE
			)

			FilesSystemReadyWorker(device,'EJECTION').start()

			return {'result': True}

		except Exception, error:

			self._logger.error('Error ejecting drive %s: %s' %  (drive,str(error)))

			return {
				'result': False,
				'error': str(error)
			}

	def copy(self, src, dst, progressCb, observerId):

			blksize = 1048576 # 1MiB
			try:
					s = open(src, 'rb')
					d = open(dst, 'wb')
			except (KeyboardInterrupt, Exception) as e:
					if 's' in locals():
							s.close()
					if 'd' in locals():
							d.close()
					raise
			try:
					total = float(os.stat(src).st_size)

					while True:
							buf = s.read(blksize)
							bytes_written = d.write(buf)<commit_msg>right accessing to action<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 subprocess
import os
import threading
import time

from sys import platform

from astroprint.printer.manager import printerManager

from octoprint.events import eventManager, Events
from octoprint.settings import settings

class FilesSystemReadyWorker(threading.Thread):

	def __init__(self, device, action):
		super(FilesSystemReadyWorker,self).__init__()
		self.daemon = True

		self.device = device

		self.action = action

		path = settings().getBaseFolder('storageLocation').replace('//','/')

		self.previousStorages = printerManager().fileManager.getLocalStorageLocations()


	def run(self):
		newStorageFound = False

		while not newStorageFound:
			time.sleep(0.5)
			currentStorages = printerManager().fileManager.getLocalStorageLocations()
			newStorageFound = (self.previousStorages != printerManager().fileManager.getLocalStorageLocations())

		if self.action == 'PLUG IN':

			eventManager().fire(
				Events.EXTERNAL_DRIVE_PLUGGED, {
					"device": self.device.sys_name
				}
			)

		elif self.action == 'EJECTION':

			eventManager().fire(
				Events.EXTERNAL_DRIVE_EJECTED, {
					"device": self.device
				}
			)

		else:#self.action == 'REMOVED'

			eventManager().fire(
				Events.EXTERNAL_DRIVE_PHISICALLY_REMOVED, {
					"device": self.device.sys_name
				}
			)

# singleton
_instance = None

def externalDriveManager():
	global _instance

	if _instance is None:
		if platform == "linux" or platform == "linux2":
			_instance = ExternalDriveManager(True)

		elif platform == "darwin":
			_instance = ExternalDriveManager(False)
			logger = logging.getLogger(__name__)
			logger.info('darwin platform is not able to watch external drives plugging...')

	return _instance


import pyudev

#
# Thread to get some plugged usb drive
#
class ExternalDriveManager(threading.Thread):
	def __init__(self, enablingPluggedEvent):
		super(ExternalDriveManager, self).__init__()
		self.daemon = True
		self.stopThread = False
		self.enablingPluggedEvent = enablingPluggedEvent

		if enablingPluggedEvent:
			self.context = pyudev.Context()
			self.monitor = pyudev.Monitor.from_netlink(self.context)
			self.monitor.filter_by(subsystem='usb')

		self._logger = logging.getLogger(__name__)

	def run(self):
		if self.enablingPluggedEvent:
			for device in iter(self.monitor.poll, None):
				if self.stopThread:
					self.monitor.stop()
					return

				if device.device_type == 'usb_device':
					if device.action == 'add':
						self._logger.info('{} connected'.format(device))
						FilesSystemReadyWorker(device,'PLUG IN').start()

					if device.action == 'remove':
						self._logger.info('{} disconnected'.format(device))
						FilesSystemReadyWorker(device,'REMOVED').start()


	def shutdown(self):
		self._logger.info('Shutting Down ExternalDriveManager')

		if self.enablingPluggedEvent:
			self.stopThread = True

		global _instance
		_instance = None


	def _cleanFileLocation(self, location):
		locationParsed = location.replace('//','/')
		return locationParsed


	def eject(self, drive):
		args = ['eject', settings().getBaseFolder('storageLocation').replace('//','/') + drive]

		try:
			ejectProccess = subprocess.Popen(
				args,
				stdout=subprocess.PIPE
			)

			FilesSystemReadyWorker(drive,'EJECTION').start()

			return {'result': True}

		except Exception, error:

			self._logger.error('Error ejecting drive %s: %s' %  (drive,str(error)))

			return {
				'result': False,
				'error': str(error)
			}

	def copy(self, src, dst, progressCb, observerId):

			blksize = 1048576 # 1MiB
			try:
					s = open(src, 'rb')
					d = open(dst, 'wb')
			except (KeyboardInterrupt, Exception) as e:
					if 's' in locals():
							s.close()
					if 'd' in locals():
							d.close()
					raise
			try:
					total = float(os.stat(src).st_size)

					while True:
							buf = s.read(blksize)
							bytes_written = d.write(buf)
{'fraction_non_alphanumeric': 0.11936147055266659, 'fraction_numerical': 0.004111742653283347, 'mean_word_length': 3.937313432835821, 'pattern_counts': {'":': 10, '<': 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': '1055995', 'n_tokens_mistral': 3164, 'n_tokens_neox': 2567, 'n_words': 587}