6 class UsersController < ApplicationController
7 # before_filter :set_current_user
10 except_funcs = [:home, :processcallback, :fakejawaker, :facebookapp, :stat, :auth, :api, :statistic_to_csv,:sign_out]
11 #before_filter :check_auth, :only => [:stat]
12 before_filter :source_statistic, :except => except_funcs
13 before_filter :create_facebook_session, :except => except_funcs
14 before_filter :set_facebook_session, :except => except_funcs
15 before_filter :checking_jawaker_session, :except => except_funcs
16 before_filter :facebook_logout, :except => except_funcs
17 before_filter :check_facebook_session, :except => except_funcs
21 if (cookies[:auth] != "ok")
22 debug_message ("Admin not log in",false)
23 redirect_to "http://jawaker.com/fb/auth"
25 debug_message ("Admin log in, OK")
30 debug_message ("Authification:")
32 if (params[:login] == FBlogin) and (params[:password] == FBpassword)
34 flash[:notice] = 'Successfully logged in'
35 respond_to do |format|
36 format.html { redirect_to("http://jawaker.com/fb/stat") }
39 flash[:notice] = 'Incorrect login and/or password'
46 cookies[:auth] = "false"
47 respond_to do |format|
48 format.html { render :action => "auth" }
52 #protect_from_forgery :except => processcallback
54 #add statistic by source
55 if (params[:from]) && (params[:from].to_i != 0)
56 add_stat(0, VISITED, params[:from] ? params[:from].to_i : 0)
59 if !params[:facebook_id].blank? && params[:api_action].blank?
60 redirect_to "http://www.jawaker.com/users/new?facebook_id=" + params[:facebook_id]
64 def check_facebook_session
65 if session[:facebook_session].blank?
66 if params[:locale].blank?
67 redirect_to Current_site
69 redirect_to Current_site + "?locale=" + params[:locale].to_s
75 @facebook_locale = session[:facebook_session].user.locale
77 @facebook_locale = nil
79 #getting and setting language info
80 if params[:locale] && params[:locale] != ""
81 I18n.locale = params[:locale]
83 unless params[:logout].blank?
84 session[:facebook_session] = nil
85 facebook_session = nil
86 cookies[:_connect_tutorial_session] = nil
87 if params[:locale].blank?
88 redirect_to Current_site
91 redirect_to Current_site + "?locale=" + params[:locale].to_s
99 #public feed after invited user
100 if params[:api_action] == "publish_about_invited"
101 @operation_result = "SUCCESS"
102 #preparing to publish
103 add_stat(params[:facebook_id], REWARDED)
104 session_new = Facebooker::Session.create
105 @userFB = Facebooker::User.new(params[:facebook_id], session_new)
107 @userFB.publish_to(@userFB,
108 :message => "has recieved " + params[:tokens] + " tokens for inviting his friend with nickname " + params[:nickname] + " in Jawaker",
110 :text => 'See my results',
111 :href => "http://apps.facebook.com/jawaker"},
113 :text => 'Try to beat him',
114 :href => "http://www.jawaker.com/fb/?from=#{FROM_FEED}"}
117 :name => "The rank of this user is increasing",
118 :href => "http://www.jawaker.com/fb/?from=#{FROM_FEED}",
119 :caption => 'Jawaker is a multiplayer card game website for the Arab world. Register now and start playing one of our online card games for FREE!',
120 :description => 'Start your first game right now',
124 :src => "http://jawaker.com/images/hp_mascot_ar-trans.png",
125 :href => "http://www.jawaker.com/fb/?from=#{FROM_FEED}"}
129 rescue Facebooker::Session::SpecialUserAuthorizationRequired
130 @operation_result = "SPECIAL_USER_AUTHORIZATION_REQUIRED"
133 @operation_result = "UNKNOWN_ERROR"
136 render :layout => false
141 def checking_jawaker_session
142 unless RAILS_ENV == "development"
143 @temp_cookies = false
144 #if jsession_id was sent - set cookies
145 if !params[:jsession_id].blank?
146 cookies[:_session_id] = params[:jsession_id]
148 cookies[:www_redirect] = true
150 #redirect with cookies
151 if request.env["HTTP_HOST"].include?("www")
152 redirect_to "http://jawaker.com/fb/?jsession_id=" + cookies[:_session_id].to_s
155 @answer_result = false
156 debug_message("Session id cookie: #{cookies[:_session_id]}, temp_cookies: #{@temp_cookies}")
157 if (cookies[:_session_id] && !(cookies[:_session_id].blank?)) # @temp_cookies
159 #checking if user still online in Jawaker
160 res = Net::HTTP.post_form(URI.parse(Jawaker_link),{'token' => 'R45ASL5V','token' => 'R45ASL5V','api_action'=>'check_session','session_id' => cookies[:_session_id]})
161 @answer_result = res.body
162 debug_message("Information about state of Jawaker logging was got: " + @answer_result.to_s)
163 if (!@answer_result.include?("true")) && (!@answer_result.include?("false"))
164 debug_message("Jawaker API does not work properly",false)
168 if @answer_result.include?("false")
169 @answer_result = false
171 @answer_result = true
175 debug_message("Cannot connect Jawaker",false)
179 if (@temp_cookies == false) && ((cookies[:_session_id].blank?) || (@answer_result == false))
180 if cookies[:_session_id].blank?
181 debug_message("cookies[:_session_id].blank",false)
183 if @answer_result == false
184 debug_message("User not loging in",false)
187 redirect_to "http://jawaker.com/login"
192 #end of unless RAILS_ENV == "development"
197 unless session[:facebook_session].blank?
200 if session[:facebook_session].user.has_permission?('publish_stream')
201 @myway = "invitefriend"
203 @myway = "permission"
205 debug_message("User already loggined so he redirected to permission/invitation page")
206 if params[:locale].blank?
207 redirect_to Current_site + @myway
209 redirect_to Current_site + @myway + "?locale=" + params[:locale].to_s
213 debug_message("Cannot get status of user permission... I continue this home page",false)
215 #end of unless session[:facebook_session].blank?
224 if session[:facebook_session].user.has_permission?('publish_stream')
225 if params[:locale].blank?
226 params[:locale] = nil
228 debug_message("User already has permission so he redirected to invitation page")
229 redirect_to Current_site + "invitefriend" + "?locale=" + params[:locale].to_s
233 debug_message("Cannot get status of user permission... Redirect to home page and logout",false)
234 redirect_to Current_site + "?logout=yes" + "?locale=" + params[:locale].to_s
238 @someUser = session[:facebook_session].user
240 @fbfriend = Fbfriend.find(:first, :conditions => ["facebook_id = '?'", @someUser.uid])
242 #preparing list of friends for Jawaker
244 #rescue stage for no frieds
246 for friend in @someUser.friends
247 my_friends.push(friend.uid)
249 #sending registration info to Jawaker
251 res = Net::HTTP.post_form(URI.parse(Jawaker_link),{'token' => 'R45ASL5V','token' => 'R45ASL5V','api_action'=>'registration', 'facebook_id'=>@someUser.uid, 'friend_list' => my_friends.join(','),'session_id' => cookies[:_session_id] })
252 debug_message("FB.id and List of friends after registration for user were sent")
254 debug_message("Problem with Jawaker connection",false)
255 raise Connection_problem_with_jawaker
258 :facebook_id => @someUser.uid,
259 :friends_list => my_friends.join(',')
261 @fbfriend = Fbfriend.new(myParams)
264 add_stat(@someUser.uid,CONNECTED)
265 debug_message("Information was added in MW local DB")
267 debug_message("Cannot get friend list, user was logout and redirect",false)
268 redirect_to "http://jawaker.com/fb?logout=yes"
271 #p "FAKE sending private info of user: [:political, :pic_small, :name, :quotes, :tv, :meeting_sex, :hs_info, :timezone, :relationship_status, :hometown_location, :about_me, :music, :work_history, :sex, :religion, :activities, :movies, :education_history, :birthday, :first_name, :meeting_for, :last_name, :interests, :current_location, :pic, :books, :affiliations, :locale]"
278 #permission adding to Jawaker
279 if params[:permission] == "publish_stream"
280 add_stat(session[:facebook_session].user.uid,PERMISSION)
282 res = Net::HTTP.post_form(URI.parse(Jawaker_link), {'token' => 'R45ASL5V','api_action' => 'permission_set', 'permission' => 'publish_stream', 'facebook_id' => session[:facebook_session].user.uid})
283 debug_message("Updating about permision was sent")
285 debug_message("Cannot connect to Jawaker or some problems with getting info from FB",false)
289 #public "registration" message on feed
290 if (params[:permission] == "publish_stream")
292 #preparing for public first feed
293 session_new = Facebooker::Session.create
294 @userFB = Facebooker::User.new(session[:facebook_session].user.uid, session_new)
295 #publishing first message
296 @userFB.publish_to(@userFB,
297 :message => "has connected his Facebook and Jawaker accounts",
300 :text => 'Visit Jawaker إذهب إلى جواكر',
301 :href => "http://www.jawaker.com/fb/?from=#{FROM_FEED}"}
304 :name => "لنلعب الورق على جواكر. إذهب إلى جواكر والعب الآن",
305 :href => "http://www.jawaker.com/fb/?from=#{FROM_FEED}",
306 :caption => "Let's play cards together on Jawaker. Visit Jawaker now and start playing.",
311 :src => "http://jawaker.com/fb/logo_of_jawaker.png",
312 :href => "http://jawaker.com/fb/?from=#{FROM_FEED}"
316 debug_message("First message was published into stream")
318 debug_message("Cannot publish to Jawaker or some problems with getting info from FB",false)
320 #logged_in? & permission
323 #getting friend list who is already registered
327 for friend in session[:facebook_session].user.friends
328 my_friends.push(friend.uid)
330 #sending list of friends and getting list who are already connected to exclude invitation
331 res = Net::HTTP.post_form(URI.parse(Jawaker_link),{'token' => 'R45ASL5V', 'api_action'=>'connected_friends','facebook_id' => session[:facebook_session].user.uid,'friend_list' => my_friends.join(',') })
332 @answer_result = res.body.split(',')
333 debug_message("Information about already registered friends was gotten")
335 debug_message ("List of friends :" + @answer_result.join(' '))
338 debug_message("Cannot get facebook friend list from FB or cannot connect Jawaker",false)
343 #public feed after request from Jawaker
344 def publish_game_result
345 @operation_result = "SUCCESS"
346 #preparing to publish
347 session_new = Facebooker::Session.create
348 @userFB = Facebooker::User.new(params[:facebook_id], session_new)
351 @userFB.publish_to(@userFB,
352 :message => "has won a big elephant",
354 :text => 'See my results',
355 :href => "http://apps.facebook.com/testjawaker"},
357 :text => 'Try to beat him',
358 :href => "http://jawaker.com"}
361 :name => "Now I've won " + params[:tokens] + " tokens and I'm " + params[:rank] + "th between my friends!",
362 :href => 'http://jawaker.com',
363 :caption => 'Jawaker is a multiplayer card game website for the Arab world. Register now and start playing one of our online card games for FREE!',
364 :description => 'Start your first game right now',
368 :src => "http://jawaker.com/images/hp_mascot_ar-trans.png",
369 :href => "http://jawaker.com"}
373 rescue Facebooker::Session::SpecialUserAuthorizationRequired
374 @operation_result = "SPECIAL_USER_AUTHORIZATION_REQUIRED"
376 @operation_result = "UNKNOWN_ERROR"
378 render :layout => false
383 #processing local callback
385 #updating information about invited friends
386 unless params[:ids].blank?
388 add_stat(0,INVITED_NUMBER,params[:ids].size)
390 res = Net::HTTP.post_form(URI.parse(Jawaker_link),{'token' => 'R45ASL5V', 'api_action'=>'invited_friends','facebook_id'=>session[:facebook_session].user.uid, 'number_of_friends' =>params[:ids].size})
391 debug_message("Localcallback: information about nuber invited friends was sent to Jawaker")
393 debug_message("Localcallback: Some FB(get user.uid) or connection problem",false)
397 if cookies[:www_redirect] == "true"
398 cookies[:www_redirect] = nil
399 redirect_to "http://www.jawaker.com/games"
402 redirect_to "http://jawaker.com/games"
409 #Totally like Radio App statistic
411 current_date = Date.new(2010,01,23)
413 today = Date.new(today_now.year,today_now.month,today_now.day)
414 @date_range = (current_date..today).to_a
417 @date_range.each {|date|
418 @query_params = Hash.new(0)
419 @query_params[:created_at] = date
420 @query_string = "DATE(created_at) = :created_at"
421 @statistic = Stat.find(:all, :conditions => [@query_string ,@query_params])
422 one_pack = Hash.new(0)
424 @statistic.each {|stat|
427 one_pack[INVITED_NUMBER]+= stat[:extra]
428 @total [INVITED_NUMBER]+=stat[:extra]
429 when CONNECTED,PERMISSION, DELETED,REWARDED
430 one_pack[ stat[:action]]+= 1
431 @total[ stat[:action]]+= 1
434 when FROM_INVITATION, FROM_FEED
435 one_pack[stat[:extra]]+= 1
436 @total[stat[:extra]]+= 1
441 @data_pack.push one_pack
445 #end of new statistics
451 @titles = "Date,Connected,Status Permissions,Unistalled,Rewarded,Invitations Sent,Source by Invitation,Source by Feed".split(",")
452 report = StringIO.new
453 CSV::Writer.generate(report, ',') do |title|
455 @data_pack.each_with_index {|data, i|
456 title << [@date_range[i],data[CONNECTED],data[PERMISSION],data[DELETED],data[REWARDED],data[INVITED_NUMBER],data[FROM_INVITATION],data[FROM_FEED]]
458 title << ["Total",@total[CONNECTED],@total[PERMISSION],@total[DELETED],@total[REWARDED],@total[INVITED_NUMBER],@total[FROM_INVITATION],@total[FROM_FEED]]
461 time_now = Time.now.to_formatted_s(:number)
462 file = File.open("#{RAILS_ROOT}/public/#{time_now}.csv", "wb")
463 file.write(report.read)
465 redirect_to "/fb/#{time_now}.csv"
467 #processing callback from facebook
470 if params[:fb_sig_uninstall] == "1"
472 res = Net::HTTP.post_form(URI.parse(Jawaker_link),{'token' => 'R45ASL5V','api_action'=>'deleted','facebook_id'=>params[:fb_sig_user]})
473 debug_message("Information about deleted user was sent")
475 debug_message("Cannot connect Jawaker",false)
477 @fbfriend = Fbfriend.find(:first, :conditions => ["facebook_id = ?", params[:fb_sig_user]])
480 debug_message("User " + params[:fb_sig_user].to_s + " was destroyed from local MW DB")
481 add_stat(params[:fb_sig_user], DELETED)
484 #if kind of callback (deleted, given permission)- give know to Jawaker
490 #if user is loggined in facebook and in our list
492 if (session[:facebook_session])
493 User.sessionkey = session[:facebook_session].session_key
494 User.sessionkey_time = DateTime.now
495 debug_message("Session key was taken")
498 if false #(session[:facebook_session])
499 #if (session[:facebook_session].user.has_added_app)
501 #getting friend list who is already registered
503 my_friends.push(session[:facebook_session].user.uid)
504 for friend in session[:facebook_session].user.friends
505 my_friends.push(friend.uid)
507 #sending list of friends and getting list who are already connected to exclude invitation
508 res = Net::HTTP.post_form(URI.parse(Jawaker_link),{'token' => 'R45ASL5V','api_action'=>'get_jawaker_rank', 'friend_list' => my_friends.join(',') })
509 @answer_result = JSON.parse(res.body)
511 "facebookapp B O O M!"
514 render :layout => false
519 p " > > > G E T R E S U L T S"
521 @json_data = Hash.new(0)
523 case params[:api_action]
526 p " > > > USER REGISTERED"
530 p " > > > USER DELETED"
532 when "permission_set"
534 p " > > > PERMISSION SET"
536 when "friend_list_update"
537 p " > > > FREIND LIST UPDATE"
539 when "connected_friends"
544 #@json_data[:friend_list] = [43422890,33334444]
545 #p " > > > GIVING REGISTERED USER FRIENDS"
548 when "get_jawaker_ranks"
549 p " > > > GET JAWAKER RANKS"
551 @json_data0 = [521325397,749095503,687665098,514733981,1382916266,516054981]
552 @json_data1 = ["batman","soccerman","killer_of_devil","just_me","Kolobok","Knight"]
553 @json_data2 = [ 122,455,566,3335,33334,55555]
557 for i in 0..@json_data0.size-1
558 @data_pack = {:nickname => @json_data1[i], :facebook_id => @json_data0[i], :tokens => @json_data2[i]}
559 friends_list.push(@data_pack)
563 @json_data[:friends_list] = friends_list
564 #end of case params[:mw_action]
567 render :layout => false
573 debug_message("Session_time: #{User.sessionkey_time}, key: #{User.sessionkey} ")
575 @fbusers = Fbfriend.find(:all)
576 #calculating of number hours since last session
577 time_since_last_session = (User.sessionkey_time != nil ) ? Date.day_fraction_to_time(DateTime.now - User.sessionkey_time ) : [1]
579 #if user exists and time more than one hour (first position in array)
580 if (@fbusers == []) || (time_since_last_session[0] > 0)
582 flash[:notice] = "No one was choosen"
584 flash[:notice] = Message_reload_app_page
587 session = Facebooker::Session.create
588 session.session_key = User.sessionkey
590 threads << Thread.new do
591 #update each user from querry
592 @fbusers.each do |fbuser|
593 @userFB = Facebooker::User.new(fbuser.facebook_id , session)
595 @userFB.set_status(params[:new_status])
596 #fbuser.update_attributes(:status => params[:new_status])
597 debug_message("User's #{fbuser.facebook_id} status now is '#{params[:new_status]}'")
598 rescue Facebooker::Session::ExtendedPermissionRequired
599 debug_message("User #{fbuser.facebook_id } does not have permission")
600 #fbuser.update_attributes(:deleted => Deleted)
601 #add_stat(fbuser.uid, DELETED)
603 debug_message("Unknown mistake trying to change status #{fbuser.uid}",false)
606 #end threads << Thread.new do
608 flash[:notice] = 'Statuses for this groupping are being changed. It will take about '+ (@fbusers.size*2).to_s+' seconds. All users without status permission will be deleted'
611 respond_to do |format|
612 format.html { redirect_to("/stat") }
613 format.xml { head :ok }
615 #end def status_change
617 #sending of notification
618 def notification_send
620 @fbusers = Fbfriend.find(:all)
623 #preparing list of users to send them
625 @fbusers.each do |fbuser|
626 ids.push(fbuser.facebook_id )
632 new_session = Facebooker::Session.create
633 ids.each_slice(Max_notification_per_time) do |current_batch|
635 current_batch.each_slice(batch_size ) do |small_batch|
636 new_session.send_notification(small_batch, params[:notification],"app_to_user")
638 #@total_sent += result
641 debug_message("#{ids.size} notifications were sent")
642 flash[:notice] = 'Notification to this groupping was successfully sended'
644 flash[:notice] = ' Error with sending occured'
647 flash[:notice] = 'No one exists to send them notification'
650 new_params = Hash.new(0)
652 :age => params[:age],
653 :gender => params[:gender],
654 :relation => params[:relation]
657 respond_to do |format|
658 format.html { redirect_to(users_url) }
659 format.xml { head :ok }
661 #end notification_send