module Eco::API::UseCases::GraphQL::Utils module Sftp include Eco::API::UseCases::GraphQL::Helpers::Base::CaseEnv def remote_subfolder nil end def remote_folder(subfolder = remote_subfolder) "#{sftp_config.remote_folder}/#{subfolder || ''}" end def sftp_group_id if self.class.const_defined?(:SFTP_GROUP) self.class.const_get(:TARGET_STRUCTURE_ID) elsif group_id = options.dig(:sftp, :group) group_id end end def upload(local_file, remote_folder: self.remote_folder, gid: sftp_group_id) return false unless local_file && File.exist?(local_file) dest_file = "#{remote_folder}/#{File.basename(local_file)}" res = sftp_session.upload!(local_file, dest_file) attrs = sftp_session.stat!(dest_file) if gid && gid != attrs.gid stat_res = sftp_session.setstat!(dest_file, {permissions: 0660, uid: attrs.uid, gid: gid}) end logger.info("Uploaded '#{local_file}' (#{res})") end def ensure_remote_empty files = with_remote_files unless files.empty? msg = "There are still files in the remote folder that will be deleted: '#{remote_folder}':\n" msg += " • " + files.map do |file| file.longname end.join("\n • ") + "\n" session.prompt_user("Do you want to proceed to delete? (Y/n):", explanation: msg, default: "Y", timeout: 3) do |response| if response.upcase.start_with?("Y") files.each do |file| remote_full_path = to_remote_path(file.name) res = sftp_session.remove(remote_full_path) logger.info("Deleted remote file: '#{remote_full_path}' (#{res})") end end end end end def with_remote_files sftp.files(remote_folder).each do |remote_file| yield(remote_file) if block_given? end end def to_remote_path(file, subfolder: nil) remote_folder(subfolder) + "/" + file end def sftp_config session.config.sftp end def sftp_session sftp.sftp_session end def sftp session.sftp end end end