trabajo-afectivo/lib/sessions.rb

540 lines
10 KiB
Ruby
Raw Normal View History

2012-07-23 22:22:23 +00:00
require 'json'
2013-05-05 22:54:06 +00:00
require 'session_helper'
2012-07-23 22:22:23 +00:00
module Sessions
2013-01-24 01:01:47 +00:00
# get application root directory
@root = Dir.pwd.to_s
2013-02-01 00:01:20 +00:00
if !@root || @root.empty? || @root == '/'
2013-01-24 01:01:47 +00:00
@root = Rails.root
end
# get working directories
@path = @root + '/tmp/websocket'
@pid = @root + '/tmp/pids/sessionworker.pid'
# create global vars for threads
2012-08-03 22:46:05 +00:00
@@client_threads = {}
2012-07-23 22:22:23 +00:00
2014-06-27 06:43:37 +00:00
=begin
start new session
Sessions.create( client_id, session_data, { :type => 'websocket' } )
returns
true|false
=end
2012-11-26 05:04:44 +00:00
def self.create( client_id, session, meta )
2012-07-23 22:22:23 +00:00
path = @path + '/' + client_id.to_s
FileUtils.mkpath path
2012-11-26 05:04:44 +00:00
meta[:last_ping] = Time.new.to_i.to_s
2013-04-08 18:56:59 +00:00
File.open( path + '/session', 'wb' ) { |file|
2012-11-26 05:04:44 +00:00
data = {
:user => {
:id => session['id'],
},
:meta => meta,
}
2013-04-08 18:56:59 +00:00
file.write Marshal.dump(data)
2012-07-23 22:22:23 +00:00
}
2012-11-02 16:10:22 +00:00
# send update to browser
if session['id']
2012-11-26 05:04:44 +00:00
self.send( client_id, {
2012-11-02 16:10:22 +00:00
:event => 'ws:login',
:data => { :success => true },
})
end
2012-07-23 22:22:23 +00:00
end
2014-06-27 06:43:37 +00:00
=begin
list of all session
client_ids = Sessions.sessions
returns
['4711', '4712']
=end
def self.sessions
path = @path + '/'
# just make sure that spool path exists
if !File::exists?( path )
FileUtils.mkpath path
end
data = []
Dir.foreach( path ) do |entry|
next if entry == '.' || entry == '..' || entry == 'spool'
data.push entry.to_s
end
data
end
=begin
list of all session
Sessions.session_exists?(client_id)
returns
true|false
=end
def self.session_exists?(client_id)
client_ids = self.sessions
client_ids.include? client_id.to_s
end
=begin
list of all session with data
client_ids_with_data = Sessions.list
returns
{
'4711' => {
:user => {
:id => 123,
},
:meta => {
:type => 'websocket',
:last_ping => time_of_last_ping,
}
},
'4712' => {
:user => {
:id => 124,
},
:meta => {
:type => 'ajax',
:last_ping => time_of_last_ping,
}
},
}
=end
def self.list
client_ids = self.sessions
session_list = {}
client_ids.each { |client_id|
data = self.get(client_id)
next if !data
session_list[client_id] = data
}
session_list
end
=begin
destroy session
Sessions.destory?(client_id)
returns
true|false
=end
def self.destory( client_id )
path = @path + '/' + client_id.to_s
FileUtils.rm_rf path
end
=begin
destroy idle session
list_of_client_ids = Sessions.destory_idle_sessions
returns
['4711', '4712']
=end
def self.destory_idle_sessions(idle_time_in_min = 4)
list_of_closed_sessions = []
clients = Sessions.list
clients.each { |client_id, client|
if ( client[:meta][:last_ping].to_i + ( 60 * idle_time_in_min ) ) < Time.now.to_i
list_of_closed_sessions.push client_id
Sessions.destory( client_id )
end
}
list_of_closed_sessions
end
=begin
touch session
Sessions.touch(client_id)
returns
true|false
=end
def self.touch( client_id )
data = self.get(client_id)
return false if !data
path = @path + '/' + client_id.to_s
data[:meta][:last_ping] = Time.new.to_i.to_s
File.open( path + '/session', 'wb' ) { |file|
file.write Marshal.dump(data)
}
true
end
=begin
get session data
data = Sessions.get(client_id)
returns
{
:user => {
:id => 123,
},
:meta => {
:type => 'websocket',
:last_ping => time_of_last_ping,
}
}
=end
def self.get( client_id )
session_file = @path + '/' + client_id.to_s + '/session'
data = nil
return if !File.exist? session_file
begin
File.open( session_file, 'rb' ) { |file|
file.flock( File::LOCK_EX )
all = file.read
file.flock( File::LOCK_UN )
data = Marshal.load( all )
}
rescue Exception => e
File.delete(session_file)
puts "Error reading '#{session_file}':"
puts e.inspect
return
end
data
end
=begin
send message to client
Sessions.send(client_id_of_recipient, data)
returns
true|false
=end
def self.send( client_id, data )
path = @path + '/' + client_id.to_s + '/'
filename = 'send-' + Time.new().to_f.to_s# + '-' + rand(99999999).to_s
check = true
count = 0
while check
if File::exists?( path + filename )
count += 1
filename = filename + '-' + count
else
check = false
end
end
return false if !File.directory? path
File.open( path + 'a-' + filename, 'wb' ) { |file|
file.flock( File::LOCK_EX )
file.write data.to_json
file.flock( File::LOCK_UN )
file.close
}
return false if !File.exists?( path + 'a-' + filename )
FileUtils.mv( path + 'a-' + filename, path + filename )
true
end
=begin
send message to all client
Sessions.broadcast(data)
returns
true|false
=end
def self.broadcast( data )
# list all current clients
client_list = self.sessions
client_list.each {|client_id|
Sessions.send( client_id, data )
}
true
end
=begin
get messages for client
messages = Sessions.queue(client_id_of_recipient)
returns
[
{
key1 => 'some data of message 1',
key2 => 'some data of message 1',
},
{
key1 => 'some data of message 2',
key2 => 'some data of message 2',
},
]
=end
def self.queue( client_id )
path = @path + '/' + client_id.to_s + '/'
data = []
files = []
Dir.foreach( path ) {|entry|
next if entry == '.' || entry == '..'
files.push entry
}
files.sort.each {|entry|
filename = path + '/' + entry
if /^send/.match( entry )
data.push Sessions.queue_file_read( path, entry )
end
}
data
end
def self.queue_file_read( path, filename )
file_old = path + filename
file_new = path + 'a-' + filename
FileUtils.mv( file_old, file_new )
data = nil
all = ''
File.open( file_new, 'rb' ) { |file|
all = file.read
}
File.delete( file_new )
JSON.parse( all )
end
2014-06-29 19:30:55 +00:00
def self.spool_cleanup
path = @path + '/spool/'
FileUtils.rm_rf path
end
def self.spool_create( msg )
path = @path + '/spool/'
FileUtils.mkpath path
file = Time.new.to_f.to_s + '-' + rand(99999).to_s
File.open( path + '/' + file , 'wb' ) { |file|
data = {
:msg => msg,
:timestamp => Time.now.to_i,
}
file.write data.to_json
}
end
def self.spool_list( timestamp, current_user_id )
path = @path + '/spool/'
FileUtils.mkpath path
data = []
to_delete = []
files = []
Dir.foreach( path ) {|entry|
next if entry == '.' || entry == '..'
files.push entry
}
files.sort.each {|entry|
filename = path + '/' + entry
next if !File::exists?( filename )
File.open( filename, 'rb' ) { |file|
all = file.read
spool = JSON.parse( all )
begin
message_parsed = JSON.parse( spool['msg'] )
rescue => e
log 'error', "can't parse spool message: #{ message }, #{ e.inspect }"
next
end
# ignore message older then 48h
if spool['timestamp'] + (2 * 86400) < Time.now.to_i
to_delete.push path + '/' + entry
next
end
# add spool attribute to push spool info to clients
2013-06-28 22:26:04 +00:00
message_parsed['spool'] = true
# only send not already now messages
if !timestamp || timestamp < spool['timestamp']
# spool to recipient list
2013-06-28 22:26:04 +00:00
if message_parsed['recipient'] && message_parsed['recipient']['user_id']
message_parsed['recipient']['user_id'].each { |user_id|
if current_user_id == user_id
item = {
:type => 'direct',
:message => message_parsed,
}
data.push item
end
}
# spool to every client
else
item = {
:type => 'broadcast',
:message => message_parsed,
}
data.push item
end
end
}
}
to_delete.each {|file|
File.delete(file)
}
return data
end
2012-07-23 22:22:23 +00:00
def self.jobs
# just make sure that spool path exists
2013-01-15 23:10:27 +00:00
if !File::exists?( @path )
FileUtils.mkpath @path
end
2012-08-03 22:46:05 +00:00
Thread.abort_on_exception = true
2012-07-23 22:22:23 +00:00
while true
client_ids = self.sessions
client_ids.each { |client_id|
2014-06-29 19:30:55 +00:00
# connection already open, ignore
2012-08-07 21:53:43 +00:00
next if @@client_threads[client_id]
# get current user
session_data = Sessions.get( client_id )
2012-11-26 05:04:44 +00:00
next if !session_data
next if !session_data[:user]
next if !session_data[:user][:id]
user = User.find( session_data[:user][:id] )
2012-08-03 22:46:05 +00:00
next if !user
# start client thread
if !@@client_threads[client_id]
2013-12-01 11:55:21 +00:00
@@client_threads[client_id] = true
2012-08-03 22:46:05 +00:00
@@client_threads[client_id] = Thread.new {
2014-04-24 16:43:24 +00:00
thread_client(client_id)
2012-08-03 22:46:05 +00:00
@@client_threads[client_id] = nil
2013-12-01 11:55:21 +00:00
puts "close client (#{client_id}) thread"
2012-08-03 22:46:05 +00:00
}
2014-07-13 23:29:29 +00:00
sleep 0.5
end
2012-07-23 22:22:23 +00:00
}
2012-08-07 06:43:15 +00:00
# system settings
2012-11-26 23:22:52 +00:00
sleep 0.5
2012-07-23 22:22:23 +00:00
end
end
2014-06-29 19:30:55 +00:00
=begin
check if thread for client_id is running
Sessions.thread_client_exists?(client_id)
returns
thread
=end
def self.thread_client_exists?(client_id)
@@client_threads[client_id]
2013-12-01 11:55:21 +00:00
end
2014-06-29 19:30:55 +00:00
=begin
start client for browser
Sessions.thread_client(client_id)
returns
thread
=end
2014-04-24 16:43:24 +00:00
def self.thread_client(client_id, try_count = 0, try_run_time = Time.now)
2014-06-29 19:30:55 +00:00
puts "LOOP #{client_id} - #{try_count}"
begin
Sessions::Client.new(client_id)
rescue => e
2014-07-13 23:29:29 +00:00
puts "thread_client #{client_id} exited with error #{ e.inspect }"
2014-07-13 18:52:32 +00:00
puts e.backtrace.join("\n ")
2014-06-29 19:30:55 +00:00
sleep 10
2013-12-01 11:55:21 +00:00
begin
2014-06-29 19:30:55 +00:00
# ActiveRecord::Base.remove_connection
# ActiveRecord::Base.connection_pool.reap
ActiveRecord::Base.connection_pool.release_connection
2013-12-01 11:55:21 +00:00
rescue => e
2014-06-29 19:30:55 +00:00
puts "Can't reconnect to database #{ e.inspect }"
end
2014-04-24 05:49:30 +00:00
2014-06-29 19:30:55 +00:00
try_run_max = 10
try_count += 1
2014-04-24 05:49:30 +00:00
2014-06-29 19:30:55 +00:00
# reset error counter if to old
if try_run_time + ( 60 * 5 ) < Time.now
try_count = 0
end
try_run_time = Time.now
2014-04-24 05:49:30 +00:00
2014-06-29 19:30:55 +00:00
# restart job again
if try_run_max > try_count
thread_client(client_id, try_count, try_run_time)
else
raise "STOP thread_client for client #{client_id} after #{try_run_max} tries"
2013-12-01 11:55:21 +00:00
end
2014-06-29 19:30:55 +00:00
end
puts "/LOOP #{client_id} - #{try_count}"
2013-12-01 11:55:21 +00:00
end
end