#!/usr/bin/env ruby # coding: utf-8 # External gems を使わずに動くテストスクリプト。 # move_old_files.rb から定数を読み取って、PROPFIND(Depth:0)で存在確認する。 require 'net/http' require 'uri' SRC = File.expand_path('move_old_files.rb', __dir__) contents = File.read(SRC) def extract_const(contents, name) if contents =~ /^\s*#{name}\s*=\s*(['"])(.*?)\1/mi $2 else nil end end BASE_URL = extract_const(contents, 'BASE_URL') || abort('BASE_URL not found') NC_USER = extract_const(contents, 'NC_USER') || abort('NC_USER not found') NC_PASS = extract_const(contents, 'NC_PASS') || abort('NC_PASS not found') TARGET_DIR = extract_const(contents, 'TARGET_DIR')|| abort('TARGET_DIR not found') BAK_DIR = extract_const(contents, 'BAK_DIR') || abort('BAK_DIR not found') # Net::HTTP::Propfind が未定義なら簡単に定義する unless defined?(Net::HTTP::Propfind) class Net::HTTP::Propfind < Net::HTTPRequest METHOD = 'PROPFIND' REQUEST_HAS_BODY = true RESPONSE_HAS_BODY = true end end # 実際に PROPFIND を投げる def exists_on_webdav?(path) uri = URI.parse(BASE_URL.chomp('/') + "/remote.php/dav/files/#{NC_USER}" + path) req = Net::HTTP::Propfind.new(uri.request_uri) req['Depth'] = '0' req['Content-Type'] = 'text/xml' req.body = "<?xml version=\"1.0\" encoding=\"utf-8\"?><d:propfind xmlns:d=\"DAV:\"><d:prop><d:resourcetype/></d:prop></d:propfind>" req.basic_auth(NC_USER, NC_PASS) res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(req) end [200,207].include?(res.code.to_i) rescue => e warn "Error checking #{path}: #{e.class}: #{e.message}" false end puts "Checking TARGET_DIR: #{TARGET_DIR}" puts exists_on_webdav?(TARGET_DIR) ? "FOUND" : "NOT FOUND" puts "Checking BAK_DIR: #{BAK_DIR}" puts exists_on_webdav?(BAK_DIR) ? "FOUND" : "NOT FOUND"