Method: MPW::MPW#sync

Defined in:
lib/mpw/mpw.rb

#sync(force = false) ⇒ Object

Sync data with remote file @args: force -> force the sync



332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
# File 'lib/mpw/mpw.rb', line 332

def sync(force=false)
	return if @config.empty? or @config['sync']['type'].to_s.empty?
	return if get_last_sync + 300 > Time.now.to_i and not force

	tmp_file  = "#{@wallet_file}.sync"
	
	case @config['sync']['type']
	when 'sftp', 'scp', 'ssh'
		require "mpw/sync/ssh"
		sync = SyncSSH.new(@config['sync'])
	when 'ftp'
		require 'mpw/sync/ftp'
		sync = SyncFTP.new(@config['sync'])
	else
		raise I18n.t('error.sync.unknown_type')
	end

	sync.connect
	sync.get(tmp_file)

	remote = MPW.new(@key, tmp_file, @gpg_pass, @gpg_exe)
	remote.read_data

	File.unlink(tmp_file) if File.exist?(tmp_file)

	return if remote.get_last_sync == @config['last_update']

	if not remote.to_s.empty?
		@data.each do |item|
			update = false

			remote.list.each do |r|
				next if item.id != r.id

				# Update item
				if item.last_edit < r.last_edit
					item.update(name:      r.name,
					            group:     r.group,
					            host:      r.host,
					            protocol:  r.protocol,
					            user:      r.user,
					            port:      r.port,
					            comment:   r.comment
					           )
					set_password(item.id, remote.get_password(item.id))
				end

				r.delete
				update = true

				break
			end

			# Remove an old item
			if not update and item.last_sync.to_i < get_last_sync and item.last_edit < get_last_sync
				item.delete
			end
		end
	end

	# Add item
	remote.list.each do |r|
		next if r.last_edit <= get_last_sync

		item = Item.new(id:        r.id,
		                name:      r.name,
		                group:     r.group,
		                host:      r.host,
		                protocol:  r.protocol,
		                user:      r.user,
		                port:      r.port,
		                comment:   r.comment,
		                created:   r.created,
		                last_edit: r.last_edit
		               )

		set_password(item.id, remote.get_password(item.id))
		add(item)
	end

	remote = nil

	@data.each do |item|
		item.set_last_sync
	end

	@config['sync']['last_sync'] = Time.now.to_i

	write_data
	sync.update(@wallet_file)
rescue Exception => e
	File.unlink(tmp_file) if File.exist?(tmp_file)

	raise "#{I18n.t('error.sync.general')}\n#{e}"
end