You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

import.rb 7.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. # frozen_string_literal: true
  2. # Redmine - project management software
  3. # Copyright (C) 2006-2022 Jean-Philippe Lang
  4. #
  5. # This program is free software; you can redistribute it and/or
  6. # modify it under the terms of the GNU General Public License
  7. # as published by the Free Software Foundation; either version 2
  8. # of the License, or (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. require 'csv'
  19. class Import < ActiveRecord::Base
  20. has_many :items, :class_name => 'ImportItem', :dependent => :delete_all
  21. belongs_to :user
  22. serialize :settings
  23. before_destroy :remove_file
  24. validates_presence_of :filename, :user_id
  25. validates_length_of :filename, :maximum => 255
  26. DATE_FORMATS = [
  27. '%Y-%m-%d',
  28. '%d/%m/%Y',
  29. '%m/%d/%Y',
  30. '%Y/%m/%d',
  31. '%d.%m.%Y',
  32. '%d-%m-%Y'
  33. ]
  34. AUTO_MAPPABLE_FIELDS = {}
  35. def self.menu_item
  36. nil
  37. end
  38. def self.layout
  39. 'base'
  40. end
  41. def self.authorized?(user)
  42. user.admin?
  43. end
  44. def initialize(*args)
  45. super
  46. self.settings ||= {}
  47. end
  48. def file=(arg)
  49. return unless arg.present? && arg.size > 0
  50. self.filename = generate_filename
  51. Redmine::Utils.save_upload(arg, filepath)
  52. end
  53. def set_default_settings(options={})
  54. separator = lu(user, :general_csv_separator)
  55. encoding = lu(user, :general_csv_encoding)
  56. if file_exists?
  57. begin
  58. content = File.read(filepath, 256)
  59. separator = [',', ';'].max_by {|sep| content.count(sep)}
  60. guessed_encoding = Redmine::CodesetUtil.guess_encoding(content)
  61. encoding =
  62. (guessed_encoding && (
  63. Setting::ENCODINGS.detect {|e| e.casecmp?(guessed_encoding)} ||
  64. Setting::ENCODINGS.detect {|e| Encoding.find(e) == Encoding.find(guessed_encoding)}
  65. )) || lu(user, :general_csv_encoding)
  66. rescue => e
  67. end
  68. end
  69. wrapper = '"'
  70. date_format = lu(user, "date.formats.default", :default => "foo")
  71. date_format = DATE_FORMATS.first unless DATE_FORMATS.include?(date_format)
  72. self.settings.merge!(
  73. 'separator' => separator,
  74. 'wrapper' => wrapper,
  75. 'encoding' => encoding,
  76. 'date_format' => date_format,
  77. 'notifications' => '0'
  78. )
  79. if options.key?(:project_id) && !options[:project_id].blank?
  80. # Do not fail if project doesn't exist
  81. begin
  82. project = Project.find(options[:project_id])
  83. self.settings.merge!('mapping' => {'project_id' => project.id})
  84. rescue; end
  85. end
  86. end
  87. def to_param
  88. filename
  89. end
  90. # Returns the full path of the file to import
  91. # It is stored in tmp/imports with a random hex as filename
  92. def filepath
  93. if filename.present? && /\A[0-9a-f]+\z/.match?(filename)
  94. File.join(Rails.root, "tmp", "imports", filename)
  95. else
  96. nil
  97. end
  98. end
  99. # Returns true if the file to import exists
  100. def file_exists?
  101. filepath.present? && File.exist?(filepath)
  102. end
  103. # Returns the headers as an array that
  104. # can be used for select options
  105. def columns_options(default=nil)
  106. i = -1
  107. headers.map {|h| [h, i+=1]}
  108. end
  109. # Parses the file to import and updates the total number of items
  110. def parse_file
  111. count = 0
  112. read_items {|row, i| count=i}
  113. update_attribute :total_items, count
  114. count
  115. end
  116. # Reads the items to import and yields the given block for each item
  117. def read_items
  118. i = 0
  119. headers = true
  120. read_rows do |row|
  121. if i == 0 && headers
  122. headers = false
  123. next
  124. end
  125. i+= 1
  126. yield row, i if block_given?
  127. end
  128. end
  129. # Returns the count first rows of the file (including headers)
  130. def first_rows(count=4)
  131. rows = []
  132. read_rows do |row|
  133. rows << row
  134. break if rows.size >= count
  135. end
  136. rows
  137. end
  138. # Returns an array of headers
  139. def headers
  140. first_rows(1).first || []
  141. end
  142. # Returns the mapping options
  143. def mapping
  144. settings['mapping'] || {}
  145. end
  146. # Adds a callback that will be called after the item at given position is imported
  147. def add_callback(position, name, *args)
  148. settings['callbacks'] ||= {}
  149. settings['callbacks'][position] ||= []
  150. settings['callbacks'][position] << [name, args]
  151. save!
  152. end
  153. # Executes the callbacks for the given object
  154. def do_callbacks(position, object)
  155. if callbacks = (settings['callbacks'] || {}).delete(position)
  156. callbacks.each do |name, args|
  157. send "#{name}_callback", object, *args
  158. end
  159. save!
  160. end
  161. end
  162. # Imports items and returns the position of the last processed item
  163. def run(options={})
  164. max_items = options[:max_items]
  165. max_time = options[:max_time]
  166. current = 0
  167. imported = 0
  168. resume_after = items.maximum(:position) || 0
  169. interrupted = false
  170. started_on = Time.now
  171. read_items do |row, position|
  172. if (max_items && imported >= max_items) || (max_time && Time.now >= started_on + max_time)
  173. interrupted = true
  174. break
  175. end
  176. if position > resume_after
  177. item = items.build
  178. item.position = position
  179. item.unique_id = row_value(row, 'unique_id') if use_unique_id?
  180. if object = build_object(row, item)
  181. if object.save
  182. item.obj_id = object.id
  183. else
  184. item.message = object.errors.full_messages.join("\n")
  185. end
  186. end
  187. item.save!
  188. imported += 1
  189. extend_object(row, item, object) if object.persisted?
  190. do_callbacks(use_unique_id? ? item.unique_id : item.position, object)
  191. end
  192. current = position
  193. end
  194. if imported == 0 || interrupted == false
  195. if total_items.nil?
  196. update_attribute :total_items, current
  197. end
  198. update_attribute :finished, true
  199. remove_file
  200. end
  201. current
  202. end
  203. def unsaved_items
  204. items.where(:obj_id => nil)
  205. end
  206. def saved_items
  207. items.where("obj_id IS NOT NULL")
  208. end
  209. private
  210. def read_rows
  211. return unless file_exists?
  212. csv_options = {:headers => false}
  213. csv_options[:encoding] = settings['encoding'].to_s.presence || 'UTF-8'
  214. csv_options[:encoding] = 'bom|UTF-8' if csv_options[:encoding] == 'UTF-8'
  215. separator = settings['separator'].to_s
  216. csv_options[:col_sep] = separator if separator.size == 1
  217. wrapper = settings['wrapper'].to_s
  218. csv_options[:quote_char] = wrapper if wrapper.size == 1
  219. CSV.foreach(filepath, **csv_options) do |row|
  220. yield row if block_given?
  221. end
  222. end
  223. def row_value(row, key)
  224. if index = mapping[key].presence
  225. row[index.to_i].presence
  226. end
  227. end
  228. def row_date(row, key)
  229. if s = row_value(row, key)
  230. format = settings['date_format']
  231. format = DATE_FORMATS.first unless DATE_FORMATS.include?(format)
  232. Date.strptime(s, format) rescue s
  233. end
  234. end
  235. # Builds a record for the given row and returns it
  236. # To be implemented by subclasses
  237. def build_object(row, item)
  238. end
  239. # Extends object with properties, that may only be handled after it's been
  240. # persisted.
  241. def extend_object(row, item, object)
  242. end
  243. # Generates a filename used to store the import file
  244. def generate_filename
  245. Redmine::Utils.random_hex(16)
  246. end
  247. # Deletes the import file
  248. def remove_file
  249. if file_exists?
  250. begin
  251. File.delete filepath
  252. rescue => e
  253. logger.error "Unable to delete file #{filepath}: #{e.message}" if logger
  254. end
  255. end
  256. end
  257. # Returns true if value is a string that represents a true value
  258. def yes?(value)
  259. value == lu(user, :general_text_yes) || value == '1'
  260. end
  261. def use_unique_id?
  262. mapping['unique_id'].present?
  263. end
  264. end