From 62d12497d8d63b96d7b1336ecdeeff5bccf56aa7 Mon Sep 17 00:00:00 2001 From: Steven Miers Date: Wed, 15 Oct 2014 17:59:59 -0500 Subject: [PATCH 01/53] VRFS-2029 : Fix issue where a nil (instead of false) is causing claimed_recording not to save properly. --- ruby/lib/jam_ruby/models/recorded_video.rb | 4 ++++ ruby/lib/jam_ruby/models/recording.rb | 6 +++--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/ruby/lib/jam_ruby/models/recorded_video.rb b/ruby/lib/jam_ruby/models/recorded_video.rb index fc787d20a..42f40ea9c 100644 --- a/ruby/lib/jam_ruby/models/recorded_video.rb +++ b/ruby/lib/jam_ruby/models/recorded_video.rb @@ -6,6 +6,10 @@ module JamRuby validates :client_video_source_id, :presence => true + def upload_sign(content_md5) + + end + def self.create_from_video_source(video_source, recording) recorded_video_source = self.new recorded_video_source.recording = recording diff --git a/ruby/lib/jam_ruby/models/recording.rb b/ruby/lib/jam_ruby/models/recording.rb index 12e6ca119..1d9c6fd9c 100644 --- a/ruby/lib/jam_ruby/models/recording.rb +++ b/ruby/lib/jam_ruby/models/recording.rb @@ -181,7 +181,7 @@ module JamRuby # Called when a user wants to "claim" a recording. To do this, the user must have been one of the tracks in the recording. def claim(user, name, description, genre, is_public, upload_to_youtube=false) - + upload_to_youtube = !!upload_to_youtube # Correct where nil is borking save unless self.users.exists?(user) raise PermissionError, "user was not in this session" end @@ -306,7 +306,7 @@ module JamRuby uploads = [] # Uploads now include videos in addition to the tracks. - # This is accomplished using a SQL union via arel, as follows: + # This is accomplished using a SQL UNION query via arel, as follows: # Select fields from track. Note the reorder, which removes # the default scope sort as it b0rks the union. Also note the @@ -357,7 +357,7 @@ module JamRuby # Further joining and criteria for the unioned object: arel = arel.joins("INNER JOIN (SELECT id as rec_id, all_discarded, duration FROM recordings) recs ON rec_id=recorded_items.recording_id") \ .where('recorded_items.user_id' => user.id) \ - .where('recorded_items.fully_uploaded =?', false) \ + .where('recorded_items.fully_uploaded = ?', false) \ .where('recorded_items.id > ?', since) \ .where("upload_failures <= #{APP_CONFIG.max_track_upload_failures}") \ .where("duration IS NOT NULL") \ From 6019aced8d3429c8485f238f9f73db4b2ae651ac Mon Sep 17 00:00:00 2001 From: Steven Miers Date: Wed, 15 Oct 2014 18:20:32 -0500 Subject: [PATCH 02/53] Routes and controller stubs for video upload web service. (VRFS-2030, VRFS-2031, VRFS-2032). --- .../controllers/api_recordings_controller.rb | 53 +++++++++++++++---- web/config/routes.rb | 7 +++ 2 files changed, 50 insertions(+), 10 deletions(-) diff --git a/web/app/controllers/api_recordings_controller.rb b/web/app/controllers/api_recordings_controller.rb index e7c67b29d..23eedb993 100644 --- a/web/app/controllers/api_recordings_controller.rb +++ b/web/app/controllers/api_recordings_controller.rb @@ -1,8 +1,9 @@ class ApiRecordingsController < ApiController before_filter :api_signed_in_user, :except => [ :add_like ] - before_filter :look_up_recording, :only => [ :show, :stop, :claim, :discard, :keep ] - before_filter :parse_filename, :only => [ :download, :upload_next_part, :upload_sign, :upload_part_complete, :upload_complete ] + before_filter :lookup_recording, :only => [ :show, :stop, :claim, :discard, :keep ] + before_filter :lookup_recorded_track, :only => [ :download, :upload_next_part, :upload_sign, :upload_part_complete, :upload_complete ] + before_filter :lookup_recorded_video, :only => [ :video_upload_sign, :video_upload_start, :video_upload_start ] respond_to :json @@ -79,7 +80,7 @@ class ApiRecordingsController < ApiController # claim will create a claimed recording for the creator def claim - claim = @recording.claim(current_user, params[:name], params[:description], Genre.find_by_id(params[:genre]), params[:is_public], params[:upload_to_youtube]) + claim = @recording.claim(current_user, params[:name], params[:description], Genre.find_by_id(params[:genre]), params[:is_public], !!params[:upload_to_youtube]) if claim.errors.any? response.status = :unprocessable_entity @@ -205,16 +206,48 @@ class ApiRecordingsController < ApiController end end - - private - def parse_filename - @recorded_track = RecordedTrack.find_by_recording_id_and_client_track_id!(params[:id], params[:track_id]) - raise PermissionError, ValidationMessages::PERMISSION_VALIDATION_ERROR unless @recorded_track.recording.has_access?(current_user) + # POST /api/recordings/:id/videos/:video_id/upload_sign + def video_upload_sign + render :json => @recorded_video.upload_sign(params[:md5]), :status => 200 end - def look_up_recording + # POST /api/recordings/:id/videos/:video_id/upload_complete + def video_upload_start + response = { + :offset=>0, + :length=>0, + :status=>200 + } + + render :json => response, :status => 200 + end + + # POST /api/recordings/:id/videos/:video_id/upload_complete + def video_upload_complete + response = { + :offset=>0, + :length=>0, + :status=>200 + } + + render :json => response, :status => 200 + end + + private + + def lookup_recording @recording = Recording.find(params[:id]) raise PermissionError, ValidationMessages::PERMISSION_VALIDATION_ERROR unless @recording.has_access?(current_user) end -end + def lookup_recorded_track + @recorded_track = RecordedTrack.find_by_recording_id_and_client_track_id!(params[:id], params[:track_id]) + raise PermissionError, ValidationMessages::PERMISSION_VALIDATION_ERROR unless @recorded_track.recording.has_access?(current_user) + end + + def lookup_recorded_video + @recorded_video = RecordedVideo.find_by_recording_id_and_client_video_source_id!(params[:id], params[:video_id]) + raise PermissionError, ValidationMessages::PERMISSION_VALIDATION_ERROR unless @recorded_video.recording.has_access?(current_user) + end + +end # class diff --git a/web/config/routes.rb b/web/config/routes.rb index 5bdab1017..fa553d0d3 100644 --- a/web/config/routes.rb +++ b/web/config/routes.rb @@ -396,12 +396,19 @@ SampleApp::Application.routes.draw do match '/recordings/:id/comments' => 'api_recordings#add_comment', :via => :post, :as => 'api_recordings_add_comment' match '/recordings/:id/likes' => 'api_recordings#add_like', :via => :post, :as => 'api_recordings_add_like' match '/recordings/:id/discard' => 'api_recordings#discard', :via => :post, :as => 'api_recordings_discard' + + # Recordings - recorded_tracks match '/recordings/:id/tracks/:track_id/download' => 'api_recordings#download', :via => :get, :as => 'api_recordings_download' match '/recordings/:id/tracks/:track_id/upload_next_part' => 'api_recordings#upload_next_part', :via => :get match '/recordings/:id/tracks/:track_id/upload_sign' => 'api_recordings#upload_sign', :via => :get match '/recordings/:id/tracks/:track_id/upload_part_complete' => 'api_recordings#upload_part_complete', :via => :post match '/recordings/:id/tracks/:track_id/upload_complete' => 'api_recordings#upload_complete', :via => :post + # Recordings - recorded_videos + match '/recordings/:id/tracks/:video_id/upload_sign' => 'api_recordings#video_upload_sign', :via => :get + match '/recordings/:id/videos/:video_id/upload_start' => 'api_recordings#video_upload_start', :via => :post + match '/recordings/:id/videos/:video_id/upload_complete' => 'api_recordings#video_upload_complete', :via => :post + # Claimed Recordings match '/claimed_recordings' => 'api_claimed_recordings#index', :via => :get match '/claimed_recordings/:id' => 'api_claimed_recordings#show', :via => :get From e4452a5e95f639e5a94af8abc131d1631c0f02a6 Mon Sep 17 00:00:00 2001 From: Steven Miers Date: Tue, 28 Oct 2014 13:57:06 -0500 Subject: [PATCH 03/53] Youtube client, with several methods to assist with logging in, starting and checking uploads, etc. Even contains an internal web server to intercept the callback from google for self-contained or feature testing. (VRFS-2030, VRFS-2031, VRFS-2032). --- web/lib/youtube_client.rb | 147 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 147 insertions(+) create mode 100644 web/lib/youtube_client.rb diff --git a/web/lib/youtube_client.rb b/web/lib/youtube_client.rb new file mode 100644 index 000000000..58dd5ce7d --- /dev/null +++ b/web/lib/youtube_client.rb @@ -0,0 +1,147 @@ +require 'faraday' +require 'thin' +require 'launchy' +require 'cgi' +require 'google/api_client' +require 'google/api_client/client_secrets' +require 'google/api_client/auth/installed_app' + + +module JamRuby + class YouTubeClient + attr_accessor :client + attr_accessor :api + attr_accessor :request + attr_accessor :server + attr_accessor :config + + def initialize() + self.config = Rails.application.config + + self.client = Google::APIClient.new( + :application_name => 'JamKazam', + :application_version => '1.0.0' + ) + + youtube = client.discovered_api('youtube', 'v3') + # client.authorization = nil + # result = client.execute + # :key => config.youtube_developer_key, + # :api_method => youtube.videos.list, + # :parameters => {:id => '', :part => 'snippet'} + # result = JSON.parse(result.data.to_json) + end + + # Return a login URL that will show a web page with + def get_login_url(username=nil) + uri = "https://accounts.google.com/o/oauth2/auth" + uri << "?scope=#{CGI.escape('email profile')}" + uri << "&client_id=#{CGI.escape(self.config.google_client_id)}" + #uri << "&client_secret=#{CGI.escape(self.config.google_secret)}" + uri << "&response_type=code" + uri << "&access_type=online" + uri << "&prompt=consent" + uri << "&state=4242" + uri << "&redirect_uri=#{('http://localhost:3000/auth/google_login/callback')}" + if username.present? + uri << "&login_hint=#{(username)}" + end + uri + end + + # This will also sign in and prompt for login as necessary; + # currently requires the server to be running at localhost:3000 + def signin_flow() + config = Rails.application.config + + self.client = Google::APIClient.new( + :application_name => 'JamKazam', + :application_version => '1.0.0' + ) + + flow = Google::APIClient::InstalledAppFlow.new( + :client_id => config.google_client_id, + :client_secret => config.google_secret, + :redirect_uri=>"http://localhost:3000/auth/google_login/callback", + :scope => 'email profile' + ) + + self.client.authorization = flow.authorize + end + + + + # Must manually confirm to obtain refresh token: + # 4/ZwtU8nNgiEiu2JlJMrmnnw.Qo7Zys7XjRoZPm8kb2vw2M2j2ZEskgI + def get_refresh_token + config = Rails.application.config + conn = Faraday.new(:url => 'https://accounts.google.com',:ssl => {:verify => false}) do |faraday| + faraday.request :url_encoded + faraday.response :logger + faraday.adapter Faraday.default_adapter + end + + wait_for_callback do |refresh_token| + puts "The refresh_token is #{refresh_token}" + end + + + result = conn.get '/o/oauth2/auth', { + 'scope'=>'email profile', + 'client_id'=>config.google_client_id, + 'response_type'=>"code", + 'access_type'=>"offline", + 'redirect_uri'=>"http://localhost:3000/auth/google_login/callback" + } + end + + def get_access_token(refresh_token) + refresh_token = "4/g9uZ8S4lq2Bj1J8PPIkgOFKhTKmCHSmRe68iHA75hRg.gj8Nt5bpVYQdPm8kb2vw2M23tnRnkgI" + #refresh_token = "4/ZwtU8nNgiEiu2JlJMrmnnw.Qo7Zys7XjRoZPm8kb2vw2M2j2ZEskgI" + config = Rails.application.config + conn = Faraday.new(:url => 'https://accounts.google.com',:ssl => {:verify => false}) do |faraday| + faraday.request :url_encoded + faraday.response :logger + faraday.adapter Faraday.default_adapter + end + + wait_for_callback do |access_token| + puts "The access_token is #{access_token}" + #self.server.stop() + end + + result = conn.post '/o/oauth2/token', nil, { + 'scope'=>'email profile', + 'client_id'=>config.google_client_id, + 'client_secret'=>config.google_secret, + 'refresh_token'=>refresh_token, + #'response_type'=>"code", + 'grant_type'=>"refresh_token", + #'access_type'=>"offline", + 'redirect_uri'=>"http://localhost:3000/auth/google_login/callback" + } + + puts "REsult: #{result.inspect}\n\n" + end + + def wait_for_callback(port=3000) + if (self.server) + self.server.stop() + self.server.stop!() + self.server=nil + end + + svr = Thin::Server.new('0.0.0.0', port) do + run lambda { |env| + # Send auth code to block & stop the server: + req = Rack::Request.new(env) + yield(req['code']) + svr.stop() + [200, {'Content-Type' => 'text/plain'}, 'OK'] + } + end + self.server = svr + self.server.start() + end + end # class +end # module From d3cd51d76d787af85743b74361507af8070af51e Mon Sep 17 00:00:00 2001 From: Steven Miers Date: Tue, 28 Oct 2014 13:57:47 -0500 Subject: [PATCH 04/53] Other drivers, such as webkit don't have these options, so check the driver first: --- web/spec/spec_helper.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/spec/spec_helper.rb b/web/spec/spec_helper.rb index 95b6f42e1..2297b22e1 100644 --- a/web/spec/spec_helper.rb +++ b/web/spec/spec_helper.rb @@ -192,7 +192,7 @@ bputs "before register capybara" end config.before(:each) do - if example.metadata[:js] + if example.metadata[:js] && Capybara.current_driver==:poltergeist page.driver.resize(1920, 1080) page.driver.headers = { 'User-Agent' => 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0' } end From c6ee3d01b0c405c6298032fa03fdc4c035d84390 Mon Sep 17 00:00:00 2001 From: Steven Miers Date: Tue, 28 Oct 2014 14:07:54 -0500 Subject: [PATCH 05/53] A util method for testing that opens the google oauth web UI and logs in using a username password, logs in and approves. Uses our youtube client to intercept the auth token and add it to the user_authorizations. This allows us to use and test youtube API functionality as a real user. (VRFS-2030, VRFS-2031, VRFS-2032). --- web/spec/support/utilities.rb | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/web/spec/support/utilities.rb b/web/spec/support/utilities.rb index e57f78fc7..7fc5ad2ad 100644 --- a/web/spec/support/utilities.rb +++ b/web/spec/support/utilities.rb @@ -73,6 +73,36 @@ def wipe_s3_test_bucket end end +def authorize_google_user(user, google_password) + youtube_client = YouTubeClient.new() + youtube_client.wait_for_callback do |access_token| + user_auth_hash = { + :provider => "google_login", + :uid => user.email, + :token => access_token, + :token_expiration => Time.now() + 7.days, + :secret => "" + } + authorization = user.user_authorizations.build(user_auth_hash) + authorization.save + end + + url = youtube_client.get_login_url(user.email) + visit url + + # Fill in password (the username is filled in with a hint in URL): + fill_in "Passwd", with: google_password + find('#signIn').trigger(:click) + + # Wait for submit to enable and then click it: + sleep(5) + #save_screenshot("log1.png") + find('#submit_approve_access').trigger(:click) + #save_screenshot("log2.png") + + puts "Google Login URL: #{url}" + youtube_client +end def sign_in(user) visit signin_path From c5d0703643df96a644e8bdaa859920d19c6fe7e2 Mon Sep 17 00:00:00 2001 From: Steven Miers Date: Tue, 28 Oct 2014 14:08:27 -0500 Subject: [PATCH 06/53] Spec that logs into a real youtube/gmail account and verifies access token. (VRFS-2030, VRFS-2031, VRFS-2032). --- web/spec/features/oauth_spec.rb | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 web/spec/features/oauth_spec.rb diff --git a/web/spec/features/oauth_spec.rb b/web/spec/features/oauth_spec.rb new file mode 100644 index 000000000..94b506ae4 --- /dev/null +++ b/web/spec/features/oauth_spec.rb @@ -0,0 +1,32 @@ +require 'spec_helper' +require 'youtube_client' + +describe "OAuth", :js=>true, :type => :feature, :capybara_feature => true do + + let(:user) { FactoryGirl.create(:user, :email => "steven@jamkazam.com") } + + subject { page } + + before(:all) do + Capybara.run_server = false + Capybara.javascript_driver = :poltergeist + Capybara.current_driver = Capybara.javascript_driver + Capybara.default_wait_time = 15 + Capybara.ignore_hidden_elements = false + end + + describe "client should authorize a google user" do + it { + youtube_client=authorize_google_user(user, "jam123") + sleep(5) + save_screenshot("log3.png") + user.reload + user.user_authorizations.count.should eq(1) + + google_auth = UserAuthorization.google_auth(user).first + google_auth.should_not be_nil + google_auth.token.should_not be_nil + } + end + +end From 7265379101e02912bb9b1ed36794f6eb72a54ec4 Mon Sep 17 00:00:00 2001 From: Steven Miers Date: Tue, 28 Oct 2014 14:09:44 -0500 Subject: [PATCH 07/53] Update gems for google/oauth/youtube stuff and testing thereof. (VRFS-2030, VRFS-2031, VRFS-2032). --- web/Gemfile | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/web/Gemfile b/web/Gemfile index 4c31c7956..7b121350b 100644 --- a/web/Gemfile +++ b/web/Gemfile @@ -37,13 +37,16 @@ gem 'compass-rails', '1.1.3' # 1.1.4 throws an exception on startup about !init gem 'rabl' # for JSON API development gem 'gon', '~>4.1.0' # for passthrough of Ruby variables to Javascript variables gem 'eventmachine', '1.0.3' +gem 'faraday', '~>0.9.0' gem 'amqp', '0.9.8' gem 'logging-rails', :require => 'logging/rails' gem 'omniauth', '1.1.1' gem 'omniauth-facebook', '1.4.1' gem 'omniauth-twitter' gem 'omniauth-google-oauth2', '0.2.1' -gem 'google-api-client' +gem 'google-api-client', '0.7.1' +gem 'google-api-omniauth', '0.1.1' +gem 'signet', '0.5.0' gem 'twitter' gem 'fb_graph', '2.5.9' gem 'sendgrid', '1.2.0' @@ -115,15 +118,17 @@ group :test, :cucumber do gem "capybara-webkit" #end gem 'capybara-screenshot', '0.3.22' # 1.0.0 broke compat with rspec. maybe we need newer rspec + gem 'selenium-webdriver' gem 'cucumber-rails', :require => false #, '1.3.0', :require => false gem 'guard-spork', '0.3.2' gem 'spork', '0.9.0' - gem 'launchy', '2.1.0' + gem 'launchy', '2.1.1' gem 'rack-test' # gem 'rb-fsevent', '0.9.1', :require => false # gem 'growl', '1.0.3' gem 'poltergeist' gem 'resque_spec' + gem 'thin' end From 2b8596607c4a738ff08149c5a9aad11b8bbe41f8 Mon Sep 17 00:00:00 2001 From: Steven Miers Date: Tue, 28 Oct 2014 14:10:55 -0500 Subject: [PATCH 08/53] Rename goog_auth to google_auth. --- ruby/lib/jam_ruby/models/user_authorization.rb | 2 +- web/app/controllers/gmail_controller.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ruby/lib/jam_ruby/models/user_authorization.rb b/ruby/lib/jam_ruby/models/user_authorization.rb index fe1a3e5f5..e83bb8db4 100644 --- a/ruby/lib/jam_ruby/models/user_authorization.rb +++ b/ruby/lib/jam_ruby/models/user_authorization.rb @@ -12,7 +12,7 @@ module JamRuby validates_uniqueness_of :uid, scope: :provider # token, secret, token_expiration can be missing - def self.goog_auth(user) + def self.google_auth(user) self .where(:user_id => user.id) .where(:provider => 'google_login') diff --git a/web/app/controllers/gmail_controller.rb b/web/app/controllers/gmail_controller.rb index e4f1e1906..16c18cad9 100644 --- a/web/app/controllers/gmail_controller.rb +++ b/web/app/controllers/gmail_controller.rb @@ -6,7 +6,7 @@ class GmailController < ApplicationController render :nothing => true, :status => 404 return end - authorization = UserAuthorization.goog_auth(current_user) + authorization = UserAuthorization.google_auth(current_user) if authorization.empty? render :nothing => true, :status => 404 return From b68ae7e4202bbeac1797f6dc0782a12891354b6e Mon Sep 17 00:00:00 2001 From: Steven Miers Date: Tue, 28 Oct 2014 15:13:19 -0500 Subject: [PATCH 09/53] Incremental API and test cleanup (VRFS-2030, VRFS-2031, VRFS-2032). --- .../controllers/api_recordings_controller.rb | 2 +- web/lib/youtube_client.rb | 182 +++++++++++++++++- web/spec/features/oauth_spec.rb | 45 +++-- web/spec/support/utilities.rb | 3 +- 4 files changed, 209 insertions(+), 23 deletions(-) diff --git a/web/app/controllers/api_recordings_controller.rb b/web/app/controllers/api_recordings_controller.rb index 23eedb993..ba16d8d6e 100644 --- a/web/app/controllers/api_recordings_controller.rb +++ b/web/app/controllers/api_recordings_controller.rb @@ -3,7 +3,7 @@ class ApiRecordingsController < ApiController before_filter :api_signed_in_user, :except => [ :add_like ] before_filter :lookup_recording, :only => [ :show, :stop, :claim, :discard, :keep ] before_filter :lookup_recorded_track, :only => [ :download, :upload_next_part, :upload_sign, :upload_part_complete, :upload_complete ] - before_filter :lookup_recorded_video, :only => [ :video_upload_sign, :video_upload_start, :video_upload_start ] + before_filter :lookup_recorded_video, :only => [ :video_upload_sign, :video_upload_start, :video_upload_complete ] respond_to :json diff --git a/web/lib/youtube_client.rb b/web/lib/youtube_client.rb index 58dd5ce7d..53dde2239 100644 --- a/web/lib/youtube_client.rb +++ b/web/lib/youtube_client.rb @@ -6,7 +6,7 @@ require 'google/api_client' require 'google/api_client/client_secrets' require 'google/api_client/auth/installed_app' - +# Youtube API functionality: module JamRuby class YouTubeClient attr_accessor :client @@ -16,6 +16,7 @@ module JamRuby attr_accessor :config def initialize() + puts "Initializing client..." self.config = Rails.application.config self.client = Google::APIClient.new( @@ -49,6 +50,167 @@ module JamRuby uri end + # Contacts youtube and prepares an upload to youtube. This + # process is somewhat painful, even in ruby, so we do the preparation + # and the client does the actual upload using the URL returned: + def upload_sign(user, filename, length) + # Something like this: + # POST /upload/youtube/v3/videos?uploadType=resumable&part=snippet,status,contentDetails HTTP/1.1 + # Host: www.googleapis.com + # Authorization: Bearer AUTH_TOKEN + # Content-Length: 278 + # Content-Type: application/json; charset=UTF-8 + # X-Upload-Content-Length: 3000000 + # X-Upload-Content-Type: video/* + + # { + # "snippet": { + # "title": "My video title", + # "description": "This is a description of my video", + # "tags": ["cool", "video", "more keywords"], + # "categoryId": 22 + # }, + # "status": { + # "privacyStatus": "public", + # "embeddable": True, + # "license": "youtube" + # } + # } + auth = UserAuthorization.google_auth(user).first + if auth.nil? || auth.token.nil? + raise SecurityError, "No current google token found for user #{user}" + end + + video_data = { + "snippet"=> { + "title"=> filename, + "description"=> filename, + # "tags"=> ["cool", "video", "more keywords"], + # "categoryId"=> 22 + }, + "status"=> { + "privacyStatus"=> "public", + "embeddable"=> true, + "license"=> "youtube" + } + } + + conn = Faraday.new(:url =>"www.googleapis.com",:ssl => {:verify => false}) do |faraday| + faraday.request :url_encoded + faraday.response :logger + faraday.adapter Faraday.default_adapter + end + + result = conn.post '/upload/youtube/v3/videos', + video_data, + { + 'authorization'=>"bearer #{auth.token}", + 'content-type'=>'application/json; charset=utf-8', + 'x-upload-content-length'=>length, + 'X-Upload-Content-Type'=>"video/*" + } + + # Response should look like: + # HTTP/1.1 200 OK + # Location: https://www.googleapis.com/upload/youtube/v3/videos?uploadType=resumable&upload_id=xa298sd_f&part=snippet,status,contentDetails + # Content-Length: 0 + + if result.body.nil? || result.body.blank? + raise "Result not in correct form: [#{result.body}]" + end + + lines = result.body.split("\n") + + if lines.length !=3 + raise "Result not in correct form: [#{lines.inspect}]" + end + + + first_line = lines.first.split(" ") + if first_line.length !=3 + raise "First line not in correct form: [#{first_line}]" + end + + status = first_line[1].to_i + if (status != 200) + raise "Status from youtube: #{status}" + end + + location_url = lines[1].split(":").last().trim() + + # This has everything one needs to start the upload to youtube: + { + "method"=> "PUT", + "url"=> location_url, + "Authorization"=> "Bearer #{token}", + "Content-Length"=> length, + "Content-Type"=> "video/*" + } + end + + # https://developers.google.com/youtube/v3/guides/using_resumable_upload_protocol#Check_Upload_Status + def get_upload_status(user, upload_url, length) + auth = UserAuthorization.google_auth(user).first + if auth.nil? || auth.token.nil? + raise SecurityError, "No current google token found for user #{user}" + end + + conn = Faraday.new(:url => upload_url,:ssl => {:verify => false}) do |faraday| + faraday.request :url_encoded + faraday.response :logger + faraday.adapter Faraday.default_adapter + end + + result = conn.put '/o/oauth2/auth', { + 'Authorization'=>"Bearer #{auth.token}", + 'Content-Length'=>0, + 'Content-Range'=>"bytes */#{length}", # This may seem like it should be on the parm above, but it is per the docs + 'access_type'=>"offline", + 'redirect_uri'=>"http://localhost:3000/auth/google_login/callback" + } + + # PUT UPLOAD_URL HTTP/1.1 + # Authorization: Bearer AUTH_TOKEN + # Content-Length: 0 + # Content-Range: bytes */CONTENT_LENGTH + + # Result looks like this: + # 308 Resume Incomplete + # Content-Length: 0 + # Range: bytes=0-999999 + + if result.body.nil? || result.body.blank? + raise "Result not in correct form: [#{result.body}]" + end + + lines = result.body.split("\n") + + if lines.length !=3 + raise "Result not in correct form: [#{lines.inspect}]" + end + + first_line = lines.first.split(" ") + if first_line.length !=3 + raise "First line not in correct form: [#{first_line}]" + end + + status = range.first.to_i + range_str = lines.last.split("=").last + range = range_str.split("-") + + { + "offset" => range.first.to_i, + "length" => range.last.to_i, + "status" => status, + } + end + + # @return true if file specified by URL uploaded, false otherwise + def verify_upload(user, url, length) + status_hash=get_upload_status(user, upload_url, length) + status_hash[:status]==201 + end + # This will also sign in and prompt for login as necessary; # currently requires the server to be running at localhost:3000 def signin_flow() @@ -125,23 +287,29 @@ module JamRuby end def wait_for_callback(port=3000) - if (self.server) - self.server.stop() - self.server.stop!() - self.server=nil - end + shutdown() svr = Thin::Server.new('0.0.0.0', port) do run lambda { |env| # Send auth code to block & stop the server: req = Rack::Request.new(env) yield(req['code']) - svr.stop() + #svr.stop() [200, {'Content-Type' => 'text/plain'}, 'OK'] } end self.server = svr self.server.start() + self.server.log_info("Listening for oauth token. Will shut down automatically.") + end + + # shutdown + def shutdown() + if (self.server) + self.server.log_info("Stopping server...") + self.server.stop() + # EventMachine.stop + end end end # class end # module diff --git a/web/spec/features/oauth_spec.rb b/web/spec/features/oauth_spec.rb index 94b506ae4..1a7bbcf0a 100644 --- a/web/spec/features/oauth_spec.rb +++ b/web/spec/features/oauth_spec.rb @@ -3,11 +3,10 @@ require 'youtube_client' describe "OAuth", :js=>true, :type => :feature, :capybara_feature => true do - let(:user) { FactoryGirl.create(:user, :email => "steven@jamkazam.com") } - subject { page } before(:all) do + @user=FactoryGirl.create(:user, :email => "steven@jamkazam.com") Capybara.run_server = false Capybara.javascript_driver = :poltergeist Capybara.current_driver = Capybara.javascript_driver @@ -15,18 +14,38 @@ describe "OAuth", :js=>true, :type => :feature, :capybara_feature => true do Capybara.ignore_hidden_elements = false end - describe "client should authorize a google user" do - it { - youtube_client=authorize_google_user(user, "jam123") - sleep(5) - save_screenshot("log3.png") - user.reload - user.user_authorizations.count.should eq(1) + before(:each) do + @youtube_client = YouTubeClient.new() + end - google_auth = UserAuthorization.google_auth(user).first - google_auth.should_not be_nil - google_auth.token.should_not be_nil - } + after(:each) do + @youtube_client.shutdown if @youtube_client + sleep(5) + @youtube_client=nil + @user.user_authorizations.destroy_all + end + + it "client should not authorize a wrong password" do + expect { + authorize_google_user(@youtube_client, @user, "f00bar") + }.to raise_error + + sleep(5) + save_screenshot("log3.png") + @user.reload + @user.user_authorizations.count.should eq(0) + end + + it "client should authorize a google user" do + authorize_google_user(@youtube_client, @user, "barfoo") + sleep(5) + save_screenshot("log3.png") + @user.reload + @user.user_authorizations.count.should eq(1) + + google_auth = UserAuthorization.google_auth(@user).first + google_auth.should_not be_nil + google_auth.token.should_not be_nil end end diff --git a/web/spec/support/utilities.rb b/web/spec/support/utilities.rb index 7fc5ad2ad..5fd012e81 100644 --- a/web/spec/support/utilities.rb +++ b/web/spec/support/utilities.rb @@ -73,8 +73,7 @@ def wipe_s3_test_bucket end end -def authorize_google_user(user, google_password) - youtube_client = YouTubeClient.new() +def authorize_google_user(youtube_client, user, google_password) youtube_client.wait_for_callback do |access_token| user_auth_hash = { :provider => "google_login", From 94c205fd0fa17e7be9e1324496f23e948533a9b7 Mon Sep 17 00:00:00 2001 From: Steven Miers Date: Wed, 29 Oct 2014 13:04:48 -0500 Subject: [PATCH 10/53] Merge - incremental --- .../views/admin/batch_emails/_form.html.erb | 2 +- db/manifest | 5 +- db/up/add_session_create_type.sql | 1 + db/up/user_syncs_and_quick_mix.sql | 68 + db/up/user_syncs_fix_dup_tracks_2408.sql | 32 + ruby/lib/jam_ruby.rb | 4 + ruby/lib/jam_ruby/lib/s3_manager.rb | 12 + ruby/lib/jam_ruby/models/mix.rb | 46 +- ruby/lib/jam_ruby/models/music_session.rb | 11 +- ruby/lib/jam_ruby/models/quick_mix.rb | 267 + .../lib/jam_ruby/models/quick_mix_observer.rb | 83 + ruby/lib/jam_ruby/models/recorded_track.rb | 23 +- ruby/lib/jam_ruby/models/recording.rb | 149 +- ruby/lib/jam_ruby/models/search.rb | 1 + ruby/lib/jam_ruby/models/user.rb | 11 +- ruby/lib/jam_ruby/models/user_sync.rb | 46 + ruby/lib/jam_ruby/resque/audiomixer.rb | 28 +- ruby/lib/jam_ruby/resque/quick_mixer.rb | 155 + .../resque/scheduled/audiomixer_retry.rb | 4 +- ruby/spec/factories.rb | 24 + ruby/spec/jam_ruby/models/quick_mix_spec.rb | 212 + .../jam_ruby/models/recorded_track_spec.rb | 1 + ruby/spec/jam_ruby/models/recording_spec.rb | 273 +- ruby/spec/jam_ruby/models/user_sync_spec.rb | 274 + ruby/spec/jam_ruby/resque/audiomixer_spec.rb | 49 +- ruby/spec/jam_ruby/resque/quick_mixer_spec.rb | 121 + ruby/spec/spec_helper.rb | 1 + web/Gemfile | 4 +- ...le24.png => icon_instrument_ukulele24.png} | Bin ...256.png => icon_instrument_ukulele256.png} | Bin ...le45.png => icon_instrument_ukulele45.png} | Bin .../javascripts/accounts_audio_profile.js | 2 +- web/app/assets/javascripts/application.js | 1 + .../javascripts/dialog/allSyncsDialog.js | 48 + .../dialog/recordingFinishedDialog.js | 5 + .../javascripts/dialog/whatsNextDialog.js | 64 - web/app/assets/javascripts/fakeJamClient.js | 8 + web/app/assets/javascripts/feedHelper.js | 17 +- .../assets/javascripts/feed_item_recording.js | 8 + web/app/assets/javascripts/globals.js | 6 +- web/app/assets/javascripts/hoverMusician.js | 32 + web/app/assets/javascripts/jam_rest.js | 46 + web/app/assets/javascripts/jquery.exists.js | 1 + web/app/assets/javascripts/landing/landing.js | 1 + web/app/assets/javascripts/layout.js | 3 + .../assets/javascripts/networkTestHelper.js | 2 +- .../assets/javascripts/notificationPanel.js | 1 + web/app/assets/javascripts/paginator.js | 18 +- .../assets/javascripts/recordingManager.js | 277 +- .../javascripts/recording_utils.js.coffee | 141 + ...ed_session.js => scheduled_session.js.erb} | 57 +- web/app/assets/javascripts/session.js | 12 +- web/app/assets/javascripts/sessionList.js | 17 +- web/app/assets/javascripts/sessionModel.js | 116 +- web/app/assets/javascripts/session_utils.js | 20 +- .../assets/javascripts/sync_viewer.js.coffee | 915 ++ web/app/assets/javascripts/utils.js | 64 +- web/app/assets/javascripts/web/web.js | 2 + .../stylesheets/client/account.css.scss | 2 +- .../assets/stylesheets/client/band.css.scss | 2 +- web/app/assets/stylesheets/client/client.css | 1 + .../assets/stylesheets/client/common.css.scss | 167 + .../stylesheets/client/content.css.scss | 1 - .../stylesheets/client/createSession.css.scss | 2 +- .../assets/stylesheets/client/ftue.css.scss | 4 +- .../assets/stylesheets/client/help.css.scss | 108 +- .../stylesheets/client/hoverBubble.css.scss | 46 + .../stylesheets/client/jamkazam.css.scss | 2 - .../client/recordingManager.css.scss | 30 +- .../stylesheets/client/screen_common.css.scss | 15 +- .../stylesheets/client/session.css.scss | 29 +- .../dialogs/gettingStartDialog.css.scss | 2 +- .../dialogs/syncViewerDialog.css.scss | 3 + .../stylesheets/easydropdown_jk.css.scss | 6 - .../stylesheets/users/syncViewer.css.scss | 287 + .../stylesheets/web/audioWidgets.css.scss | 15 +- .../stylesheets/web/recordings.css.scss | 5 +- .../api_claimed_recordings_controller.rb | 19 +- web/app/controllers/api_configs_controller.rb | 14 + .../api_music_notations_controller.rb | 17 +- .../controllers/api_recordings_controller.rb | 73 +- .../controllers/api_user_syncs_controller.rb | 41 + web/app/controllers/recordings_controller.rb | 6 +- web/app/helpers/feeds_helper.rb | 1 - web/app/helpers/recording_helper.rb | 7 + .../views/api_claimed_recordings/show.rabl | 16 +- web/app/views/api_feeds/show.rabl | 22 +- web/app/views/api_music_sessions/show.rabl | 62 +- .../api_music_sessions/show_history.rabl | 4 +- web/app/views/api_recordings/show.rabl | 40 +- .../api_recordings/show_recorded_track.rabl | 7 + web/app/views/api_user_syncs/index.rabl | 15 + web/app/views/api_user_syncs/show.rabl | 103 + web/app/views/api_users/show.rabl | 6 + web/app/views/api_users/show_minimal.rabl | 3 + .../views/clients/_account_identity.html.erb | 2 + web/app/views/clients/_findSession.html.erb | 2 +- web/app/views/clients/_help.html.erb | 22 + .../views/clients/_help_launcher.html.slim | 2 + web/app/views/clients/_hoverMusician.html.erb | 5 + web/app/views/clients/_musicians.html.erb | 2 +- web/app/views/clients/_play_controls.html.erb | 2 +- .../views/clients/_recordingManager.html.erb | 3 + .../views/clients/_scheduledSession.html.erb | 10 +- .../clients/_sync_viewer_templates.html.slim | 207 + web/app/views/clients/index.html.erb | 8 +- .../views/dialogs/_allSyncsDialog.html.slim | 14 + web/app/views/dialogs/_dialogs.html.haml | 2 +- web/app/views/users/_feed_recording.html.haml | 10 +- .../users/_feed_recording_ajax.html.haml | 7 +- web/app/views/users/_latest.html.haml | 2 +- web/config/application.rb | 4 +- web/config/routes.rb | 15 + .../api_claimed_recordings_spec.rb | 91 +- .../api_recordings_controller_spec.rb | 2 +- .../api_user_syncs_controller_spec.rb | 163 + web/spec/factories.rb | 42 +- web/spec/features/alt_landing_spec.rb | 8 +- web/spec/features/youtube_spec.rb | 42 + .../javascripts/fixtures/syncViewer.html.slim | 2 + .../fixtures/user_sync_track1.json | 174 + .../javascripts/helpers/jasmine-jquery.js | 700 -- web/spec/javascripts/spec_helper.js | 8 +- web/spec/javascripts/support/jasmine.yml | 76 - .../javascripts/sync_viewer_spec.js.coffee | 228 + web/spec/javascripts/vendor/jquery.js | 9405 ----------------- web/vendor/assets/javascripts/jquery.bt.js | 14 +- 127 files changed, 5520 insertions(+), 10728 deletions(-) create mode 100644 db/up/add_session_create_type.sql create mode 100644 db/up/user_syncs_and_quick_mix.sql create mode 100644 db/up/user_syncs_fix_dup_tracks_2408.sql create mode 100644 ruby/lib/jam_ruby/models/quick_mix.rb create mode 100644 ruby/lib/jam_ruby/models/quick_mix_observer.rb create mode 100644 ruby/lib/jam_ruby/models/user_sync.rb create mode 100644 ruby/lib/jam_ruby/resque/quick_mixer.rb create mode 100644 ruby/spec/jam_ruby/models/quick_mix_spec.rb create mode 100644 ruby/spec/jam_ruby/models/user_sync_spec.rb create mode 100644 ruby/spec/jam_ruby/resque/quick_mixer_spec.rb rename web/app/assets/images/content/{icon_instrument_ukelele24.png => icon_instrument_ukulele24.png} (100%) rename web/app/assets/images/content/{icon_instrument_ukelele256.png => icon_instrument_ukulele256.png} (100%) rename web/app/assets/images/content/{icon_instrument_ukelele45.png => icon_instrument_ukulele45.png} (100%) create mode 100644 web/app/assets/javascripts/dialog/allSyncsDialog.js delete mode 100644 web/app/assets/javascripts/dialog/whatsNextDialog.js create mode 100644 web/app/assets/javascripts/jquery.exists.js create mode 100644 web/app/assets/javascripts/recording_utils.js.coffee rename web/app/assets/javascripts/{scheduled_session.js => scheduled_session.js.erb} (93%) create mode 100644 web/app/assets/javascripts/sync_viewer.js.coffee create mode 100644 web/app/assets/stylesheets/dialogs/syncViewerDialog.css.scss create mode 100644 web/app/assets/stylesheets/users/syncViewer.css.scss create mode 100644 web/app/controllers/api_configs_controller.rb create mode 100644 web/app/controllers/api_user_syncs_controller.rb create mode 100644 web/app/views/api_recordings/show_recorded_track.rabl create mode 100644 web/app/views/api_user_syncs/index.rabl create mode 100644 web/app/views/api_user_syncs/show.rabl create mode 100644 web/app/views/api_users/show_minimal.rabl create mode 100644 web/app/views/clients/_help_launcher.html.slim create mode 100644 web/app/views/clients/_sync_viewer_templates.html.slim create mode 100644 web/app/views/dialogs/_allSyncsDialog.html.slim create mode 100644 web/spec/controllers/api_user_syncs_controller_spec.rb create mode 100644 web/spec/features/youtube_spec.rb create mode 100644 web/spec/javascripts/fixtures/syncViewer.html.slim create mode 100644 web/spec/javascripts/fixtures/user_sync_track1.json delete mode 100644 web/spec/javascripts/helpers/jasmine-jquery.js create mode 100644 web/spec/javascripts/sync_viewer_spec.js.coffee diff --git a/admin/app/views/admin/batch_emails/_form.html.erb b/admin/app/views/admin/batch_emails/_form.html.erb index 18fd10b82..75f4e0dd9 100644 --- a/admin/app/views/admin/batch_emails/_form.html.erb +++ b/admin/app/views/admin/batch_emails/_form.html.erb @@ -1,6 +1,6 @@ <%= semantic_form_for([:admin, resource], :url => resource.new_record? ? admin_batch_emails_path : "#{Gon.global.prefix}/admin/batch_emails/#{resource.id}") do |f| %> <%= f.inputs do %> - <%= f.input(:from_email, :label => "From Email", :input_html => {:maxlength => 64}) %> + <%= f.input(:from_email, :label => "From Email", :input_html => {:maxlength => 64}, :hint => 'JamKazam ') %> <%= f.input(:subject, :label => "Subject", :input_html => {:maxlength => 128}) %> <%= f.input(:test_emails, :label => "Test Emails", :input_html => {:maxlength => 1024, :size => '3x3'}) %> <%= f.input(:body, :label => "Body", :input_html => {:maxlength => 60000, :size => '10x20'}) %> diff --git a/db/manifest b/db/manifest index dbc4afe31..c8652bebf 100755 --- a/db/manifest +++ b/db/manifest @@ -221,4 +221,7 @@ connection_network_testing.sql video_sources.sql recorded_videos.sql emails_from_update2.sql -add_youtube_flag_to_claimed_recordings.sql \ No newline at end of file +add_youtube_flag_to_claimed_recordings.sql +add_session_create_type.sql +user_syncs_and_quick_mix.sql +user_syncs_fix_dup_tracks_2408.sql diff --git a/db/up/add_session_create_type.sql b/db/up/add_session_create_type.sql new file mode 100644 index 000000000..00fd5c728 --- /dev/null +++ b/db/up/add_session_create_type.sql @@ -0,0 +1 @@ +ALTER TABLE music_sessions ADD COLUMN create_type VARCHAR(64); diff --git a/db/up/user_syncs_and_quick_mix.sql b/db/up/user_syncs_and_quick_mix.sql new file mode 100644 index 000000000..4b997310a --- /dev/null +++ b/db/up/user_syncs_and_quick_mix.sql @@ -0,0 +1,68 @@ +ALTER TABLE recordings ADD COLUMN has_stream_mix BOOLEAN DEFAULT FALSE NOT NULL; +ALTER TABLE recordings ADD COLUMN has_final_mix BOOLEAN DEFAULT FALSE NOT NULL; +UPDATE recordings SET has_final_mix = TRUE WHERE (SELECT count(mixes.id) FROM mixes WHERE recording_id = recordings.id) > 0; + +CREATE TABLE quick_mixes ( + id BIGINT PRIMARY KEY, + next_part_to_upload INTEGER NOT NULL DEFAULT 0, + fully_uploaded BOOLEAN NOT NULL DEFAULT FALSE, + upload_id VARCHAR(1024), + file_offset BIGINT DEFAULT 0, + is_part_uploading BOOLEAN NOT NULL DEFAULT FALSE, + upload_failures INTEGER DEFAULT 0, + part_failures INTEGER DEFAULT 0, + ogg_md5 VARCHAR(100), + ogg_length INTEGER, + ogg_url VARCHAR(1000), + mp3_md5 VARCHAR(100), + mp3_length INTEGER, + mp3_url VARCHAR(1000), + error_count INTEGER NOT NULL DEFAULT 0, + error_reason TEXT, + error_detail TEXT, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + started_at TIMESTAMP, + completed_at TIMESTAMP, + completed BOOLEAN NOT NULL DEFAULT FALSE, + should_retry BOOLEAN NOT NULL DEFAULT FALSE, + cleaned BOOLEAN NOT NULL DEFAULT FALSE, + user_id VARCHAR(64) REFERENCES users(id) ON DELETE SET NULL, + recording_id VARCHAR(64) REFERENCES recordings(id) ON DELETE CASCADE +); + +ALTER TABLE quick_mixes ALTER COLUMN id SET DEFAULT nextval('tracks_next_tracker_seq'); + +CREATE VIEW user_syncs AS + SELECT b.id AS recorded_track_id, + CAST(NULL as BIGINT) AS mix_id, + CAST(NULL as BIGINT) as quick_mix_id, + b.id AS unified_id, + a.user_id AS user_id, + b.fully_uploaded, + recordings.created_at AS created_at, + recordings.id AS recording_id + FROM recorded_tracks a INNER JOIN recordings ON a.recording_id = recordings.id AND duration IS NOT NULL AND all_discarded = FALSE INNER JOIN recorded_tracks b ON a.recording_id = b.recording_id + UNION ALL + SELECT CAST(NULL as BIGINT) AS recorded_track_id, + mixes.id AS mix_id, + CAST(NULL as BIGINT) AS quick_mix_id, + mixes.id AS unified_id, + claimed_recordings.user_id AS user_id, + NULL as fully_uploaded, + recordings.created_at AS created_at, + recordings.id AS recording_id + FROM mixes INNER JOIN recordings ON mixes.recording_id = recordings.id INNER JOIN claimed_recordings ON recordings.id = claimed_recordings.recording_id WHERE claimed_recordings.discarded = FALSE + UNION ALL + SELECT CAST(NULL as BIGINT) AS recorded_track_id, + CAST(NULL as BIGINT) AS mix_id, + quick_mixes.id AS quick_mix_id, + quick_mixes.id AS unified_id, + quick_mixes.user_id, + quick_mixes.fully_uploaded, + recordings.created_at AS created_at, + recordings.id AS recording_id + FROM quick_mixes INNER JOIN recordings ON quick_mixes.recording_id = recordings.id AND duration IS NOT NULL AND all_discarded = FALSE; + +ALTER TABLE recordings ADD COLUMN first_quick_mix_id BIGINT REFERENCES quick_mixes(id) ON DELETE SET NULL; + diff --git a/db/up/user_syncs_fix_dup_tracks_2408.sql b/db/up/user_syncs_fix_dup_tracks_2408.sql new file mode 100644 index 000000000..2d98e8940 --- /dev/null +++ b/db/up/user_syncs_fix_dup_tracks_2408.sql @@ -0,0 +1,32 @@ +DROP VIEW user_syncs; + +CREATE VIEW user_syncs AS + SELECT DISTINCT b.id AS recorded_track_id, + CAST(NULL as BIGINT) AS mix_id, + CAST(NULL as BIGINT) as quick_mix_id, + b.id AS unified_id, + a.user_id AS user_id, + b.fully_uploaded, + recordings.created_at AS created_at, + recordings.id AS recording_id + FROM recorded_tracks a INNER JOIN recordings ON a.recording_id = recordings.id AND duration IS NOT NULL AND all_discarded = FALSE INNER JOIN recorded_tracks b ON a.recording_id = b.recording_id + UNION ALL + SELECT CAST(NULL as BIGINT) AS recorded_track_id, + mixes.id AS mix_id, + CAST(NULL as BIGINT) AS quick_mix_id, + mixes.id AS unified_id, + claimed_recordings.user_id AS user_id, + NULL as fully_uploaded, + recordings.created_at AS created_at, + recordings.id AS recording_id + FROM mixes INNER JOIN recordings ON mixes.recording_id = recordings.id INNER JOIN claimed_recordings ON recordings.id = claimed_recordings.recording_id WHERE claimed_recordings.discarded = FALSE + UNION ALL + SELECT CAST(NULL as BIGINT) AS recorded_track_id, + CAST(NULL as BIGINT) AS mix_id, + quick_mixes.id AS quick_mix_id, + quick_mixes.id AS unified_id, + quick_mixes.user_id, + quick_mixes.fully_uploaded, + recordings.created_at AS created_at, + recordings.id AS recording_id + FROM quick_mixes INNER JOIN recordings ON quick_mixes.recording_id = recordings.id AND duration IS NOT NULL AND all_discarded = FALSE; diff --git a/ruby/lib/jam_ruby.rb b/ruby/lib/jam_ruby.rb index 394975a34..98b93a4c1 100755 --- a/ruby/lib/jam_ruby.rb +++ b/ruby/lib/jam_ruby.rb @@ -38,6 +38,7 @@ require "jam_ruby/lib/em_helper" require "jam_ruby/lib/nav" require "jam_ruby/lib/html_sanitize" require "jam_ruby/resque/audiomixer" +require "jam_ruby/resque/quick_mixer" require "jam_ruby/resque/icecast_config_writer" require "jam_ruby/resque/resque_hooks" require "jam_ruby/resque/scheduled/audiomixer_retry" @@ -122,6 +123,8 @@ require "jam_ruby/models/recording_comment" require "jam_ruby/models/recording_liker" require "jam_ruby/models/recorded_track" require "jam_ruby/models/recorded_track_observer" +require "jam_ruby/models/quick_mix" +require "jam_ruby/models/quick_mix_observer" require "jam_ruby/models/share_token" require "jam_ruby/models/mix" require "jam_ruby/models/claimed_recording" @@ -174,6 +177,7 @@ require "jam_ruby/models/chat_message" require "jam_ruby/models/generic_state" require "jam_ruby/models/score_history" require "jam_ruby/models/jam_company" +require "jam_ruby/models/user_sync" require "jam_ruby/models/video_source" require "jam_ruby/models/recorded_video" diff --git a/ruby/lib/jam_ruby/lib/s3_manager.rb b/ruby/lib/jam_ruby/lib/s3_manager.rb index 2ff30aae4..8e31532d1 100644 --- a/ruby/lib/jam_ruby/lib/s3_manager.rb +++ b/ruby/lib/jam_ruby/lib/s3_manager.rb @@ -64,6 +64,10 @@ module JamRuby s3_bucket.objects[upload_filename].multipart_uploads[upload_id].parts[part] end + def exists?(filename) + s3_bucket.objects[filename].exists? + end + def delete(filename) s3_bucket.objects[filename].delete end @@ -76,6 +80,14 @@ module JamRuby s3_bucket.objects.with_prefix(folder).delete_all end + def download(key, filename) + File.open(filename, "wb") do |f| + s3_bucket.objects[key].read do |data| + f.write(data) + end + end + end + private def s3_bucket diff --git a/ruby/lib/jam_ruby/models/mix.rb b/ruby/lib/jam_ruby/models/mix.rb index 0d2282b0c..957e46ba4 100644 --- a/ruby/lib/jam_ruby/models/mix.rb +++ b/ruby/lib/jam_ruby/models/mix.rb @@ -49,8 +49,8 @@ module JamRuby mix.is_skip_mount_uploader = true mix.recording = recording mix.save - mix[:ogg_url] = construct_filename(mix.created_at, recording.id, mix.id, type='ogg') - mix[:mp3_url] = construct_filename(mix.created_at, recording.id, mix.id, type='mp3') + mix[:ogg_url] = construct_filename(recording.created_at, recording.id, mix.id, type='ogg') + mix[:mp3_url] = construct_filename(recording.created_at, recording.id, mix.id, type='mp3') if mix.save mix.enqueue end @@ -68,19 +68,53 @@ module JamRuby end # avoid db validations - Mix.where(:id => self.id).update_all(:started_at => Time.now) + Mix.where(:id => self.id).update_all(:started_at => Time.now, :should_retry => false) true end def can_download?(some_user) - !ClaimedRecording.find_by_user_id_and_recording_id(some_user.id, recording_id).nil? + claimed_recording = ClaimedRecording.find_by_user_id_and_recording_id(some_user.id, recording.id) + + if claimed_recording + !claimed_recording.discarded + else + false + end + end + + def mix_timeout? + Time.now - started_at > 60 * 30 # 30 minutes to mix is more than enough + end + + def state + return 'mixed' if completed + return 'stream-mix' if recording.has_stream_mix + return 'waiting-to-mix' if started_at.nil? + return 'error' if error_count > 0 || mix_timeout? + return 'mixing' + end + + def error + return nil if state != 'error' + return {error_count: error_count, error_reason: error_reason, error_detail: error_detail} if error_count > 0 + return {error_count: 1, error_reason: 'mix-timeout', error_detail: started_at} if mix_timeout? + return {error_count: 1, error_reason: 'unknown', error_detail: 'unknown'} + end + + def too_many_downloads? + (self.download_count < 0 || self.download_count > APP_CONFIG.max_audio_downloads) && !@current_user.admin end def errored(reason, detail) + self.started_at = nil self.error_reason = reason self.error_detail = detail self.error_count = self.error_count + 1 + if self.error_count <= 3 + self.should_retry = true + end + save end @@ -94,6 +128,8 @@ module JamRuby if save Notification.send_recording_master_mix_complete(recording) end + + Recording.where(:id => self.recording.id).update_all(:has_final_mix => true) end # valid for 1 day; because the s3 urls eventually expire @@ -154,7 +190,7 @@ module JamRuby def filename(type='ogg') # construct a path for s3 - Mix.construct_filename(self.created_at, self.recording_id, self.id, type) + Mix.construct_filename(recording.created_at, self.recording_id, self.id, type) end def update_download_count(count=1) diff --git a/ruby/lib/jam_ruby/models/music_session.rb b/ruby/lib/jam_ruby/models/music_session.rb index 35b021d8d..376a104e9 100644 --- a/ruby/lib/jam_ruby/models/music_session.rb +++ b/ruby/lib/jam_ruby/models/music_session.rb @@ -16,6 +16,12 @@ module JamRuby UNSTARTED_INTERVAL_DAYS_PURGE = '28' # days past scheduled start to purge session UNSTARTED_INTERVAL_DAYS_PURGE_RECUR = '28' # days past scheduled start to purge recurddingsession + CREATE_TYPE_START_SCHEDULED = 'start-scheduled' + CREATE_TYPE_SCHEDULE_FUTURE = 'schedule-future' + CREATE_TYPE_RSVP = 'rsvp' + CREATE_TYPE_IMMEDIATE = 'immediately' + CREATE_TYPE_QUICK_START = 'quick-start' + attr_accessor :legal_terms, :language_description, :access_description, :scheduling_info_changed attr_accessor :approved_rsvps, :open_slots, :pending_invitations @@ -293,8 +299,9 @@ module JamRuby query = MusicSession.where("music_sessions.canceled = FALSE") query = query.where("music_sessions.user_id = '#{user.id}'") query = query.where("music_sessions.scheduled_start IS NULL OR #{session_not_started} OR #{session_finished}") + query = query.where("music_sessions.create_type IS NULL OR music_sessions.create_type != '#{CREATE_TYPE_QUICK_START}'") query = query.order("music_sessions.scheduled_start ASC") - + query end @@ -338,6 +345,7 @@ module JamRuby ms.legal_terms = true ms.open_rsvps = options[:open_rsvps] if options[:open_rsvps] ms.creator = user + ms.create_type = options[:create_type] ms.is_unstructured_rsvp = options[:isUnstructuredRsvp] if options[:isUnstructuredRsvp] ms.scheduled_start = parse_scheduled_start(options[:start], options[:timezone]) if options[:start] && options[:timezone] @@ -716,6 +724,7 @@ module JamRuby query = query.offset(offset) query = query.limit(limit) + query = query.where("music_sessions.create_type IS NULL OR music_sessions.create_type != ?", MusicSession::CREATE_TYPE_QUICK_START) query = query.where("music_sessions.genre_id = ?", genre) unless genre.blank? query = query.where('music_sessions.language = ?', lang) unless lang.blank? query = query.where("(description_tsv @@ to_tsquery('jamenglish', ?))", ActiveRecord::Base.connection.quote(keyword) + ':*') unless keyword.blank? diff --git a/ruby/lib/jam_ruby/models/quick_mix.rb b/ruby/lib/jam_ruby/models/quick_mix.rb new file mode 100644 index 000000000..752805fae --- /dev/null +++ b/ruby/lib/jam_ruby/models/quick_mix.rb @@ -0,0 +1,267 @@ +module JamRuby + class QuickMix < ActiveRecord::Base + include S3ManagerMixin + + MAX_MIX_TIME = 7200 # 2 hours + + attr_accessible :ogg_url, :should_retry, as: :admin + attr_accessor :marking_complete, :is_skip_mount_uploader + attr_writer :current_user + + + belongs_to :user, :class_name => "JamRuby::User", :inverse_of => :quick_mixes + belongs_to :recording, :class_name => "JamRuby::Recording", :inverse_of => :quick_mixes, :foreign_key => 'recording_id' + validates :ogg_md5, :presence => true, :if => :upload_starting? + validates :ogg_length, length: {minimum: 1, maximum: 1024 * 1024 * 256 }, if: :upload_starting? # 256 megs max. is this reasonable? surely... + validates :user, presence: true + validate :validate_fully_uploaded + validate :validate_part_complete + validate :validate_too_many_upload_failures + + before_destroy :delete_s3_files + + skip_callback :save, :before, :store_picture!, if: :is_skip_mount_uploader + + def too_many_upload_failures? + upload_failures >= APP_CONFIG.max_track_upload_failures + end + + def upload_starting? + next_part_to_upload_was == 0 && next_part_to_upload == 1 + end + + def validate_too_many_upload_failures + if upload_failures >= APP_CONFIG.max_track_upload_failures + errors.add(:upload_failures, ValidationMessages::UPLOAD_FAILURES_EXCEEDED) + end + end + + def validate_fully_uploaded + if marking_complete && fully_uploaded && fully_uploaded_was + errors.add(:fully_uploaded, ValidationMessages::ALREADY_UPLOADED) + end + end + + def validate_part_complete + + # if we see a transition from is_part_uploading from true to false, we validate + if is_part_uploading_was && !is_part_uploading + if next_part_to_upload_was + 1 != next_part_to_upload + errors.add(:next_part_to_upload, ValidationMessages::INVALID_PART_NUMBER_SPECIFIED) + end + + if file_offset > ogg_length + errors.add(:file_offset, ValidationMessages::FILE_OFFSET_EXCEEDS_LENGTH) + end + elsif next_part_to_upload_was + 1 == next_part_to_upload + # this makes sure we are only catching 'upload_part_complete' transitions, and not upload_start + if next_part_to_upload_was != 0 + # we see that the part number was ticked--but was is_part_upload set to true before this transition? + if !is_part_uploading_was && !is_part_uploading + errors.add(:next_part_to_upload, ValidationMessages::PART_NOT_STARTED) + end + end + end + end + + def sanitize_active_admin + self.user_id = nil if self.user_id == '' + end + + def upload_start(length, md5) + #self.upload_id set by the observer + self.next_part_to_upload = 1 + self.ogg_length = length + self.ogg_md5 = md5 + save + end + + # if for some reason the server thinks the client can't carry on with the upload, + # this resets everything to the initial state + def reset_upload + self.upload_failures = self.upload_failures + 1 + self.part_failures = 0 + self.file_offset = 0 + self.next_part_to_upload = 0 + self.upload_id = nil + self.ogg_md5 = nil + self.ogg_length = 0 + self.fully_uploaded = false + self.is_part_uploading = false + save :validate => false # skip validation because we need this to always work + end + + def upload_next_part(length, md5) + self.marking_complete = true + if next_part_to_upload == 0 + upload_start(length, md5) + end + self.is_part_uploading = true + save + end + + def upload_sign(content_md5) + s3_manager.upload_sign(self[:ogg_url], content_md5, next_part_to_upload, upload_id) + end + + def upload_part_complete(part, offset) + # validated by :validate_part_complete + self.marking_complete = true + self.is_part_uploading = false + self.next_part_to_upload = self.next_part_to_upload + 1 + self.file_offset = offset.to_i + self.part_failures = 0 + save + end + + def upload_complete + # validate from happening twice by :validate_fully_uploaded + self.fully_uploaded = true + self.marking_complete = true + enqueue + save + end + + def increment_part_failures(part_failure_before_error) + self.part_failures = part_failure_before_error + 1 + QuickMix.update_all("part_failures = #{self.part_failures}", "id = '#{self.id}'") + end + + def self.create(recording, user) + raise if recording.nil? + + mix = QuickMix.new + mix.is_skip_mount_uploader = true + mix.recording = recording + mix.user = user + mix.save + mix[:ogg_url] = construct_filename(mix.created_at, recording.id, mix.id, type='ogg') + mix[:mp3_url] = construct_filename(mix.created_at, recording.id, mix.id, type='mp3') + mix.save + mix.is_skip_mount_uploader = false + + mix + end + + def enqueue + begin + Resque.enqueue(QuickMixer, self.id, self.sign_put(3600 * 24, 'mp3')) + rescue Exception => e + # implies redis is down. we don't update started_at by bailing out here + false + end + + # avoid db validations + QuickMix.where(:id => self.id).update_all(:started_at => Time.now, :should_retry => false) + + true + end + + def mix_timeout? + Time.now - started_at > 60 * 30 # 30 minutes to mix is more than enough + end + + def state + return 'mixed' if completed + return 'waiting-to-mix' if started_at.nil? + return 'error' if error_count > 0 || mix_timeout? + return 'mixing' + end + + def error + return nil if state != 'error' + return {error_count: error_count, error_reason: error_reason, error_detail: error_detail} if error_count > 0 + return {error_count: 1, error_reason: 'mix-timeout', error_detail: started_at} if mix_timeout? + return {error_count: 1, error_reason: 'unknown', error_detail: 'unknown'} + end + + def errored(reason, detail) + self.started_at = nil + self.error_reason = reason + self.error_detail = detail + self.error_count = self.error_count + 1 + if self.error_count <= 3 + self.should_retry = true + end + save + end + + def finish(mp3_length, mp3_md5) + self.completed_at = Time.now + self.mp3_length = mp3_length + self.mp3_md5 = mp3_md5 + self.completed = true + save! + Recording.where(:id => self.recording.id).update_all(:has_stream_mix => true) + # only update first_quick_mix_id pointer if this is the 1st quick mix to complete for this recording + Recording.where(:id => self.recording.id).update_all(:first_quick_mix_id => self.id) if recording.first_quick_mix_id.nil? + end + + def s3_url(type='ogg') + if type == 'ogg' + s3_manager.s3_url(self[:ogg_url]) + else + s3_manager.s3_url(self[:mp3_url]) + end + end + + def is_completed + completed + end + + # if the url starts with http, just return it because it's in some other store. Otherwise it's a relative path in s3 and needs be signed + def resolve_url(url_field, mime_type, expiration_time) + self[url_field].start_with?('http') ? self[url_field] : s3_manager.sign_url(self[url_field], {:expires => expiration_time, :response_content_type => mime_type, :secure => false}) + end + + def sign_url(expiration_time = 120, type='ogg') + type ||= 'ogg' + # expire link in 1 minute--the expectation is that a client is immediately following this link + if type == 'ogg' + resolve_url(:ogg_url, 'audio/ogg', expiration_time) + else + resolve_url(:mp3_url, 'audio/mpeg', expiration_time) + end + end + + def sign_put(expiration_time = 3600 * 24, type='ogg') + type ||= 'ogg' + if type == 'ogg' + s3_manager.sign_url(self[:ogg_url], {:expires => expiration_time, :content_type => 'audio/ogg', :secure => false}, :put) + else + s3_manager.sign_url(self[:mp3_url], {:expires => expiration_time, :content_type => 'audio/mpeg', :secure => false}, :put) + end + end + + def self.cleanup_excessive_storage + QuickMix + .joins(:recording) + .includes(:recording) + .where("cleaned = FALSE AND completed = TRUE AND NOW() - completed_at > '7 days'::INTERVAL AND (has_final_mix = TRUE OR (has_stream_mix = TRUE AND quick_mixes.id IN (SELECT qm.id FROM quick_mixes qm WHERE qm.recording_id = recordings.id AND (recordings.first_quick_mix_id IS NULL OR recordings.first_quick_mix_id != qm.id))))").limit(1000).each do |quick_mix| + + quick_mix.delete_s3_files + + QuickMix.where(:id => quick_mix.id).update_all(:cleaned => true) + + if quick_mix.recording.first_quick_mix_id == quick_mix.id + Recording.where(:id => quick_mix.recording.id).update_all(:has_stream_mix => false, :first_quick_mix_id => nil) + end + end + end + + def filename(type='ogg') + # construct a path for s3 + QuickMix.construct_filename(self.created_at, self.recording_id, self.id, type) + end + + def delete_s3_files + s3_manager.delete(filename(type='ogg')) if self[:ogg_url] && s3_manager.exists?(filename(type='ogg')) + s3_manager.delete(filename(type='mp3')) if self[:mp3_url] && s3_manager.exists?(filename(type='mp3')) + end + + def self.construct_filename(created_at, recording_id, id, type='ogg') + raise "unknown ID" unless id + "recordings/#{created_at.strftime('%m-%d-%Y')}/#{recording_id}/stream-mix-#{id}.#{type}" + end + end +end \ No newline at end of file diff --git a/ruby/lib/jam_ruby/models/quick_mix_observer.rb b/ruby/lib/jam_ruby/models/quick_mix_observer.rb new file mode 100644 index 000000000..ccc63891a --- /dev/null +++ b/ruby/lib/jam_ruby/models/quick_mix_observer.rb @@ -0,0 +1,83 @@ +module JamRuby + class QuickMixObserver < ActiveRecord::Observer + + # if you change the this class, tests really should accompany. having alot of logic in observers is really tricky, as we do here + observe JamRuby::QuickMix + + def before_validation(quick_mix) + + # if we see that a part was just uploaded entirely, validate that we can find the part that was just uploaded + if quick_mix.is_part_uploading_was && !quick_mix.is_part_uploading + begin + aws_part = quick_mix.s3_manager.multiple_upload_find_part(quick_mix[:ogg_url], quick_mix.upload_id, quick_mix.next_part_to_upload - 1) + # calling size on a part that does not exist will throw an exception... that's what we want + aws_part.size + rescue SocketError => e + raise # this should cause a 500 error, which is what we want. The client will retry later on 500. + rescue Exception => e + quick_mix.errors.add(:next_part_to_upload, ValidationMessages::PART_NOT_FOUND_IN_AWS) + rescue RuntimeError => e + quick_mix.errors.add(:next_part_to_upload, ValidationMessages::PART_NOT_FOUND_IN_AWS) + rescue + quick_mix.errors.add(:next_part_to_upload, ValidationMessages::PART_NOT_FOUND_IN_AWS) + end + + end + + # if we detect that this just became fully uploaded -- if so, tell s3 to put the parts together + if quick_mix.marking_complete && !quick_mix.fully_uploaded_was && quick_mix.fully_uploaded + + multipart_success = false + begin + quick_mix.s3_manager.multipart_upload_complete(quick_mix[:ogg_url], quick_mix.upload_id) + multipart_success = true + rescue SocketError => e + raise # this should cause a 500 error, which is what we want. The client will retry later. + rescue Exception => e + #quick_mix.reload + quick_mix.reset_upload + quick_mix.errors.add(:upload_id, ValidationMessages::BAD_UPLOAD) + end + end + end + + def after_commit(quick_mix) + + end + + # here we tick upload failure counts, or revert the state of the model, as needed + def after_rollback(quick_mix) + # if fully uploaded, don't increment failures + if quick_mix.fully_uploaded + return + end + + # increment part failures if there is a part currently being uploaded + if quick_mix.is_part_uploading_was + #quick_mix.reload # we don't want anything else that the user set to get applied + quick_mix.increment_part_failures(quick_mix.part_failures_was) + if quick_mix.part_failures >= APP_CONFIG.max_track_part_upload_failures + # save upload id before we abort this bad boy + upload_id = quick_mix.upload_id + begin + quick_mix.s3_manager.multipart_upload_abort(quick_mix[:ogg_url], upload_id) + rescue => e + puts e.inspect + end + quick_mix.reset_upload + if quick_mix.upload_failures >= APP_CONFIG.max_track_upload_failures + # do anything? + end + end + end + + end + + def before_save(quick_mix) + # if we are on the 1st part, then we need to make sure we can save the upload_id + if quick_mix.next_part_to_upload == 1 + quick_mix.upload_id = quick_mix.s3_manager.multipart_upload_start(quick_mix[:ogg_url]) + end + end + end +end \ No newline at end of file diff --git a/ruby/lib/jam_ruby/models/recorded_track.rb b/ruby/lib/jam_ruby/models/recorded_track.rb index 69b6d48f7..ce3299d8b 100644 --- a/ruby/lib/jam_ruby/models/recorded_track.rb +++ b/ruby/lib/jam_ruby/models/recorded_track.rb @@ -61,7 +61,21 @@ module JamRuby end def can_download?(some_user) - !ClaimedRecording.find_by_user_id_and_recording_id(some_user.id, recording.id).nil? + claimed_recording = recording.claimed_recordings.find{|claimed_recording| claimed_recording.user == some_user } + + if claimed_recording + !claimed_recording.discarded + else + false + end + end + + def too_many_upload_failures? + upload_failures >= APP_CONFIG.max_track_upload_failures + end + + def too_many_downloads? + (self.download_count < 0 || self.download_count > APP_CONFIG.max_audio_downloads) && !@current_user.admin end def upload_starting? @@ -126,7 +140,7 @@ module JamRuby recorded_track.file_offset = 0 recorded_track.is_skip_mount_uploader = true recorded_track.save - recorded_track.url = construct_filename(recorded_track.created_at, recording.id, track.client_track_id) + recorded_track.url = construct_filename(recording.created_at, recording.id, track.client_track_id) recorded_track.save recorded_track.is_skip_mount_uploader = false recorded_track @@ -152,7 +166,6 @@ module JamRuby self.file_offset = 0 self.next_part_to_upload = 0 self.upload_id = nil - self.file_offset self.md5 = nil self.length = 0 self.fully_uploaded = false @@ -161,6 +174,7 @@ module JamRuby end def upload_next_part(length, md5) + self.marking_complete = true if next_part_to_upload == 0 upload_start(length, md5) end @@ -174,6 +188,7 @@ module JamRuby def upload_part_complete(part, offset) # validated by :validate_part_complete + self.marking_complete = true self.is_part_uploading = false self.next_part_to_upload = self.next_part_to_upload + 1 self.file_offset = offset.to_i @@ -195,7 +210,7 @@ module JamRuby def filename # construct a path from s3 - RecordedTrack.construct_filename(self.created_at, self.recording.id, self.client_track_id) + RecordedTrack.construct_filename(recording.created_at, self.recording.id, self.client_track_id) end def update_download_count(count=1) diff --git a/ruby/lib/jam_ruby/models/recording.rb b/ruby/lib/jam_ruby/models/recording.rb index 1d9c6fd9c..bbb2fb422 100644 --- a/ruby/lib/jam_ruby/models/recording.rb +++ b/ruby/lib/jam_ruby/models/recording.rb @@ -3,11 +3,16 @@ module JamRuby self.primary_key = 'id' + + @@log = Logging.logger[Recording] + + attr_accessible :owner, :owner_id, :band, :band_id, :recorded_tracks_attributes, :mixes_attributes, :claimed_recordings_attributes, :name, :description, :genre, :is_public, :duration, as: :admin has_many :users, :through => :recorded_tracks, :class_name => "JamRuby::User" has_many :claimed_recordings, :class_name => "JamRuby::ClaimedRecording", :inverse_of => :recording, :foreign_key => 'recording_id', :dependent => :destroy has_many :mixes, :class_name => "JamRuby::Mix", :inverse_of => :recording, :foreign_key => 'recording_id', :dependent => :destroy + has_many :quick_mixes, :class_name => "JamRuby::QuickMix", :foreign_key => :recording_id, :dependent => :destroy has_many :recorded_tracks, :class_name => "JamRuby::RecordedTrack", :foreign_key => :recording_id, :dependent => :destroy has_many :recorded_videos, :class_name => "JamRuby::RecordedVideo", :foreign_key => :recording_id, :dependent => :destroy has_many :comments, :class_name => "JamRuby::RecordingComment", :foreign_key => "recording_id", :dependent => :destroy @@ -44,10 +49,34 @@ module JamRuby self.comments.size end - def has_mix? - self.mixes.length > 0 && self.mixes.first.completed + def high_quality_mix? + has_final_mix end + def has_mix? + # this is used by the UI to know whether it can show a play button. We prefer a real mix, but a stream mix will do + return true if high_quality_mix? + has_stream_mix + end + + # this should be a has-one relationship. until this, this is easiest way to get from recording > mix + def mix + self.mixes[0] if self.mixes.length > 0 + end + + def mix_state + mix.state if mix + end + + def mix_error + mix.error if mix + end + + def stream_mix + quick_mixes.find{|quick_mix| quick_mix.completed && !quick_mix.cleaned } + end + + # this can probably be done more efficiently, but David needs this asap for a video def grouped_tracks tracks = [] @@ -148,7 +177,12 @@ module JamRuby if recording.save GoogleAnalyticsEvent.report_band_recording(recording.band) - + + # make quick mixes *before* the audio/video tracks, because this will give them precedence in list_uploads + music_session.users.uniq.each do |user| + QuickMix.create(recording, user) + end + music_session.connections.each do |connection| connection.tracks.each do |track| recording.recorded_tracks << RecordedTrack.create_from_track(track, recording) @@ -179,6 +213,7 @@ module JamRuby end + # Called when a user wants to "claim" a recording. To do this, the user must have been one of the tracks in the recording. def claim(user, name, description, genre, is_public, upload_to_youtube=false) upload_to_youtube = !!upload_to_youtube # Correct where nil is borking save @@ -337,37 +372,73 @@ module JamRuby Arel::Nodes::As.new('video', Arel.sql('item_type')) ]).reorder("") - # Glue them together: - union = track_arel.union(vid_arel) + # Select fields for quick mix. Note that it must include + # the same number of fields as the track or video in order for + # the union to work: + quick_mix_arel = QuickMix.select([ + :id, + :recording_id, + :user_id, + :ogg_url, + :fully_uploaded, + :upload_failures, + Arel::Nodes::As.new('', Arel.sql('quick_mix_track_id')), + Arel::Nodes::As.new('stream_mix', Arel.sql('item_type')) + ]).reorder("") - # Create a table alias from the union so we can get back to arel: - utable = RecordedTrack.arel_table.create_table_alias(union, :recorded_items) + # Glue them together: + union = track_arel.union(vid_arel) + + utable = Arel::Nodes::TableAlias.new(union, :recorded_items) arel = track_arel.from(utable) + arel = arel.except(:select) + + # Remove the implicit select created by .from. It + # contains an ambigious "id" field: + arel = arel.except(:select) arel = arel.select([ - :id, - :recording_id, - :user_id, - :url, - :fully_uploaded, - :upload_failures, - :client_track_id, - :item_type - ]) + "recorded_items.id", + :recording_id, + :user_id, + :url, + :fully_uploaded, + :upload_failures, + :client_track_id, + :item_type + ]) + + # And repeat: + union_all = arel.union(quick_mix_arel) + utable_all = Arel::Nodes::TableAlias.new(union_all, :recorded_items_all) + arel = arel.from(utable_all) + + arel = arel.except(:select) + arel = arel.select([ + "recorded_items_all.id", + :recording_id, + :user_id, + :url, + :fully_uploaded, + :upload_failures, + :client_track_id, + :item_type + ]) + # Further joining and criteria for the unioned object: - arel = arel.joins("INNER JOIN (SELECT id as rec_id, all_discarded, duration FROM recordings) recs ON rec_id=recorded_items.recording_id") \ - .where('recorded_items.user_id' => user.id) \ - .where('recorded_items.fully_uploaded = ?', false) \ - .where('recorded_items.id > ?', since) \ + arel = arel.joins("INNER JOIN recordings ON recordings.id=recorded_items_all.recording_id") \ + .where('recorded_items_all.user_id' => user.id) \ + .where('recorded_items_all.fully_uploaded = ?', false) \ + .where('recorded_items_all.id > ?', since) \ .where("upload_failures <= #{APP_CONFIG.max_track_upload_failures}") \ .where("duration IS NOT NULL") \ .where('all_discarded = false') \ - .order('recorded_items.id') \ + .order('recorded_items_all.id') \ .limit(limit) # Load into array: arel.each do |recorded_item| - if(recorded_item.item_type=='video') + if recorded_item.item_type=='video' # A video: uploads << ({ :type => "recorded_video", @@ -375,7 +446,7 @@ module JamRuby :recording_id => recorded_item.recording_id, :next => recorded_item.id }) - else + elsif recorded_item.item_type == 'track' # A track: uploads << ({ :type => "recorded_track", @@ -383,7 +454,16 @@ module JamRuby :recording_id => recorded_item.recording_id, :next => recorded_item.id }) + elsif recorded_item.item_type == 'stream_mix' + uploads << ({ + :type => "stream_mix", + :recording_id => recorded_item.recording_id, + :next => recorded_item.id + }) + else + end + end next_value = uploads.length > 0 ? uploads[-1][:next].to_s : nil @@ -397,18 +477,22 @@ module JamRuby } end + def preconditions_for_mix? + recorded_tracks.each do |recorded_track| + return false unless recorded_track.fully_uploaded + end + true + end + # Check to see if all files have been uploaded. If so, kick off a mix. def upload_complete # Don't allow multiple mixes for now. - raise JamRuby::JamArgumentError unless self.mixes.length == 0 + return if self.mixes.length > 0 # FIXME: There's a possible race condition here. If two users complete # uploads at the same time, we'll schedule 2 mixes. - recorded_tracks.each do |recorded_track| - return unless recorded_track.fully_uploaded - end - self.mixes << Mix.schedule(self) + self.mixes << Mix.schedule(self) if preconditions_for_mix? save end @@ -423,7 +507,14 @@ module JamRuby claimed_recordings.first end - private + # returns a ClaimedRecording that the user did not discard + def claim_for_user(user) + return nil unless user + claim = claimed_recordings.find{|claimed_recording| claimed_recording.user == user } + claim unless claim && claim.discarded + end + + private def self.validate_user_is_band_member(user, band) unless band.users.exists? user raise PermissionError, ValidationMessages::USER_NOT_BAND_MEMBER_VALIDATION_ERROR diff --git a/ruby/lib/jam_ruby/models/search.rb b/ruby/lib/jam_ruby/models/search.rb index 51e2db56c..c83730172 100644 --- a/ruby/lib/jam_ruby/models/search.rb +++ b/ruby/lib/jam_ruby/models/search.rb @@ -276,6 +276,7 @@ module JamRuby rel, page = self.relation_pagination(rel, params) rel = rel.includes([:instruments, :followings, :friends]) + # XXX: DOES THIS MEAN ALL MATCHING USERS ARE RETURNED? objs = rel.all srch = Search.new diff --git a/ruby/lib/jam_ruby/models/user.rb b/ruby/lib/jam_ruby/models/user.rb index b33a1d2c0..5216063db 100644 --- a/ruby/lib/jam_ruby/models/user.rb +++ b/ruby/lib/jam_ruby/models/user.rb @@ -104,6 +104,7 @@ module JamRuby # saved tracks has_many :recorded_tracks, :foreign_key => "user_id", :class_name => "JamRuby::RecordedTrack", :inverse_of => :user has_many :recorded_videos, :foreign_key => "user_id", :class_name => "JamRuby::RecordedVideo", :inverse_of => :user + has_many :quick_mixes, :foreign_key => "user_id", :class_name => "JamRuby::QuickMix", :inverse_of => :user # invited users has_many :invited_users, :foreign_key => "sender_id", :class_name => "JamRuby::InvitedUser" @@ -324,7 +325,7 @@ module JamRuby read_attribute(:music_session_id) end - # ===== ARTIFICIAL ATTRIBUTES CREATED BY ActiveMusicSession.ams_users, MusicSession.sms_uses + # ===== ARTIFICIAL ATTRIBUTES CREATED BY ActiveMusicSession.ams_users, MusicSession.sms_users def full_score return nil unless has_attribute?(:full_score) a = read_attribute(:full_score) @@ -344,6 +345,14 @@ module JamRuby end # ====== END ARTIFICAL ATTRIBUTES + def score_info(destination_user) + if self.last_jam_locidispid && destination_user.last_jam_locidispid + self.connection.execute("select score from current_network_scores where alocidispid = #{self.last_jam_locidispid} and blocidispid = #{destination_user.last_jam_locidispid}").check + else + nil + end + end + # mods comes back as text; so give ourselves a parsed version def mods_json @mods_json ||= mods ? JSON.parse(mods, symbolize_names: true) : {} diff --git a/ruby/lib/jam_ruby/models/user_sync.rb b/ruby/lib/jam_ruby/models/user_sync.rb new file mode 100644 index 000000000..17925bcdf --- /dev/null +++ b/ruby/lib/jam_ruby/models/user_sync.rb @@ -0,0 +1,46 @@ +module JamRuby + class UserSync < ActiveRecord::Base + + belongs_to :recorded_track + belongs_to :mix + belongs_to :quick_mix + + def self.show(id, user_id) + self.index({user_id: user_id, id: id, limit: 1, offset: 0})[:query].first + end + + def self.index(params) + user_id = params[:user_id] + limit = params[:limit].to_i + limit = limit == 0 ? 20 : limit + offset = params[:offset].to_i + id = params[:id] + recording_id = params[:recording_id] + + page = (offset / limit) + 1 # one-based madness + + raise 'no user id specified' if user_id.blank? + + query = UserSync.includes(recorded_track: [{recording: [:owner, {claimed_recordings: [:share_token]}, {recorded_tracks: [:user]}, {comments:[:user]}, :likes, :plays, :mixes]}, user: [], instrument:[]], mix: [], quick_mix:[]).where(user_id: user_id).paginate(:page => page, :per_page => limit).order('created_at DESC, unified_id') + + + # allow selection of single user_sync, by ID + unless id.blank? + query = query.where(unified_id: id) + end + + unless recording_id.blank? + query = query.where(recording_id: recording_id) + end + + if query.length == 0 + { query:query, next: nil} + elsif query.length < limit + { query:query, next: nil} + else + { query:query, next: offset + limit} + end + end + end +end + diff --git a/ruby/lib/jam_ruby/resque/audiomixer.rb b/ruby/lib/jam_ruby/resque/audiomixer.rb index 37fb2496e..66973b12a 100644 --- a/ruby/lib/jam_ruby/resque/audiomixer.rb +++ b/ruby/lib/jam_ruby/resque/audiomixer.rb @@ -30,7 +30,7 @@ module JamRuby end def self.queue_jobs_needing_retry - Mix.find_each(:conditions => 'should_retry = TRUE or started_at is NULL', :batch_size => 100) do |mix| + Mix.find_each(:conditions => "completed = FALSE AND (should_retry = TRUE OR (started_at IS NOT NULL AND NOW() - started_at > '1 hour'::INTERVAL))", :batch_size => 100) do |mix| mix.enqueue end end @@ -130,6 +130,8 @@ module JamRuby # update manifest so that audiomixer writes here @manifest[:output][:filename] = @output_ogg_filename + # this is not used by audiomixer today; since today the Ruby code handles this + @manifest[:output][:filename_mp3] = @output_mp3_filename @@log.debug("output ogg file: #{@output_ogg_filename}, output mp3 file: #{@output_mp3_filename}") end @@ -204,6 +206,18 @@ module JamRuby end + def cleanup_files() + File.delete(@output_ogg_filename) if File.exists(@output_ogg_filename) + File.delete(@output_mp3_filename) if File.exists(@output_mp3_filename) + File.delete(@manifest_file) if File.exists(@manifest_file) + File.delete(@error_out_filename) if File.exists(@error_out_filename) + + @manifest[:files].each do |file| + filename = file[:filename] + File.delete(filename) if File.exists(filename) + end + end + def post_success(mix) ogg_length = File.size(@output_ogg_filename) @@ -218,6 +232,7 @@ module JamRuby mix.finish(ogg_length, ogg_md5.to_s, mp3_length, mp3_md5.to_s) end + def post_error(mix, e) begin @@ -228,8 +243,8 @@ module JamRuby end mix.errored(error_reason, error_detail) - rescue - @@log.error "unable to post back to the database the error" + rescue Exception => e + @@log.error "unable to post back to the database the error #{e}" end end @@ -260,9 +275,12 @@ module JamRuby execute(@manifest_file) postback - + post_success(mix) - + + # only cleanup files if we manage to get this far + cleanup_files + @@log.info("audiomixer job successful. mix_id #{mix_id}") rescue Exception => e diff --git a/ruby/lib/jam_ruby/resque/quick_mixer.rb b/ruby/lib/jam_ruby/resque/quick_mixer.rb new file mode 100644 index 000000000..f9b9d80bb --- /dev/null +++ b/ruby/lib/jam_ruby/resque/quick_mixer.rb @@ -0,0 +1,155 @@ +require 'json' +require 'resque' +require 'resque-retry' +require 'net/http' +require 'digest/md5' + +module JamRuby + + # executes a mix of tracks, creating a final output mix + class QuickMixer + + @queue = :quick_mixer + + @@log = Logging.logger[QuickMixer] + + attr_accessor :quick_mix_id, :quick_mix, :output_filename, :error_out_filename, + :postback_mp3_url, :error_reason, :error_detail + + def self.perform(quick_mix_id, postback_mp3_url) + + JamWebEventMachine.run_wait_stop do + audiomixer = QuickMixer.new + audiomixer.postback_mp3_url = postback_mp3_url + audiomixer.quick_mix_id = quick_mix_id + audiomixer.run + end + + end + + def self.find_jobs_needing_retry &blk + QuickMix.find_each(:conditions => "completed = FALSE AND (should_retry = TRUE OR (started_at IS NOT NULL AND NOW() - started_at > '1 hour'::INTERVAL))", :batch_size => 100) do |mix| + blk.call(mix) + end + end + + def self.queue_jobs_needing_retry + find_jobs_needing_retry do |mix| + mix.enqueue + end + end + + def initialize + @s3_manager = S3Manager.new(APP_CONFIG.aws_bucket, APP_CONFIG.aws_access_key_id, APP_CONFIG.aws_secret_access_key) + end + + def run + @@log.info("quickmixer job starting. quick_mix_id #{quick_mix_id}") + + @quick_mix = QuickMix.find(quick_mix_id) + + begin + # bailout check + if @quick_mix.completed + @@log.debug("quick mix is already completed. bailing") + return + end + + fetch_audio_files + + create_mp3(@input_ogg_filename, @output_mp3_filename) + + postback + + post_success(@quick_mix) + + cleanup_files + + @@log.info("audiomixer job successful. mix_id #{quick_mix_id}") + + rescue Exception => e + puts "EEOUOU #{e}" + post_error(@quick_mix, e) + raise + end + end + + + def postback + + @@log.debug("posting mp3 mix to #{@postback_mp3_url}") + + uri = URI.parse(@postback_mp3_url) + http = Net::HTTP.new(uri.host, uri.port) + request = Net::HTTP::Put.new(uri.request_uri) + + response = nil + File.open(@output_mp3_filename,"r") do |f| + request.body_stream=f + request["Content-Type"] = "audio/mpeg" + request.add_field('Content-Length', File.size(@output_mp3_filename)) + response = http.request(request) + end + + response_code = response.code.to_i + unless response_code >= 200 && response_code <= 299 + @error_reason = "postback-mp3-mix-to-s3" + raise "unable to put to url: #{@postback_mp3_url}, status: #{response.code}, body: #{response.body}" + end + + end + + def post_success(mix) + + mp3_length = File.size(@output_mp3_filename) + mp3_md5 = Digest::MD5.new + File.open(@output_mp3_filename, 'rb').each {|line| mp3_md5.update(line)} + + mix.finish(mp3_length, mp3_md5.to_s) + end + + def post_error(mix, e) + begin + + # if error_reason is null, assume this is an unhandled error + unless @error_reason + @error_reason = "unhandled-job-exception" + @error_detail = e.to_s + end + mix.errored(error_reason, error_detail) + + rescue Exception => e + @@log.error "unable to post back to the database the error #{e}" + end + end + + def cleanup_files() + File.delete(@input_ogg_filename) if File.exists(@input_ogg_filename) + File.delete(@output_mp3_filename) if File.exists(@output_mp3_filename) + end + + + def fetch_audio_files + @input_ogg_filename = Dir::Tmpname.make_tmpname( ["#{Dir.tmpdir}/quick_mixer_#{@quick_mix.id}}", '.ogg'], nil) + @output_mp3_filename = Dir::Tmpname.make_tmpname( ["#{Dir.tmpdir}/quick_mixer_#{@quick_mix.id}}", '.mp3'], nil) + @s3_manager.download(@quick_mix[:ogg_url], @input_ogg_filename) + end + + private + + def create_mp3(input_ogg_filename, output_mp3_filename) + ffmpeg_cmd = "#{APP_CONFIG.ffmpeg_path} -i \"#{input_ogg_filename}\" -ab 128k -metadata JamRecordingId=#{@quick_mix.recording_id} -metadata JamQuickMixId=#{@quick_mix_id} -metadata JamType=QuickMix \"#{output_mp3_filename}\"" + + system(ffmpeg_cmd) + + unless $? == 0 + @error_reason = 'ffmpeg-failed' + @error_detail = $?.to_s + error_msg = "ffmpeg failed status=#{$?} error_reason=#{@error_reason} error_detail=#{@error_detail}" + @@log.info(error_msg) + raise error_msg + end + + end + end +end \ No newline at end of file diff --git a/ruby/lib/jam_ruby/resque/scheduled/audiomixer_retry.rb b/ruby/lib/jam_ruby/resque/scheduled/audiomixer_retry.rb index c314c2f48..6c2d8fe90 100644 --- a/ruby/lib/jam_ruby/resque/scheduled/audiomixer_retry.rb +++ b/ruby/lib/jam_ruby/resque/scheduled/audiomixer_retry.rb @@ -6,7 +6,7 @@ require 'digest/md5' module JamRuby - # periodically scheduled to find jobs that need retrying + # periodically scheduled to find jobs that need retrying, and cleanup activities class AudioMixerRetry extend Resque::Plugins::LonelyJob @@ -21,6 +21,8 @@ module JamRuby def self.perform AudioMixer.queue_jobs_needing_retry + QuickMixer.queue_jobs_needing_retry + QuickMix.cleanup_excessive_storage end end diff --git a/ruby/spec/factories.rb b/ruby/spec/factories.rb index 26a4d5389..b91b9dee1 100644 --- a/ruby/spec/factories.rb +++ b/ruby/spec/factories.rb @@ -308,6 +308,30 @@ FactoryGirl.define do } end + factory :quick_mix, :class => JamRuby::QuickMix do + ignore do + autowire true + end + started_at nil + completed_at nil + ogg_md5 nil + ogg_length 0 + ogg_url nil + mp3_md5 nil + mp3_length 0 + mp3_url nil + completed false + + before(:create) {|mix, evaluator| + if evaluator.autowire + user = FactoryGirl.create(:user) + mix.user = user + mix.recording = FactoryGirl.create(:recording_with_track, owner: user) + mix.recording.claimed_recordings << FactoryGirl.create(:claimed_recording, user: user, recording: mix.recording) + end + } + end + factory :invited_user, :class => JamRuby::InvitedUser do sequence(:email) { |n| "user#{n}@someservice.com" } autofriend false diff --git a/ruby/spec/jam_ruby/models/quick_mix_spec.rb b/ruby/spec/jam_ruby/models/quick_mix_spec.rb new file mode 100644 index 000000000..b8d16d3ef --- /dev/null +++ b/ruby/spec/jam_ruby/models/quick_mix_spec.rb @@ -0,0 +1,212 @@ +require 'spec_helper' +require 'rest-client' + +describe QuickMix do + + include UsesTempFiles + + before do + @user = FactoryGirl.create(:user) + @connection = FactoryGirl.create(:connection, :user => @user) + @instrument = FactoryGirl.create(:instrument, :description => 'a great instrument') + @music_session = FactoryGirl.create(:active_music_session, :creator => @user, :musician_access => true) + @track = FactoryGirl.create(:track, :connection => @connection, :instrument => @instrument) + @recording = FactoryGirl.create(:recording, :music_session => @music_session, :owner => @user) + end + + it "should copy from a regular track properly" do + @quick_mix = QuickMix.create(@recording, @user) + @quick_mix.user.id.should == @track.connection.user.id + @quick_mix.next_part_to_upload.should == 0 + @quick_mix.fully_uploaded.should == false + end + + it "should update the next part to upload properly" do + @quick_mix = QuickMix.create(@recording, @user) + @quick_mix.upload_part_complete(1, 1000) + @quick_mix.errors.any?.should be_true + @quick_mix.errors[:ogg_length][0].should == "is too short (minimum is 1 characters)" + @quick_mix.errors[:ogg_md5][0].should == "can't be blank" + end + + + it "gets a url for the track" do + @quick_mix = QuickMix.create(@recording, @user) + @quick_mix.errors.any?.should be_false + @quick_mix[:ogg_url].should == "recordings/#{@recording.created_at.strftime('%m-%d-%Y')}/#{@recording.id}/stream-mix-#{@quick_mix.id}.ogg" + @quick_mix[:mp3_url].should == "recordings/#{@recording.created_at.strftime('%m-%d-%Y')}/#{@recording.id}/stream-mix-#{@quick_mix.id}.mp3" + end + + it "signs url" do + stub_const("APP_CONFIG", app_config) + @quick_mix = QuickMix.create(@recording, @user) + @quick_mix.sign_url.should_not be_nil + end + + describe "aws-based operations", :aws => true do + + def put_file_to_aws(signed_data, contents) + + begin + RestClient.put( signed_data[:url], + contents, + { + :'Content-Type' => 'audio/ogg', + :Date => signed_data[:datetime], + :'Content-MD5' => signed_data[:md5], + :Authorization => signed_data[:authorization] + }) + rescue => e + puts e.response + raise e + end + + end + # create a test file + upload_file='some_file.ogg' + in_directory_with_file(upload_file) + + upload_file_contents="ogg binary stuff in here" + md5 = Base64.encode64(Digest::MD5.digest(upload_file_contents)).chomp + test_config = app_config + s3_manager = S3Manager.new(test_config.aws_bucket, test_config.aws_access_key_id, test_config.aws_secret_access_key) + + + before do + stub_const("APP_CONFIG", app_config) + # this block of code will fully upload a sample file to s3 + content_for_file(upload_file_contents) + s3_manager.delete_folder('recordings') # keep the bucket clean to save cost, and make it easier if post-mortuem debugging + + + end + + it "cant mark a part complete without having started it" do + @quick_mix = QuickMix.create(@recording, @user) + @quick_mix.upload_start(1000, "abc") + @quick_mix.upload_part_complete(1, 1000) + @quick_mix.errors.any?.should be_true + @quick_mix.errors[:next_part_to_upload][0].should == ValidationMessages::PART_NOT_STARTED + end + + it "no parts" do + @quick_mix = QuickMix.create(@recording, @user) + @quick_mix.upload_start(1000, "abc") + @quick_mix.upload_next_part(1000, "abc") + @quick_mix.errors.any?.should be_false + @quick_mix.upload_part_complete(1, 1000) + @quick_mix.errors.any?.should be_true + @quick_mix.errors[:next_part_to_upload][0].should == ValidationMessages::PART_NOT_FOUND_IN_AWS + end + + it "enough part failures reset the upload" do + @quick_mix = QuickMix.create(@recording, @user) + @quick_mix.upload_start(File.size(upload_file), md5) + @quick_mix.upload_next_part(File.size(upload_file), md5) + @quick_mix.errors.any?.should be_false + APP_CONFIG.max_track_part_upload_failures.times do |i| + @quick_mix.upload_part_complete(@quick_mix.next_part_to_upload, File.size(upload_file)) + @quick_mix.errors[:next_part_to_upload] == [ValidationMessages::PART_NOT_FOUND_IN_AWS] + part_failure_rollover = i == APP_CONFIG.max_track_part_upload_failures - 1 + expected_is_part_uploading = !part_failure_rollover + expected_part_failures = part_failure_rollover ? 0 : i + 1 + @quick_mix.reload + @quick_mix.is_part_uploading.should == expected_is_part_uploading + @quick_mix.part_failures.should == expected_part_failures + end + + @quick_mix.reload + @quick_mix.upload_failures.should == 1 + @quick_mix.file_offset.should == 0 + @quick_mix.next_part_to_upload.should == 0 + @quick_mix.upload_id.should be_nil + @quick_mix.ogg_md5.should be_nil + @quick_mix.ogg_length.should == 0 + end + + it "enough upload failures fails the upload forever" do + APP_CONFIG.stub(:max_track_upload_failures).and_return(1) + APP_CONFIG.stub(:max_track_part_upload_failures).and_return(2) + @quick_mix = QuickMix.create(@recording, @user) + APP_CONFIG.max_track_upload_failures.times do |j| + @quick_mix.upload_start(File.size(upload_file), md5) + @quick_mix.upload_next_part(File.size(upload_file), md5) + @quick_mix.errors.any?.should be_false + APP_CONFIG.max_track_part_upload_failures.times do |i| + @quick_mix.upload_part_complete(@quick_mix.next_part_to_upload, File.size(upload_file)) + @quick_mix.errors[:next_part_to_upload] == [ValidationMessages::PART_NOT_FOUND_IN_AWS] + part_failure_rollover = i == APP_CONFIG.max_track_part_upload_failures - 1 + expected_is_part_uploading = part_failure_rollover ? false : true + expected_part_failures = part_failure_rollover ? 0 : i + 1 + @quick_mix.reload + @quick_mix.is_part_uploading.should == expected_is_part_uploading + @quick_mix.part_failures.should == expected_part_failures + end + @quick_mix.upload_failures.should == j + 1 + end + + @quick_mix.reload + @quick_mix.upload_failures.should == APP_CONFIG.max_track_upload_failures + @quick_mix.file_offset.should == 0 + @quick_mix.next_part_to_upload.should == 0 + @quick_mix.upload_id.should be_nil + @quick_mix.ogg_md5.should be_nil + @quick_mix.ogg_length.should == 0 + + # try to poke it and get the right kind of error back + @quick_mix.upload_next_part(File.size(upload_file), md5) + @quick_mix.errors[:upload_failures] = [ValidationMessages::UPLOAD_FAILURES_EXCEEDED] + end + + describe "correctly uploaded a file" do + + before do + @quick_mix = QuickMix.create(@recording, @user) + @quick_mix.upload_start(File.size(upload_file), md5) + @quick_mix.upload_next_part(File.size(upload_file), md5) + signed_data = @quick_mix.upload_sign(md5) + @response = put_file_to_aws(signed_data, upload_file_contents) + @quick_mix.upload_part_complete(@quick_mix.next_part_to_upload, File.size(upload_file)) + @quick_mix.errors.any?.should be_false + @quick_mix.upload_complete + @quick_mix.marking_complete = false # this is a side effect of using the same model throughout this process; controllers wouldn't see this + @quick_mix.finish(File.size(upload_file), md5) + @quick_mix.errors.any?.should be_false + + # let's verify that .finish sets everything it should + @quick_mix.mp3_length.should == File.size(upload_file) + @quick_mix.mp3_md5.should == md5 + @quick_mix.completed.should be_true + @quick_mix.recording.reload + @quick_mix.recording.first_quick_mix_id.should == @quick_mix.id + end + + it "can download an updated file" do + @response = RestClient.get @quick_mix.sign_url + @response.body.should == upload_file_contents + end + + it "can't mark completely uploaded twice" do + @quick_mix.upload_complete + @quick_mix.errors.any?.should be_true + @quick_mix.errors[:fully_uploaded][0].should == "already set" + @quick_mix.part_failures.should == 0 + end + + it "can't ask for a next part if fully uploaded" do + @quick_mix.upload_next_part(File.size(upload_file), md5) + @quick_mix.errors.any?.should be_true + @quick_mix.errors[:fully_uploaded][0].should == "already set" + @quick_mix.part_failures.should == 0 + end + + it "can't ask for mark part complete if fully uploaded" do + @quick_mix.upload_part_complete(1, 1000) + @quick_mix.errors.any?.should be_true + @quick_mix.errors[:fully_uploaded][0].should == "already set" + @quick_mix.part_failures.should == 0 + end + end + end +end + diff --git a/ruby/spec/jam_ruby/models/recorded_track_spec.rb b/ruby/spec/jam_ruby/models/recorded_track_spec.rb index fe9f4c2e9..13e7ce746 100644 --- a/ruby/spec/jam_ruby/models/recorded_track_spec.rb +++ b/ruby/spec/jam_ruby/models/recorded_track_spec.rb @@ -192,6 +192,7 @@ describe RecordedTrack do @recorded_track.errors.any?.should be_false @recorded_track.upload_complete @recorded_track.errors.any?.should be_false + @recorded_track.marking_complete = false end it "can download an updated file" do diff --git a/ruby/spec/jam_ruby/models/recording_spec.rb b/ruby/spec/jam_ruby/models/recording_spec.rb index 0989e777c..c093d5950 100644 --- a/ruby/spec/jam_ruby/models/recording_spec.rb +++ b/ruby/spec/jam_ruby/models/recording_spec.rb @@ -2,6 +2,11 @@ require 'spec_helper' describe Recording do + include UsesTempFiles + + + let(:s3_manager) { S3Manager.new(app_config.aws_bucket, app_config.aws_access_key_id, app_config.aws_secret_access_key) } + before do @user = FactoryGirl.create(:user) @instrument = FactoryGirl.create(:instrument, :description => 'a great instrument') @@ -9,7 +14,187 @@ describe Recording do @connection = FactoryGirl.create(:connection, :user => @user, :music_session => @music_session) @track = FactoryGirl.create(:track, :connection => @connection, :instrument => @instrument) end - + + describe "cleanup_excessive_storage" do + + sample_audio='sample.file' + in_directory_with_file(sample_audio) + + let(:user2) {FactoryGirl.create(:user)} + let(:quick_mix) { FactoryGirl.create(:quick_mix) } + let(:quick_mix2) { + recording.recorded_tracks << FactoryGirl.create(:recorded_track, recording: recording, user: user2) + recording.claimed_recordings << FactoryGirl.create(:claimed_recording, user: user2, recording: recording) + recording.save! + FactoryGirl.create(:quick_mix, autowire: false, recording:recording, user: user2) } + let(:recording) { quick_mix.recording } + + before(:each) do + content_for_file("ogg goodness") + end + + it "cleans up nothing without failing" do + QuickMix.cleanup_excessive_storage + end + + it "leaves untouched no completed mixes" do + + + recording.has_final_mix.should be_false + recording.has_stream_mix.should be_false + quick_mix.cleaned.should be_false + + QuickMix.cleanup_excessive_storage + recording.reload + quick_mix.reload + + recording.has_final_mix.should be_false + recording.has_stream_mix.should be_false + quick_mix.cleaned.should be_false + + end + + it "leaves untouched a completed quick mix if it's the only one and old enough" do + s3_manager.upload(quick_mix.filename('ogg'), sample_audio) + s3_manager.upload(quick_mix.filename('mp3'), sample_audio) + quick_mix.completed = true + quick_mix[:ogg_url] = quick_mix.filename('ogg') + quick_mix[:mp3_url] = quick_mix.filename('mp3') + quick_mix.completed_at = 10.days.ago + quick_mix.save! + recording.has_stream_mix = true + recording.first_quick_mix_id = quick_mix.id + recording.save! + quick_mix.recording_id.should == recording.id + + QuickMix.cleanup_excessive_storage + recording.reload + quick_mix.reload + + recording.has_final_mix.should be_false + recording.has_stream_mix.should be_true + quick_mix.cleaned.should be_false + quick_mix[:ogg_url].should_not be_nil + quick_mix[:mp3_url].should_not be_nil + end + + it "cleans up completed quick mix if their is a final mix" do + s3_manager.upload(quick_mix.filename('ogg'), sample_audio) + s3_manager.upload(quick_mix.filename('mp3'), sample_audio) + quick_mix.completed = true + quick_mix[:ogg_url] = quick_mix.filename('ogg') + quick_mix[:mp3_url] = quick_mix.filename('mp3') + quick_mix.completed_at = 10.days.ago + quick_mix.save! + recording.has_final_mix = true + recording.has_stream_mix = true + recording.first_quick_mix_id = quick_mix.id + recording.save! + quick_mix.recording_id.should == recording.id + + QuickMix.cleanup_excessive_storage + recording.reload + quick_mix.reload + + recording.has_final_mix.should be_true + recording.has_stream_mix.should be_false + recording.first_quick_mix_id.should be_nil + quick_mix.cleaned.should be_true + quick_mix[:ogg_url].should_not be_nil + quick_mix[:mp3_url].should_not be_nil + s3_manager.exists?(quick_mix.filename('ogg')).should be_false + s3_manager.exists?(quick_mix.filename('mp3')).should be_false + + end + + it "cleans up one of two quick mixes" do + # quick_mix2 should get cleaned up, but quick_mix1 should be left alone because we need at least one if has_final_mix = false + quick_mix2.touch + s3_manager.upload(quick_mix.filename('ogg'), sample_audio) + s3_manager.upload(quick_mix.filename('mp3'), sample_audio) + s3_manager.upload(quick_mix2.filename('ogg'), sample_audio) + s3_manager.upload(quick_mix2.filename('mp3'), sample_audio) + quick_mix.completed = true + quick_mix[:ogg_url] = quick_mix.filename('ogg') + quick_mix[:mp3_url] = quick_mix.filename('mp3') + quick_mix.completed_at = 10.days.ago + quick_mix.save! + quick_mix2.completed = true + quick_mix2[:ogg_url] = quick_mix.filename('ogg') + quick_mix2[:mp3_url] = quick_mix.filename('mp3') + quick_mix2.completed_at = 10.days.ago + quick_mix2.save! + recording.has_stream_mix = true + recording.first_quick_mix_id = quick_mix.id + recording.save! + quick_mix.recording_id.should == recording.id + + QuickMix.cleanup_excessive_storage + recording.reload + quick_mix.reload + quick_mix2.reload + + recording.has_final_mix.should be_false + recording.has_stream_mix.should be_true + recording.first_quick_mix_id.should_not be_nil + quick_mix.cleaned.should be_false + quick_mix[:ogg_url].should_not be_nil + quick_mix[:mp3_url].should_not be_nil + s3_manager.exists?(quick_mix.filename('ogg')).should be_true + s3_manager.exists?(quick_mix.filename('mp3')).should be_true + quick_mix2.cleaned.should be_true + quick_mix2[:ogg_url].should_not be_nil + quick_mix2[:mp3_url].should_not be_nil + s3_manager.exists?(quick_mix2.filename('ogg')).should be_false + s3_manager.exists?(quick_mix2.filename('mp3')).should be_false + + end + + it "cleans up all quick mixes if there is a final mix" do + # quick_mix2 should get cleaned up, but quick_mix1 should be left alone because we need at least one if has_final_mix = false + quick_mix2.touch + s3_manager.upload(quick_mix.filename('ogg'), sample_audio) + s3_manager.upload(quick_mix.filename('mp3'), sample_audio) + s3_manager.upload(quick_mix2.filename('ogg'), sample_audio) + s3_manager.upload(quick_mix2.filename('mp3'), sample_audio) + quick_mix.completed = true + quick_mix[:ogg_url] = quick_mix.filename('ogg') + quick_mix[:mp3_url] = quick_mix.filename('mp3') + quick_mix.completed_at = 10.days.ago + quick_mix.save! + quick_mix2.completed = true + quick_mix2[:ogg_url] = quick_mix.filename('ogg') + quick_mix2[:mp3_url] = quick_mix.filename('mp3') + quick_mix2.completed_at = 10.days.ago + quick_mix2.save! + recording.has_final_mix = true + recording.has_stream_mix = true + recording.first_quick_mix_id = quick_mix.id + recording.save! + quick_mix.recording_id.should == recording.id + + QuickMix.cleanup_excessive_storage + recording.reload + quick_mix.reload + quick_mix2.reload + + recording.has_final_mix.should be_true + recording.has_stream_mix.should be_false + recording.first_quick_mix_id.should be_nil + quick_mix.cleaned.should be_true + quick_mix[:ogg_url].should_not be_nil + quick_mix[:mp3_url].should_not be_nil + s3_manager.exists?(quick_mix.filename('ogg')).should be_false + s3_manager.exists?(quick_mix.filename('mp3')).should be_false + quick_mix2.cleaned.should be_true + quick_mix2[:ogg_url].should_not be_nil + quick_mix2[:mp3_url].should_not be_nil + s3_manager.exists?(quick_mix2.filename('ogg')).should be_false + s3_manager.exists?(quick_mix2.filename('mp3')).should be_false + + end + end + it "should allow finding of recorded tracks" do user2 = FactoryGirl.create(:user) connection2 = FactoryGirl.create(:connection, :user => user2, :music_session => @music_session) @@ -241,7 +426,7 @@ describe Recording do @genre = FactoryGirl.create(:genre) @recording.claim(@user, "Recording", "Recording Description", @genre, true) uploads = Recording.list_uploads(@user) - uploads["uploads"].length.should == 1 + uploads["uploads"].length.should == 2 # recorded_track and stream_mix Recording.list_uploads(@user, 10, uploads["next"])["uploads"].length.should == 0 end @@ -336,11 +521,12 @@ describe Recording do # We should have 2 items; a track and a video: uploads = Recording.list_uploads(@user) - uploads["uploads"].should have(2).items - uploads["uploads"][0][:type].should eq("recorded_track") - uploads["uploads"][1][:type].should eq("recorded_video") - uploads["uploads"][0].should include(:client_track_id) - uploads["uploads"][1].should include(:client_video_source_id) + uploads["uploads"].should have(3).items + uploads["uploads"][0][:type].should eq("stream_mix") + uploads["uploads"][1][:type].should eq("recorded_track") + uploads["uploads"][2][:type].should eq("recorded_video") + uploads["uploads"][1].should include(:client_track_id) + uploads["uploads"][2].should include(:client_video_source_id) # Next page should have nothing: uploads = Recording.list_uploads(@user, 10, uploads["next"]) @@ -358,13 +544,19 @@ describe Recording do # Limit to 1, so we can test pagination: uploads = Recording.list_uploads(@user, 1) uploads["uploads"].should have(1).items # First page + uploads["uploads"][0][:type].should == 'stream_mix' # Second page: uploads = Recording.list_uploads(@user, 1, uploads["next"]) - uploads["uploads"].should have(1).items + uploads["uploads"].should have(1).items + uploads["uploads"][0][:type].should == 'recorded_track' # Last page (should be empty): - uploads = Recording.list_uploads(@user, 10, uploads["next"]) + uploads = Recording.list_uploads(@user, 1, uploads["next"]) + uploads["uploads"].should have(1).items + uploads["uploads"][0][:type].should == 'recorded_video' + + uploads = Recording.list_uploads(@user, 1, uploads["next"]) uploads["uploads"].should have(0).items end @@ -384,15 +576,17 @@ describe Recording do @genre = FactoryGirl.create(:genre) @recording.claim(@user, "Recording", "Recording Description", @genre, true) - # We should have 2 items; a track and a video: + # We should have 3 items; a track and a video: uploads = Recording.list_uploads(@user) - uploads["uploads"].should have(2).items - uploads["uploads"][0][:type].should eq("recorded_track") - uploads["uploads"][1][:type].should eq("recorded_video") - uploads["uploads"][0].should include(:client_track_id) - uploads["uploads"][1].should include(:client_video_source_id) - uploads["uploads"][0][:client_track_id].should eq(@track.client_track_id) - uploads["uploads"][1][:client_video_source_id].should eq(video_source.client_video_source_id) + uploads["uploads"].should have(3).items + uploads["uploads"][0][:type].should eq("stream_mix") + uploads["uploads"][1][:type].should eq("recorded_track") + uploads["uploads"][2][:type].should eq("recorded_video") + uploads["uploads"][1].should include(:client_track_id) + uploads["uploads"][2].should include(:client_video_source_id) + + uploads["uploads"][1][:client_track_id].should eq(@track.client_track_id) + uploads["uploads"][2][:client_video_source_id].should eq(video_source.client_video_source_id) # Next page should have nothing: uploads = Recording.list_uploads(@user, 10, uploads["next"]) @@ -401,20 +595,49 @@ describe Recording do # List uploads for user2. We should have 2 items; a track and a video: # The track and video source IDs should be different than above: uploads = Recording.list_uploads(user2) - uploads["uploads"].should have(2).items - uploads["uploads"][0][:type].should eq("recorded_track") - uploads["uploads"][1][:type].should eq("recorded_video") - uploads["uploads"][0].should include(:client_track_id) - uploads["uploads"][1].should include(:client_video_source_id) - uploads["uploads"][0][:client_track_id].should eq(track2.client_track_id) - uploads["uploads"][1][:client_video_source_id].should eq(video_source2.client_video_source_id) + uploads["uploads"].should have(3).items + uploads["uploads"][0][:type].should eq("stream_mix") + uploads["uploads"][1][:type].should eq("recorded_track") + uploads["uploads"][2][:type].should eq("recorded_video") + uploads["uploads"][1].should include(:client_track_id) + uploads["uploads"][2].should include(:client_video_source_id) + uploads["uploads"][1][:client_track_id].should eq(track2.client_track_id) + uploads["uploads"][2][:client_video_source_id].should eq(video_source2.client_video_source_id) # Next page should have nothing: - uploads = Recording.list_uploads(@user, 10, uploads["next"]) + uploads = Recording.list_uploads(user2, 10, uploads["next"]) uploads["uploads"].should have(0).items end + it "stream_mix.fully_uploaded = true removes from list_uploads" do + @recording = Recording.start(@music_session, @user) + @recording.stop + @recording.reload + @genre = FactoryGirl.create(:genre) + @recording.claim(@user, "Recording", "Recording Description", @genre, true) + + # We should have 2 items; a track and a quick mix: + uploads = Recording.list_uploads(@user) + uploads["uploads"].should have(2).items + uploads["uploads"][0][:type].should eq("stream_mix") + uploads["uploads"][1][:type].should eq("recorded_track") + + @recording.quick_mixes[0].fully_uploaded = true + @recording.quick_mixes[0].save! + + uploads = Recording.list_uploads(@user) + uploads["uploads"].should have(1).items + uploads["uploads"][0][:type].should eq("recorded_track") + + + @recording.recorded_tracks[0].fully_uploaded = true + @recording.recorded_tracks[0].save! + + uploads = Recording.list_uploads(@user) + uploads["uploads"].should have(0).items + + end end diff --git a/ruby/spec/jam_ruby/models/user_sync_spec.rb b/ruby/spec/jam_ruby/models/user_sync_spec.rb new file mode 100644 index 000000000..349cf706e --- /dev/null +++ b/ruby/spec/jam_ruby/models/user_sync_spec.rb @@ -0,0 +1,274 @@ +require 'spec_helper' + +describe UserSync do + + let(:user1) {FactoryGirl.create(:user)} + let(:user2) {FactoryGirl.create(:user)} + + before(:each) do + + end + + it "empty results" do + UserSync.all.length.should == 0 + end + + describe "index" do + it "empty results" do + data = UserSync.index({user_id: user1}) + data[:query].length.should == 0 + data[:next].should be_nil + end + + it "one mix" do + mix = FactoryGirl.create(:mix) + mix.recording.duration = 1 + mix.recording.save! + + data = UserSync.index({user_id: mix.recording.recorded_tracks[0].user.id}) + data[:next].should be_nil + user_syncs = data[:query] + user_syncs.length.should == 2 + user_syncs[0].recorded_track.should == mix.recording.recorded_tracks[0] + user_syncs[0].mix.should be_nil + user_syncs[1].mix.should == mix + user_syncs[1].recorded_track.should be_nil + end + + it "two mixes, one not belonging to querier" do + mix1 = FactoryGirl.create(:mix) + mix2 = FactoryGirl.create(:mix) + mix1.recording.duration = 1 + mix1.recording.save! + mix2.recording.duration = 1 + mix2.recording.save! + + data = UserSync.index({user_id: mix1.recording.recorded_tracks[0].user.id}) + data[:next].should be_nil + user_syncs = data[:query] + user_syncs.length.should == 2 + user_syncs[0].recorded_track.should == mix1.recording.recorded_tracks[0] + user_syncs[0].mix.should be_nil + user_syncs[1].mix.should == mix1 + user_syncs[1].recorded_track.should be_nil + + data = UserSync.index({user_id: mix2.recording.recorded_tracks[0].user.id}) + data[:next].should be_nil + user_syncs = data[:query] + user_syncs.length.should == 2 + user_syncs[0].recorded_track.should == mix2.recording.recorded_tracks[0] + user_syncs[0].mix.should be_nil + user_syncs[1].mix.should == mix2 + user_syncs[1].recorded_track.should be_nil + end + + describe "one recording with two users" do + let!(:recording1) { + recording = FactoryGirl.create(:recording, owner: user1, band: nil, duration:1) + recording.recorded_tracks << FactoryGirl.create(:recorded_track, recording: recording, user: recording.owner) + recording.recorded_tracks << FactoryGirl.create(:recorded_track, recording: recording, user: user2) + recording.save! + recording.reload + recording + } + + let(:sorted_tracks) { + Array.new(recording1.recorded_tracks).sort! {|a, b| + if a.created_at == b.created_at + a.id <=> b.id + else + a.created_at <=> b.created_at + end + } + } + + it "no claimed_recordings" do + # both user1 and user2 should be told about each others tracks, because both will need to upload their tracks + data = UserSync.index({user_id: user1.id}) + data[:next].should be_nil + user_syncs = data[:query] + user_syncs.length.should == 2 + user_syncs[0].recorded_track.should == sorted_tracks[0] + user_syncs[1].recorded_track.should == sorted_tracks[1] + + data = UserSync.index({user_id: user2.id}) + data[:next].should be_nil + user_syncs = data[:query] + user_syncs[0].recorded_track.should == sorted_tracks[0] + user_syncs[1].recorded_track.should == sorted_tracks[1] + end + + it "recording isn't over" do + recording1.duration = nil + recording1.save! + + # nothing should be returned, because the recording isn't over + data = UserSync.index({user_id: user1.id}) + data[:next].should be_nil + user_syncs = data[:query] + user_syncs.length.should == 0 + + data = UserSync.index({user_id: user2.id}) + data[:next].should be_nil + user_syncs = data[:query] + user_syncs.length.should == 0 + end + + it "one user decides to keep the recording" do + claimed_recording = FactoryGirl.create(:claimed_recording, user: user1, recording: recording1, discarded:false) + claimed_recording.recording.should == recording1 + + data = UserSync.index({user_id: user1.id}) + data[:next].should be_nil + user_syncs = data[:query] + user_syncs.length.should == 2 + user_syncs[0].recorded_track.should == sorted_tracks[0] + user_syncs[1].recorded_track.should == sorted_tracks[1] + + data = UserSync.index({user_id: user2.id}) + data[:next].should be_nil + user_syncs = data[:query] + user_syncs.length.should == 2 + user_syncs[0].recorded_track.should == sorted_tracks[0] + user_syncs[1].recorded_track.should == sorted_tracks[1] + end + + + it "one user decides to discard the recording" do + FactoryGirl.create(:claimed_recording, user: user1, recording: recording1, discarded:true) + + data = UserSync.index({user_id: user1.id}) + data[:next].should be_nil + user_syncs = data[:query] + user_syncs.length.should == 2 + user_syncs[0].recorded_track.should == sorted_tracks[0] + user_syncs[1].recorded_track.should == sorted_tracks[1] + + data = UserSync.index({user_id: user2.id}) + data[:next].should be_nil + user_syncs = data[:query] + user_syncs.length.should == 2 + user_syncs[0].recorded_track.should == sorted_tracks[0] + user_syncs[1].recorded_track.should == sorted_tracks[1] + end + + it "both users decide to discard the recording" do + recording1.all_discarded = true + recording1.save! + + data = UserSync.index({user_id: user1.id}) + data[:next].should be_nil + user_syncs = data[:query] + user_syncs.length.should == 0 + + data = UserSync.index({user_id: user2.id}) + data[:next].should be_nil + user_syncs = data[:query] + user_syncs.length.should == 0 + end + end + + describe "one recording with multi-track users" do + let!(:recording1) { + recording = FactoryGirl.create(:recording, owner: user1, band: nil, duration:1) + recording.recorded_tracks << FactoryGirl.create(:recorded_track, recording: recording, user: recording.owner) + recording.recorded_tracks << FactoryGirl.create(:recorded_track, recording: recording, user: recording.owner) + recording.recorded_tracks << FactoryGirl.create(:recorded_track, recording: recording, user: user2) + recording.recorded_tracks << FactoryGirl.create(:recorded_track, recording: recording, user: user2) + recording.save! + recording.reload + recording + } + + let(:sorted_tracks) { + Array.new(recording1.recorded_tracks).sort! {|a, b| + if a.created_at == b.created_at + a.id <=> b.id + else + a.created_at <=> b.created_at + end + } + } + + + it "one user decides to keep the recording" do + claimed_recording = FactoryGirl.create(:claimed_recording, user: user1, recording: recording1, discarded:false) + claimed_recording.recording.should == recording1 + + data = UserSync.index({user_id: user1.id}) + data[:next].should be_nil + user_syncs = data[:query] + user_syncs.length.should == 4 + user_syncs[0].recorded_track.should == sorted_tracks[0] + user_syncs[1].recorded_track.should == sorted_tracks[1] + user_syncs[2].recorded_track.should == sorted_tracks[2] + user_syncs[3].recorded_track.should == sorted_tracks[3] + + data = UserSync.index({user_id: user2.id}) + data[:next].should be_nil + user_syncs = data[:query] + user_syncs.length.should == 4 + user_syncs[0].recorded_track.should == sorted_tracks[0] + user_syncs[1].recorded_track.should == sorted_tracks[1] + user_syncs[2].recorded_track.should == sorted_tracks[2] + user_syncs[3].recorded_track.should == sorted_tracks[3] + end + end + + end + + describe "pagination" do + let!(:recording1) { + recording = FactoryGirl.create(:recording, owner: user1, band: nil, duration:1) + recording.recorded_tracks << FactoryGirl.create(:recorded_track, recording: recording, user: recording.owner) + recording.recorded_tracks << FactoryGirl.create(:recorded_track, recording: recording, user: user2) + recording.save! + recording.reload + recording + } + let(:sorted_tracks) { + Array.new(recording1.recorded_tracks).sort! {|a, b| + if a.created_at == b.created_at + a.id <=> b.id + else + a.created_at <=> b.created_at + end + } + } + + it "tiny page size" do + # get the 1st track + data = UserSync.index({user_id: user1.id, offset: 0, limit: 1}) + data[:next].should == 1 + user_syncs = data[:query] + user_syncs.length.should == 1 + user_syncs[0].recorded_track.should == sorted_tracks[0] + data[:query].total_entries.should == 2 + + # then get the second track, which happens to be on an edge, pagination wise + data = UserSync.index({user_id: user1.id, offset: 1, limit: 1}) + data[:next].should == 2 + user_syncs = data[:query] + user_syncs.length.should == 1 + user_syncs[0].recorded_track.should == sorted_tracks[1] + data[:query].total_entries.should == 2 + + # so prove it's on the edge by asking for 2 items instead of 1. + data = UserSync.index({user_id: user1.id, offset: 0, limit: 3}) + data[:next].should == nil + user_syncs = data[:query] + user_syncs.length.should == 2 + user_syncs[0].recorded_track.should == sorted_tracks[0] + user_syncs[1].recorded_track.should == sorted_tracks[1] + data[:query].total_entries.should == 2 + + data = UserSync.index({user_id: user1.id, offset: 2, limit: 1}) + data[:next].should == nil + user_syncs = data[:query] + user_syncs.length.should == 0 + data[:query].total_entries.should == 2 + + + end + end +end diff --git a/ruby/spec/jam_ruby/resque/audiomixer_spec.rb b/ruby/spec/jam_ruby/resque/audiomixer_spec.rb index 95e7b136f..ab4ed7875 100644 --- a/ruby/spec/jam_ruby/resque/audiomixer_spec.rb +++ b/ruby/spec/jam_ruby/resque/audiomixer_spec.rb @@ -1,7 +1,6 @@ require 'spec_helper' require 'fileutils' -=begin # these tests avoid the use of ActiveRecord and FactoryGirl to do blackbox, non test-instrumented tests describe AudioMixer do @@ -141,6 +140,7 @@ describe AudioMixer do File.read(audiomixer.manifest[:error_out]).should == "some_error" end end +=begin describe "integration" do @@ -157,7 +157,7 @@ describe AudioMixer do @music_session = FactoryGirl.create(:active_music_session, :creator => @user, :musician_access => true) # @music_session.connections << @connection @music_session.save - @connection.join_the_session(@music_session, true, nil) + @connection.join_the_session(@music_session, true, [@track], @user, 10) @recording = Recording.start(@music_session, @user) @recording.stop @recording.claim(@user, "name", "description", Genre.first, true) @@ -178,8 +178,10 @@ describe AudioMixer do # stub out methods that are environmentally sensitive (so as to skip s3, and not run an actual audiomixer) before(:each) do AudioMixer.any_instance.stub(:execute) do |manifest_file| - output_filename = JSON.parse(File.read(manifest_file))['output']['filename'] - FileUtils.touch output_filename + output_ogg_filename = JSON.parse(File.read(manifest_file))['output']['filename'] + FileUtils.touch output_ogg_filename + output_mp3_filename = JSON.parse(File.read(manifest_file))['output']['filename_mp3'] + FileUtils.touch output_mp3_filename end AudioMixer.any_instance.stub(:postback) # don't actually post resulting off file up @@ -194,18 +196,20 @@ describe AudioMixer do @mix = Mix.schedule(@recording) @mix.reload @mix.started_at.should_not be_nil - AudioMixer.perform(@mix.id, @mix.sign_url(60 * 60 * 24)) + AudioMixer.perform(@mix.id, @mix.sign_url(60 * 60 * 24, 'ogg'), @mix.sign_url(60 * 60 * 24, 'mp3')) @mix.reload @mix.completed.should be_true - @mix.length.should == 0 - @mix.md5.should == 'd41d8cd98f00b204e9800998ecf8427e' # that's the md5 of a touched file + @mix.ogg_length.should == 0 + @mix.ogg_md5.should == 'd41d8cd98f00b204e9800998ecf8427e' # that's the md5 of a touched file + @mix.mp3_length.should == 0 + @mix.mp3_md5.should == 'd41d8cd98f00b204e9800998ecf8427e' # that's the md5 of a touched file end it "errored" do local_files_manifest[:files][0][:filename] = '/some/path/to/nowhere' Mix.any_instance.stub(:manifest).and_return(local_files_manifest) @mix = Mix.schedule(@recording) - expect{ AudioMixer.perform(@mix.id, @mix.sign_url(60 * 60 * 24)) }.to raise_error + expect{ AudioMixer.perform(@mix.id, @mix.sign_url(60 * 60 * 24, 'ogg'), @mix.sign_url(60 * 60 * 24, 'mp3')) }.to raise_error @mix.reload @mix.completed.should be_false @mix.error_count.should == 1 @@ -283,8 +287,10 @@ describe AudioMixer do @s3_sample = @s3_manager.sign_url(key, :secure => false) AudioMixer.any_instance.stub(:execute) do |manifest_file| - output_filename = JSON.parse(File.read(manifest_file))['output']['filename'] - FileUtils.touch output_filename + output_filename_ogg = JSON.parse(File.read(manifest_file))['output']['filename'] + FileUtils.touch output_filename_ogg + output_filename_mp3 = JSON.parse(File.read(manifest_file))['output']['filename_mp3'] + FileUtils.touch output_filename_mp3 end end @@ -296,26 +302,13 @@ describe AudioMixer do @mix.reload @mix.completed.should be_true - @mix.length.should == 0 - @mix.md5.should == 'd41d8cd98f00b204e9800998ecf8427e' # that's the md5 of a touched file, which is what the stubbed :execute does - end - - it "fails" do - with_resque do - s3_manifest[:files][0][:filename] = @s3_manager.url('audiomixer/bogus.ogg', :secure => false) # take off some of the trailing chars of the url - Mix.any_instance.stub(:manifest).and_return(s3_manifest) - expect{ Mix.schedule(@recording) }.to raise_error - end - - @mix = Mix.order('id desc').limit(1).first() - @mix.reload - @mix.completed.should be_false - @mix.error_reason.should == "unable to download" - #ResqueFailedJobMailer::Mailer.deliveries.count.should == 1 + @mix.ogg_length.should == 0 + @mix.ogg_md5.should == 'd41d8cd98f00b204e9800998ecf8427e' # that's the md5 of a touched file, which is what the stubbed :execute does + @mix.mp3_length.should == 0 + @mix.mp3_md5.should == 'd41d8cd98f00b204e9800998ecf8427e' # that's the md5 of a touched file, which is what the stubbed :execute does end end end +=end end - -=end \ No newline at end of file diff --git a/ruby/spec/jam_ruby/resque/quick_mixer_spec.rb b/ruby/spec/jam_ruby/resque/quick_mixer_spec.rb new file mode 100644 index 000000000..9a622ce1a --- /dev/null +++ b/ruby/spec/jam_ruby/resque/quick_mixer_spec.rb @@ -0,0 +1,121 @@ +require 'spec_helper' +require 'fileutils' + +# these tests avoid the use of ActiveRecord and FactoryGirl to do blackbox, non test-instrumented tests +describe AudioMixer do + + include UsesTempFiles + + let(:quick_mix) { FactoryGirl.create(:quick_mix, started_at: nil, should_retry: false) } + + + before(:each) do + stub_const("APP_CONFIG", app_config) + module EM + @next_tick_queue = [] + end + + MQRouter.client_exchange = double("client_exchange") + MQRouter.user_exchange = double("user_exchange") + MQRouter.client_exchange.should_receive(:publish).any_number_of_times + MQRouter.user_exchange.should_receive(:publish).any_number_of_times + end + + def assert_found_job_count(expected) + count = 0 + QuickMixer.find_jobs_needing_retry do + count = count + 1 + end + count.should == expected + end + + describe "queue_jobs_needing_retry" do + it "won't find anything if no quick mixes" do + assert_found_job_count(0) + end + + it "won't find a quick mix that hasn't been started" do + quick_mix.touch + + assert_found_job_count(0) + end + + it "won't find a quick mix that has should_retry flagged" do + quick_mix.should_retry = true + quick_mix.save! + + assert_found_job_count(1) + end + + it "won't find a quick mix that has should_retry flagged" do + quick_mix.should_retry = false + quick_mix.started_at = 2.hours.ago + quick_mix.save! + + assert_found_job_count(1) + end + end + + + # these tests try to run the job with minimal faking. Here's what we still fake: + # we don't run audiomixer. audiomixer is tested already + # we don't run redis and actual resque, because that's tested by resque/resque-spec + describe "full", :aws => true do + + + sample_ogg='sample.ogg' + in_directory_with_file(sample_ogg) + + + before(:each) do + content_for_file("ogg goodness") + @user = FactoryGirl.create(:user) + @connection = FactoryGirl.create(:connection, :user => @user) + @instrument = FactoryGirl.create(:instrument, :description => 'a great instrument') + @track = FactoryGirl.create(:track, :connection => @connection, :instrument => @instrument) + @music_session = FactoryGirl.create(:active_music_session, :creator => @user, :musician_access => true) + # @music_session.connections << @connection + @music_session.save + @connection.join_the_session(@music_session, true, [@track], @user, 10) + @recording = Recording.start(@music_session, @user) + @recording.stop + @recording.claim(@user, "name", "description", Genre.first, true) + @recording.errors.any?.should be_false + @recording.quick_mixes.length.should == 1 + @quick_mix = @recording.quick_mixes[0] + + test_config = app_config + + @s3_manager = S3Manager.new(test_config.aws_bucket, test_config.aws_access_key_id, test_config.aws_secret_access_key) + + # put a file in s3 + @s3_manager.upload(@quick_mix[:ogg_url], sample_ogg) + + # create a signed url that the job will use to fetch it back down + @s3_sample = @s3_manager.sign_url(@quick_mix[:ogg_url], :secure => false) + + QuickMixer.any_instance.stub(:create_mp3) do |input_file, output_file| + FileUtils.mv input_file, output_file + end + end + + it "completes" do + with_resque do + #QuickMix.any_instance.stub(:manifest).and_return(s3_manifest) + @mix = @recording.quick_mixes[0] + @mix.enqueue + end + + @mix.reload + @mix.completed.should be_true + @mix.mp3_length.should == "ogg goodness".length + @mix.mp3_md5.should == ::Digest::MD5.file(sample_ogg).hexdigest + + # fetch back the mp3 file from s3, check that it's equivalent to the sample_ogg file (which we did a FileUtils.mv of to make a fake mp3) + mp3_fetched_from_s3 = Tempfile.new('foo') + @s3_manager.download(@quick_mix[:mp3_url], mp3_fetched_from_s3.path) + @mix.mp3_md5.should == ::Digest::MD5.file(mp3_fetched_from_s3).hexdigest + + end + end +end diff --git a/ruby/spec/spec_helper.rb b/ruby/spec/spec_helper.rb index 3898c2462..73e9a3384 100644 --- a/ruby/spec/spec_helper.rb +++ b/ruby/spec/spec_helper.rb @@ -42,6 +42,7 @@ ActiveRecord::Base.add_observer InvitedUserObserver.instance ActiveRecord::Base.add_observer UserObserver.instance ActiveRecord::Base.add_observer FeedbackObserver.instance ActiveRecord::Base.add_observer RecordedTrackObserver.instance +ActiveRecord::Base.add_observer QuickMixObserver.instance #RecordedTrack.observers.disable :all # only a few tests want this observer active diff --git a/web/Gemfile b/web/Gemfile index 7b121350b..a1068822c 100644 --- a/web/Gemfile +++ b/web/Gemfile @@ -34,7 +34,7 @@ gem 'uuidtools', '2.1.2' gem 'ruby-protocol-buffers', '1.2.2' gem 'pg', '0.17.1' gem 'compass-rails', '1.1.3' # 1.1.4 throws an exception on startup about !initialize on nil -gem 'rabl' # for JSON API development +gem 'rabl', '0.11.0' # for JSON API development gem 'gon', '~>4.1.0' # for passthrough of Ruby variables to Javascript variables gem 'eventmachine', '1.0.3' gem 'faraday', '~>0.9.0' @@ -110,7 +110,7 @@ end group :test, :cucumber do gem 'simplecov', '~> 0.7.1' gem 'simplecov-rcov' - gem 'capybara' + gem 'capybara', '2.4.4' #if ENV['JAMWEB_QT5'] == '1' # # necessary on platforms such as arch linux, where pacman -S qt5-webkit is your easiet option # gem "capybara-webkit", :git => 'git://github.com/thoughtbot/capybara-webkit.git' diff --git a/web/app/assets/images/content/icon_instrument_ukelele24.png b/web/app/assets/images/content/icon_instrument_ukulele24.png similarity index 100% rename from web/app/assets/images/content/icon_instrument_ukelele24.png rename to web/app/assets/images/content/icon_instrument_ukulele24.png diff --git a/web/app/assets/images/content/icon_instrument_ukelele256.png b/web/app/assets/images/content/icon_instrument_ukulele256.png similarity index 100% rename from web/app/assets/images/content/icon_instrument_ukelele256.png rename to web/app/assets/images/content/icon_instrument_ukulele256.png diff --git a/web/app/assets/images/content/icon_instrument_ukelele45.png b/web/app/assets/images/content/icon_instrument_ukulele45.png similarity index 100% rename from web/app/assets/images/content/icon_instrument_ukelele45.png rename to web/app/assets/images/content/icon_instrument_ukulele45.png diff --git a/web/app/assets/javascripts/accounts_audio_profile.js b/web/app/assets/javascripts/accounts_audio_profile.js index 13c679c1c..1ac004c20 100644 --- a/web/app/assets/javascripts/accounts_audio_profile.js +++ b/web/app/assets/javascripts/accounts_audio_profile.js @@ -93,7 +93,7 @@ var profiles = populateAccountAudio(); if(profiles.length <= 1) { setTimeout(function() { - context.JK.prodBubble($addNewGearBtn, 'no-audio-profiles', {}, {positions: ['bottom'], offsetParent: $addNewGearBtn.closest('.screen')}); + context.JK.prodBubble($addNewGearBtn, 'no-audio-profiles', {}, {positions: ['bottom'], offsetParent: $addNewGearBtn.closest('.screen')}) }, 1000); } diff --git a/web/app/assets/javascripts/application.js b/web/app/assets/javascripts/application.js index ec05b467c..b971a1d5e 100644 --- a/web/app/assets/javascripts/application.js +++ b/web/app/assets/javascripts/application.js @@ -34,6 +34,7 @@ //= require jquery.pulse //= require jquery.browser //= require jquery.custom-protocol +//= require jquery.exists //= require jstz //= require class //= require AAC_underscore diff --git a/web/app/assets/javascripts/dialog/allSyncsDialog.js b/web/app/assets/javascripts/dialog/allSyncsDialog.js new file mode 100644 index 000000000..e6de6cf3f --- /dev/null +++ b/web/app/assets/javascripts/dialog/allSyncsDialog.js @@ -0,0 +1,48 @@ +(function (context, $) { + + "use strict"; + context.JK = context.JK || {}; + context.JK.AllSyncsDialog = function (app) { + var logger = context.JK.logger; + var rest = context.JK.Rest(); + var $dialog = null; + var $syncsHolder = null; + var syncViewer = null; + + + function registerEvents() { + + } + + function beforeShow() { + syncViewer.onShow() + } + + function beforeHide() { + syncViewer.onHide() + } + + function initialize(invitationDialogInstance) { + var dialogBindings = { + 'beforeShow': beforeShow, + 'beforeHide': beforeHide + }; + + app.bindDialog('all-syncs-dialog', dialogBindings); + + $dialog = $('#all-syncs-dialog'); + $syncsHolder = $dialog.find('.syncs') + + syncViewer = new context.JK.SyncViewer(app); + syncViewer.init($syncsHolder); + $syncsHolder.append(syncViewer.root) + registerEvents(); + + }; + + + this.initialize = initialize; + } + + return this; +})(window, jQuery); \ No newline at end of file diff --git a/web/app/assets/javascripts/dialog/recordingFinishedDialog.js b/web/app/assets/javascripts/dialog/recordingFinishedDialog.js index 201e1cc9f..5863d54e8 100644 --- a/web/app/assets/javascripts/dialog/recordingFinishedDialog.js +++ b/web/app/assets/javascripts/dialog/recordingFinishedDialog.js @@ -7,6 +7,7 @@ var rest = context.JK.Rest(); var playbackControls = null; var recording = null; // deferred object + var $dialog = null; function resetForm() { @@ -16,6 +17,7 @@ } function beforeShow() { + $dialog.data('result', null); if (recording == null) { alert("recording data should not be null"); app.layout.closeDialog('recordingFinished'); @@ -104,6 +106,7 @@ logger.error("recording discard by user failed. recordingId=%o. reason: %o", recording.id, jqXHR.responseText); }) .always(function () { + $dialog.data('result', {keep:false}); app.layout.closeDialog('recordingFinished') registerDiscardRecordingHandlers(true); }) @@ -128,6 +131,7 @@ is_public: is_public }) .done(function () { + $dialog.data('result', {keep:true}); app.layout.closeDialog('recordingFinished'); context.JK.GA.trackMakeRecording(); }) @@ -231,6 +235,7 @@ app.bindDialog('recordingFinished', dialogBindings); + $dialog = $('#recording-finished-dialog') playbackControls = new context.JK.PlaybackControls($('#recording-finished-dialog .recording-controls')); registerStaticEvents(); diff --git a/web/app/assets/javascripts/dialog/whatsNextDialog.js b/web/app/assets/javascripts/dialog/whatsNextDialog.js deleted file mode 100644 index e7c5fd5f2..000000000 --- a/web/app/assets/javascripts/dialog/whatsNextDialog.js +++ /dev/null @@ -1,64 +0,0 @@ -(function (context, $) { - - "use strict"; - context.JK = context.JK || {}; - context.JK.WhatsNextDialog = function (app) { - var logger = context.JK.logger; - var rest = context.JK.Rest(); - var invitationDialog = null; - - - function registerEvents() { - - $('#whatsnext-dialog a.facebook-invite').on('click', function (e) { - invitationDialog.showFacebookDialog(e); - }); - - $('#whatsnext-dialog a.google-invite').on('click', function (e) { - invitationDialog.showGoogleDialog(); - }); - - $('#whatsnext-dialog a.email-invite').on('click', function (e) { - invitationDialog.showEmailDialog(); - }); - } - - function beforeShow() { - } - - function beforeHide() { - var $dontShowWhatsNext = $('#show_whats_next'); - - if ($dontShowWhatsNext.is(':checked')) { - rest.updateUser({show_whats_next: false}) - } - - } - - function initializeButtons() { - var dontShow = $('#show_whats_next'); - - context.JK.checkbox(dontShow); - } - - function initialize(invitationDialogInstance) { - var dialogBindings = { - 'beforeShow': beforeShow, - 'beforeHide': beforeHide - }; - - app.bindDialog('whatsNext', dialogBindings); - - registerEvents(); - - invitationDialog = invitationDialogInstance; - - initializeButtons(); - }; - - - this.initialize = initialize; - } - - return this; -})(window, jQuery); \ No newline at end of file diff --git a/web/app/assets/javascripts/fakeJamClient.js b/web/app/assets/javascripts/fakeJamClient.js index 393501e1b..294580721 100644 --- a/web/app/assets/javascripts/fakeJamClient.js +++ b/web/app/assets/javascripts/fakeJamClient.js @@ -336,6 +336,12 @@ dbg('AbortRecording'); fakeJamClientRecordings.AbortRecording(recordingId, errorReason, errorDetail); } + function OnTrySyncCommand(cmd) { + + } + function GetRecordingManagerState() { + return {running: false} + } function TestASIOLatency(s) { dbg('TestASIOLatency' + JSON.stringify(arguments)); } @@ -808,6 +814,8 @@ // Javascript Bridge seems to camel-case // Set the instance functions: this.AbortRecording = AbortRecording; + this.OnTrySyncCommand = OnTrySyncCommand; + this.GetRecordingManagerState = GetRecordingManagerState; this.GetASIODevices = GetASIODevices; this.GetOS = GetOS; this.GetOSAsString = GetOSAsString; diff --git a/web/app/assets/javascripts/feedHelper.js b/web/app/assets/javascripts/feedHelper.js index 78d827a9d..01a4740e0 100644 --- a/web/app/assets/javascripts/feedHelper.js +++ b/web/app/assets/javascripts/feedHelper.js @@ -9,6 +9,7 @@ var rest = new context.JK.Rest(); var EVENTS = context.JK.EVENTS; var ui = new context.JK.UIHelper(JK.app); + var recordingUtils = context.JK.RecordingUtils; var userId = null; var currentFeedPage = 0; var feedBatchSize = 10; @@ -179,7 +180,7 @@ if(data.displayText) $status.text(data.displayText); - if(data.isEnd) stopSessionPlay(); + if(data.isEnd) stopSessionPlay($feedItem); if(data.isSessionOver) { $controls.removeClass('inprogress').addClass('ended') @@ -320,7 +321,10 @@ $isPrivate.removeClass('enabled') } else { - $feedEntry.find('.play-button').hide(); + if(!isOwner()) + { + $feedEntry.find('.play-button').hide(); // still show play button if private && isOwner() + } $isPrivate.addClass('enabled') } } @@ -424,6 +428,9 @@ logger.error("a recording in the feed should always have one claimed_recording") return; } + // pump some useful data about mixing into the feed item + feed.mix_info = recordingUtils.createMixInfo({state: feed.mix_state}) + var options = { feed_item: feed, candidate_claimed_recording: obtainCandidate(feed), @@ -433,6 +440,10 @@ var $feedItem = $(context._.template($('#template-feed-recording').html(), options, {variable: 'data'})); var $controls = $feedItem.find('.recording-controls'); + $controls.data('mix-state', feed.mix_info) // for recordingUtils helper methods + $controls.data('server-info', feed.mix) // for recordingUtils helper methods + $controls.data('view-context', 'feed') + $('.timeago', $feedItem).timeago(); context.JK.prettyPrintElements($('.duration', $feedItem)); context.JK.setInstrumentAssetPath($('.instrument-icon', $feedItem)); @@ -501,6 +512,8 @@ }).show(); } + context.JK.helpBubble($feedItem.find('.help-launcher'), recordingUtils.onMixHover, {}, {width:'450px', closeWhenOthersOpen: true, positions:['top', 'left', 'bottom', 'right'], offsetParent: $screen.parent()}) + // put the feed item on the page renderFeed($feedItem); diff --git a/web/app/assets/javascripts/feed_item_recording.js b/web/app/assets/javascripts/feed_item_recording.js index e9c138479..e9d1778de 100644 --- a/web/app/assets/javascripts/feed_item_recording.js +++ b/web/app/assets/javascripts/feed_item_recording.js @@ -6,10 +6,12 @@ context.JK.FeedItemRecording = function($parentElement, options){ var ui = new context.JK.UIHelper(JK.app); + var recordingUtils = context.JK.RecordingUtils; var claimedRecordingId = $parentElement.attr('data-claimed-recording-id'); var recordingId = $parentElement.attr('id'); var mode = $parentElement.attr('data-mode'); + var mixInfo = null; var $feedItem = $parentElement; var $name = $('.name', $feedItem); @@ -129,6 +131,12 @@ context.JK.bindHoverEvents($feedItem); //context.JK.bindProfileClickEvents($feedItem); + + mixInfo = recordingUtils.createMixInfo({state: options.mix_state}) + $controls.data('mix-state', mixInfo) // for recordingUtils helper methods + $controls.data('view-context', 'feed') + $controls.addClass(mixInfo.mixStateClass) + $status.text(mixInfo.mixStateMsg) } initialize(); diff --git a/web/app/assets/javascripts/globals.js b/web/app/assets/javascripts/globals.js index 0886cacf2..eb6fd0b27 100644 --- a/web/app/assets/javascripts/globals.js +++ b/web/app/assets/javascripts/globals.js @@ -35,7 +35,11 @@ RSVP_CANCELED : 'rsvp_canceled', USER_UPDATED : 'user_updated', SESSION_STARTED : 'session_started', - SESSION_ENDED : 'session_stopped' + SESSION_ENDED : 'session_stopped', + FILE_MANAGER_CMD_START : 'file_manager_cmd_start', + FILE_MANAGER_CMD_STOP : 'file_manager_cmd_stop', + FILE_MANAGER_CMD_PROGRESS : 'file_manager_cmd_progress', + FILE_MANAGER_CMD_ASAP_UPDATE : 'file_manager_cmd_asap_update' }; context.JK.ALERT_NAMES = { diff --git a/web/app/assets/javascripts/hoverMusician.js b/web/app/assets/javascripts/hoverMusician.js index 70f688d35..f5f69440a 100644 --- a/web/app/assets/javascripts/hoverMusician.js +++ b/web/app/assets/javascripts/hoverMusician.js @@ -7,8 +7,12 @@ var logger = context.JK.logger; var rest = context.JK.Rest(); var hoverSelector = "#musician-hover"; + var helpBubble = context.JK.HelpBubbleHelper; + var $templateLatency = null; + var sessionUtils = context.JK.SessionUtils; this.showBubble = function() { + $templateLatency = $("#template-account-session-latency"); var mouseLeft = x < (document.body.clientWidth / 2); var mouseTop = y < (document.body.clientHeight / 2); var css = {}; @@ -82,10 +86,29 @@ } } + var fullScore = null; + + if (response.internet_score) { + fullScore = response.last_jam_audio_latency + calculateAudioLatency(response.my_audio_latency) + calculateAudioLatency(response.internet_score); + } + + // latency badge template needs these 2 properties + $.extend(response, { + audio_latency: response.last_jam_audio_latency, + full_score: fullScore + }); + + var latencyBadge = context._.template( + $templateLatency.html(), + $.extend(sessionUtils.createLatency(response), response), + {variable: 'data'} + ); + var musicianHtml = context.JK.fillTemplate(template, { userId: response.id, avatar_url: context.JK.resolveAvatarUrl(response.photo_url), name: response.name, + first_name: response.first_name, location: response.location, instruments: instrumentHtml, friend_count: response.friend_count, @@ -95,6 +118,7 @@ session_display: sessionDisplayStyle, join_display: joinDisplayStyle, sessionId: sessionId, + latency_badge: latencyBadge, //friendAction: response.is_friend ? "removeMusicianFriend" : (response.pending_friend_request ? "" : "sendMusicianFriendRequest"), friendAction: response.is_friend ? "" : (response.pending_friend_request ? "" : "sendMusicianFriendRequest"), followAction: response.is_following ? "removeMusicianFollowing" : "addMusicianFollowing", @@ -121,6 +145,14 @@ }); }; + function calculateAudioLatency(latency) { + if (!latency || latency === 0) { + return 13; + } + + return latency; + } + function configureActionButtons(user) { var btnFriendSelector = "#btnFriend"; var btnFollowSelector = "#btnFollow"; diff --git a/web/app/assets/javascripts/jam_rest.js b/web/app/assets/javascripts/jam_rest.js index ff031af99..5c714bde5 100644 --- a/web/app/assets/javascripts/jam_rest.js +++ b/web/app/assets/javascripts/jam_rest.js @@ -68,6 +68,13 @@ }); } + function getMusicNotation(query) { + return $.ajax({ + type: "GET", + url: "/api/music_notations/"+query + }); + } + function legacyJoinSession(options) { var sessionId = options["session_id"]; delete options["session_id"]; @@ -833,7 +840,29 @@ }) } + function getUserSyncs(options) { + if(!options) { options = {}; } + var userId = getId(options) + return $.ajax({ + type: 'GET', + dataType: "json", + url: "/api/users/" + userId + "/syncs?" + $.param(options), + processData:false + }) + } + function getUserSync(options) { + if(!options) { options = {}; } + var userId = getId(options) + var userSyncId = options['user_sync_id'] + + return $.ajax({ + type: 'GET', + dataType: "json", + url: "/api/users/" + userId + "/syncs/" + userSyncId, + processData:false + }) + } function sendFriendRequest(app, userId, callback) { var url = "/api/users/" + context.JK.currentUserId + "/friend_requests"; @@ -972,6 +1001,18 @@ }) } + function getRecordedTrack(options) { + var recordingId = options["recording_id"]; + var trackId = options["track_id"]; + + return $.ajax({ + type: "GET", + dataType: "json", + contentType: 'application/json', + url: "/api/recordings/" + recordingId + "/tracks/" + trackId + }); + } + function getRecording(options) { var recordingId = options["id"]; @@ -1214,6 +1255,7 @@ }); } + function initialize() { return self; } @@ -1223,6 +1265,7 @@ this.legacyCreateSession = legacyCreateSession; this.createScheduledSession = createScheduledSession; this.uploadMusicNotations = uploadMusicNotations; + this.getMusicNotation = getMusicNotation; this.legacyJoinSession = legacyJoinSession; this.joinSession = joinSession; this.cancelSession = cancelSession; @@ -1273,6 +1316,8 @@ this.getMusicianInvites = getMusicianInvites; this.postFeedback = postFeedback; this.getFeeds = getFeeds; + this.getUserSyncs = getUserSyncs; + this.getUserSync = getUserSync; this.serverHealthCheck = serverHealthCheck; this.sendFriendRequest = sendFriendRequest; this.getFriendRequest = getFriendRequest; @@ -1287,6 +1332,7 @@ this.startRecording = startRecording; this.stopRecording = stopRecording; this.getRecording = getRecording; + this.getRecordedTrack = getRecordedTrack; this.getClaimedRecordings = getClaimedRecordings; this.getClaimedRecording = getClaimedRecording; this.updateClaimedRecording = updateClaimedRecording; diff --git a/web/app/assets/javascripts/jquery.exists.js b/web/app/assets/javascripts/jquery.exists.js new file mode 100644 index 000000000..ff88124d0 --- /dev/null +++ b/web/app/assets/javascripts/jquery.exists.js @@ -0,0 +1 @@ +jQuery.fn.exists = function(){return this.length > 0;} diff --git a/web/app/assets/javascripts/landing/landing.js b/web/app/assets/javascripts/landing/landing.js index b8a0567dd..0afe196f0 100644 --- a/web/app/assets/javascripts/landing/landing.js +++ b/web/app/assets/javascripts/landing/landing.js @@ -18,6 +18,7 @@ //= require jquery.custom-protocol //= require jquery.ba-bbq //= require jquery.icheck +//= require jquery.exists //= require AAA_Log //= require AAC_underscore //= require alert diff --git a/web/app/assets/javascripts/layout.js b/web/app/assets/javascripts/layout.js index 6abce7e89..7bf5abfd2 100644 --- a/web/app/assets/javascripts/layout.js +++ b/web/app/assets/javascripts/layout.js @@ -462,6 +462,7 @@ $dialog.triggerHandler(EVENTS.DIALOG_CLOSED, {name: dialog, dialogCount: openDialogs.length, result: $dialog.data('result'), canceled: canceled }); $(context).triggerHandler(EVENTS.DIALOG_CLOSED, {name: dialog, dialogCount: openDialogs.length, result: $dialog.data('result'), canceled: canceled }); dialogEvent(dialog, 'afterHide'); + $.btOffAll(); // add any prod bubbles if you close a dialog } function screenEvent(screen, evtName, data) { @@ -568,6 +569,7 @@ screenEvent(previousScreen, 'afterHide', data); screenEvent(currentScreen, 'afterShow', data); + jQuery.btOffAll(); // add any prod bubbles if you change screens // Show any requested dialog if ("d" in data) { @@ -700,6 +702,7 @@ addScreenContextToDialog($dialog) $dialog.show(); dialogEvent(dialog, 'afterShow', options); + $.btOffAll(); // add any prod bubbles if you open a dailog return $dialog; } diff --git a/web/app/assets/javascripts/networkTestHelper.js b/web/app/assets/javascripts/networkTestHelper.js index 324190a8f..c295f1123 100644 --- a/web/app/assets/javascripts/networkTestHelper.js +++ b/web/app/assets/javascripts/networkTestHelper.js @@ -156,7 +156,7 @@ function appendContextualStatement() { if (inGearWizard) { - return "You can skip this step for now." + return " You can skip this step for now." } else { return ''; diff --git a/web/app/assets/javascripts/notificationPanel.js b/web/app/assets/javascripts/notificationPanel.js index 08121983a..1e56483f3 100644 --- a/web/app/assets/javascripts/notificationPanel.js +++ b/web/app/assets/javascripts/notificationPanel.js @@ -345,6 +345,7 @@ else if (type === context.JK.MessageType.RECORDING_MASTER_MIX_COMPLETE) { $notification.find('#div-actions').hide(); + logger.debug("context.jamClient.OnDownloadAvailable!") context.jamClient.OnDownloadAvailable(); // poke backend, letting it know a download is available } diff --git a/web/app/assets/javascripts/paginator.js b/web/app/assets/javascripts/paginator.js index 7a2405460..963aee1e3 100644 --- a/web/app/assets/javascripts/paginator.js +++ b/web/app/assets/javascripts/paginator.js @@ -9,6 +9,8 @@ context.JK.Paginator = { + $templatePaginator: null, + /** returns a jquery object that encapsulates pagination markup. * It's left to the caller to append it to the page as they like. * @param pages the number of pages @@ -18,6 +20,16 @@ */ create:function(totalEntries, perPage, currentPage, onPageSelected) { + if(this.$templatePaginator === null) { + this.$templatePaginator = $('#template-paginator') + if(this.$templatePaginator.length == 0) { + throw "no #template-paginator" + } + } + + var $templatePaginator = this.$templatePaginator; + + function calculatePages(total, perPageValue) { return Math.ceil(total / perPageValue); } @@ -32,13 +44,13 @@ onPageSelected(targetPage) .done(function(data, textStatus, jqXHR) { - totalEntries = parseInt(jqXHR.getResponseHeader('total-entries')); + totalEntries = data.total_entries || parseInt(jqXHR.getResponseHeader('total-entries')); pages = calculatePages(totalEntries, perPage); options = { pages: pages, currentPage: targetPage }; // recreate the pagination, and - var newPaginator = $(context._.template($('#template-paginator').html(), options, { variable: 'data' })); + var newPaginator = $(context._.template($templatePaginator.html(), options, { variable: 'data' })); registerEvents(newPaginator); paginator.replaceWith(newPaginator); paginator = newPaginator; @@ -90,7 +102,7 @@ var options = { pages: pages, currentPage: currentPage }; - var paginator = $(context._.template($('#template-paginator').html(), options, { variable: 'data' })); + var paginator = $(context._.template($templatePaginator.html(), options, { variable: 'data' })); registerEvents(paginator); diff --git a/web/app/assets/javascripts/recordingManager.js b/web/app/assets/javascripts/recordingManager.js index 75de3e2ef..30b10da4c 100644 --- a/web/app/assets/javascripts/recordingManager.js +++ b/web/app/assets/javascripts/recordingManager.js @@ -2,121 +2,178 @@ * Recording Manager viewer * Although multiple instances could be made, only one should be */ -(function(context, $) { +(function (context, $) { - "use strict"; + "use strict"; - context.JK = context.JK || {}; + context.JK = context.JK || {}; - context.JK.RecordingManager = function(){ + context.JK.RecordingManager = function (app) { - var $parentElement = $('#recording-manager-viewer'); + var $parentElement = $('#recording-manager-viewer'); - var logger = context.JK.logger; - if($parentElement.length == 0) { - logger.debug("no $parentElement specified in RecordingManager"); - } + var logger = context.JK.logger; + var EVENTS = context.JK.EVENTS; - var $downloadCommand = $('#recording-manager-download', $parentElement); - var $downloadPercent = $('#recording-manager-download .percent', $parentElement); - var $uploadCommand = $('#recording-manager-upload', $parentElement); - var $uploadPercent = $('#recording-manager-upload .percent', $parentElement); - var $convertCommand = $('#recording-manager-convert', $parentElement); - var $convertPercent = $('#recording-manager-convert .percent', $parentElement); - - // keys come from backend - var lookup = { - SyncDownload: { command: $downloadCommand, percent: $downloadPercent }, - SyncUpload: { command: $uploadCommand, percent: $uploadPercent }, - SyncConvert: { command: $convertCommand, percent: $convertPercent } - } - - var $self = $(this); - - - function renderStartCommand($command) { - $command.css('visibility', 'visible'); - } - - function renderEndCommand($command) { - $command.css('visibility', 'hidden'); - } - - function renderPercentage($percent, value) { - $percent.text(Math.round(value * 100)); - } - - function onStartCommand(id, type) { - var command = lookup[type]; - if(!command) { return } - - var existingCommandId = command.command.data('command-id'); - - if(existingCommandId && existingCommandId != id) { - renderEndCommand(command.command); - } - - command.command.data('command-id', id); - renderStartCommand(command.command); - renderPercentage(command.percent, 0); - } - - function onStopCommand(id, type, success, reason, detail) { - var command = lookup[type]; - if(!command) { return } - - var existingCommandId = command.command.data('command-id'); - - if(!existingCommandId) { - command.command.data('command-id', id); - renderStartCommand(command.command); - } - else if(existingCommandId && existingCommandId != id) { - renderEndCommand(command.command); - command.command.data('command-id', id); - renderStartCommand(command.command); - } - - renderPercentage(command.percent, 1); - renderEndCommand(command.command); - command.command.data('command-id', null); - } - - function onCommandProgress(id, type, progress) { - var command = lookup[type]; - if(!command) { return } - - var existingCommandId = command.command.data('command-id'); - - if(!existingCommandId) { - command.command.data('command-id', id); - renderStartCommand(command.command); - } - else if(existingCommandId && existingCommandId != id) { - renderEndCommand(command.command); - command.command.data('command-id', id); - renderStartCommand(command.command); - } - - renderPercentage(command.percent, progress); - } - - function onCommandsChanged(id, type) { - - } - - context.JK.RecordingManagerCommandStart = onStartCommand; - context.JK.RecordingManagerCommandStop = onStopCommand; - context.JK.RecordingManagerCommandProgress = onCommandProgress; - context.JK.RecordingManagerCommandsChanged = onCommandsChanged; - - context.jamClient.RegisterRecordingManagerCallbacks( - "JK.RecordingManagerCommandStart", - "JK.RecordingManagerCommandProgress", - "JK.RecordingManagerCommandStop", - "JK.RecordingManagerCommandsChanged" - ) - - return this; + if ($parentElement.length == 0) { + logger.debug("no $parentElement specified in RecordingManager"); } + + var $downloadCommand = $('#recording-manager-download', $parentElement); + var $downloadPercent = $('#recording-manager-download .percent', $parentElement); + var $uploadCommand = $('#recording-manager-upload', $parentElement); + var $uploadPercent = $('#recording-manager-upload .percent', $parentElement); + var $convertCommand = $('#recording-manager-convert', $parentElement); + var $convertPercent = $('#recording-manager-convert .percent', $parentElement); + var $fileManager = $('#recording-manager-launcher', $parentElement); + + if($fileManager.length == 0) {throw "no file manager element"; } + + $downloadCommand.data('command-type', 'download') + $uploadCommand.data('command-type', 'upload') + $convertCommand.data('command-type', 'convert') + + // keys come from backend + var lookup = { + SyncDownload: { command: $downloadCommand, percent: $downloadPercent}, + SyncUpload: { command: $uploadCommand, percent: $uploadPercent}, + SyncConvert: { command: $convertCommand, percent: $convertPercent} + } + + var $self = $(this); + + if (context.jamClient.IsNativeClient()) { + $parentElement.addClass('native-client') + } + + function renderStartCommand($command) { + $command.css('visibility', 'visible').addClass('running'); + $parentElement.addClass('running') + $(document).triggerHandler(EVENTS.FILE_MANAGER_CMD_START, $command.data()) + } + + function renderEndCommand($command) { + $command.css('visibility', 'hidden').removeClass('running') + if ($parentElement.find('.recording-manager-command.running').length == 0) { + $parentElement.removeClass('running') + } + $(document).triggerHandler(EVENTS.FILE_MANAGER_CMD_STOP, $command.data()) + } + + function renderPercentage($command, $percent, value) { + var percentage = Math.round(value * 100) + if(percentage > 100) percentage = 100; + + $percent.text(percentage); + $command.data('percentage', percentage) + $(document).triggerHandler(EVENTS.FILE_MANAGER_CMD_PROGRESS, $command.data()) + } + + function onStartCommand(id, type, metadata) { + var command = lookup[type]; + if (!command) { + return + } + + var existingCommandId = command.command.data('command-id'); + + if (existingCommandId && existingCommandId != id) { + renderEndCommand(command.command); + } + + command.command.data('command-id', id) + command.command.data('command-metadata', metadata) + command.command.data('command-success', null); + command.command.data('command-reason', null); + command.command.data('command-detail', null); + + renderStartCommand(command.command); + renderPercentage(command.command, command.percent, 0); + } + + function onStopCommand(id, type, success, reason, detail) { + var command = lookup[type]; + if (!command) { + return + } + + var existingCommandId = command.command.data('command-id'); + + + if (!existingCommandId) { + command.command.data('command-id', id); + renderStartCommand(command.command); + } + else if (existingCommandId && existingCommandId != id) { + renderEndCommand(command.command); + command.command.data('command-id', id); + renderStartCommand(command.command); + } + + + command.command.data('command-success', success); + command.command.data('command-reason', reason); + command.command.data('command-detail', detail); + + renderPercentage(command.command, command.percent, 1); + renderEndCommand(command.command); + command.command.data('command-id', null); + } + + function onCommandProgress(id, type, progress) { + var command = lookup[type]; + if (!command) { + return + } + + var existingCommandId = command.command.data('command-id'); + + if (!existingCommandId) { + command.command.data('command-id', id); + renderStartCommand(command.command); + } + else if (existingCommandId && existingCommandId != id) { + renderEndCommand(command.command); + command.command.data('command-id', id); + renderStartCommand(command.command); + } + + renderPercentage(command.command, command.percent, progress); + } + + function onCommandsChanged(id, type) { + + } + + function onAsapCommandStatus(id, type, metadata, reason) { + $(document).triggerHandler(EVENTS.FILE_MANAGER_CMD_ASAP_UPDATE, {commandMetadata: metadata, commandId: id, commandReason: reason}) + } + + function onClick() { + app.layout.showDialog('all-syncs-dialog') + return false; + } + + $fileManager.click(onClick) + $convertCommand.click(onClick) + $downloadCommand.click(onClick) + $uploadCommand.click(onClick) + + + context.JK.RecordingManagerCommandStart = onStartCommand; + context.JK.RecordingManagerCommandStop = onStopCommand; + context.JK.RecordingManagerCommandProgress = onCommandProgress; + context.JK.RecordingManagerCommandsChanged = onCommandsChanged; + context.JK.RecordingManagerAsapCommandStatus = onAsapCommandStatus; + + context.jamClient.RegisterRecordingManagerCallbacks( + "JK.RecordingManagerCommandStart", + "JK.RecordingManagerCommandProgress", + "JK.RecordingManagerCommandStop", + "JK.RecordingManagerCommandsChanged", + "JK.RecordingManagerAsapCommandStatus" + ) + + return this; + } })(window, jQuery); \ No newline at end of file diff --git a/web/app/assets/javascripts/recording_utils.js.coffee b/web/app/assets/javascripts/recording_utils.js.coffee new file mode 100644 index 000000000..3a6dbd002 --- /dev/null +++ b/web/app/assets/javascripts/recording_utils.js.coffee @@ -0,0 +1,141 @@ +# +# Common utility functions. +# + +$ = jQuery +context = window +context.JK ||= {}; + +class RecordingUtils + constructor: () -> + @logger = context.JK.logger + + init: () => + @templateHoverMix = $('#template-sync-viewer-hover-mix') + + mixStateErrorDescription: (mix) => + summary = '' + if mix.error.error_reason == 'mix-timeout' + summary = "The mix was started, but it has taken too long to for it to finish. The mix was started #{$.timeago(mix.error.error_detail)}. JamKazam employees have been notified of the issue." + else if mix.error.error_reason == 'unknown' + summary = "The reason the mix failed is unknown. JamKazam employees have been notified of the issue. " + else if mix.error.error_reason == 'unable to download' + summary = "The mixer could not fetch one of the tracks from JamKazam servers. JamKazam employees have been notified of the issue." + else if mix.error.error_reason == 'unable-parse-error-out' + summary = "The mixer failed, but it could not report what went wrong. JamKazam employees have been notified of the issue." + else if mix.error.error_reason == 'postback-ogg-mix-to-s3' or mix.error_reason == 'postback-mp3-mix-to-s3' + summary = "The mixer made the mix, but could not publish it. JamKazam employees have been notified of the issue." + else if mix.error.error_reason == 'unhandled-job-exception' + summary = "The mixer had an error while mixing. JamKazam employees have been notified of the issue." + else if mix.error.error_reason == 'unhandled-job-exception' + summary = "The mixer had an error while mixing. JamKazam employees have been notified of the issue." + summary + + mixStateDefinition: (mixState) => + + definition = switch mixState + when 'still-uploading' then "STILL UPLOADING means you or others in the recording have not uploaded enough information yet to make a mix." + when 'stream-mix' then "STREAM MIX means a user's real-time mix is available to listen to." + when 'discarded' then "DISCARDED means you chose to not keep this recording when the recording was over." + when 'mixed' then "MIXED means all tracks have been uploaded, and a final mix has been made." + when 'mixing' then "MIXING means all tracks have been uploaded, and the final mix is currently being made." + when 'waiting-to-mix' then "MIX QUEUED means all tracks have been uploaded, and the final mix should start being made very soon." + when 'error' then 'MIX FAILED means something went wrong with the mixer after all tracks were uploaded.' + else 'There is no help for this state' + + createMixInfo: (mix) => + mixStateMsg = 'UNKNOWN' + mixStateClass = 'unknown' + mixState = 'unknown' + + if mix? and mix.state? and !mix.fake + + # the '.download' property is only used for personalized views of a mix. + if !mix.download? mix.download.should_download + + if mix.state == 'error' + mixStateMsg = 'MIX FAILED' + mixStateClass = 'error' + mixState = 'error' + else if mix.state == 'stream-mix' + mixStateMsg = 'STREAM MIX' + mixStateClass = 'stream-mix' + mixState = 'stream-mix' + else if mix.state == 'waiting-to-mix' + mixStateMsg = 'MIX QUEUED' + mixStateClass = 'waiting-to-mix' + mixState = 'waiting-to-mix' + else if mix.state == 'mixing' + mixStateMsg = 'MIXING' + mixStateClass = 'mixing' + mixState = 'mixing' + else if mix.state == 'mixed' + mixStateMsg = 'MIXED' + mixStateClass = 'mixed' + mixState = 'mixed' + else + mixStateMsg = mix.state + mixStateClass = 'unknown' + mixState = 'unknown' + + + else + mixStateMsg = 'DISCARDED' + mixStateClass = 'discarded' + mixState = 'discarded' + else + mixStateMsg = 'STILL UPLOADING' + mixStateClass = 'still-uploading' + mixState = 'still-uploading' + + return { + mixStateMsg: mixStateMsg, + mixStateClass: mixStateClass, + mixState: mixState, + isError: mixState == 'error' + } + + onMixHover: () -> + $mix = $(this).closest('.mix') + mixStateInfo = $mix.data('mix-state') + viewContext = $mix.data('view-context') + if !mixStateInfo? # to support feed and syncs both using this same code, check .mix-state too + $mixState = $mix.find('.mix-state') + mixStateInfo = $mixState.data('mix-state') + + if !mixStateInfo? + logger.error('no mix-state anywhere', this) + throw 'no mix-state' + + mixStateMsg = mixStateInfo.mixStateMsg + mixStateClass = mixStateInfo.mixStateClass + mixState = mixStateInfo.mixState + + serverInfo = $mix.data('server-info') + + # lie if this is a virtualized mix (i.e., mix is created after recording is made) + mixState = 'still-uploading' if !serverInfo? or serverInfo.fake + + summary = '' + if mixState == 'still-uploading' + #summary = "No one in the recording has uploaded any files yet. Once tracks have been uploaded, a mix will be made." + else if mixState == 'discarded' + summary = "When this recording was made, you elected to not keep it. But at least one other person elected to keep it so your tracks are needed for the mix." + else if mixState == 'mixed' + #summary = 'All tracks have been uploaded, and a final mix has been made.' + else if mixState == 'stream-mix' + summary = 'A STREAM MIX the mix that someone heard in their headphones as the actual recording was made. In the case of a recording involving two or more people, it will contain any imperfections caused by the internet. Once the final, high-quality mix is available, we will automatically replace the stream mix with it.' + else if mixState == 'mixing' + #summary = 'All tracks have been uploaded, and the final mix is currently being made.' + else if mixState == 'waiting-to-mix' + #summary = 'All tracks have been uploaded, and the finale mix should start being made very soon.' + else if mixState == 'error' + summary = context.JK.RecordingUtils.mixStateErrorDescription(serverInfo) + + mixStateDefinition = context.JK.RecordingUtils.mixStateDefinition(mixState) + + context._.template(context.JK.RecordingUtils.templateHoverMix.html(), {summary: summary, mixStateDefinition: mixStateDefinition, mixStateMsg: mixStateMsg, mixStateClass: mixStateClass, viewContext: viewContext}, {variable: 'data'}) + + +# global instance +context.JK.RecordingUtils = new RecordingUtils() \ No newline at end of file diff --git a/web/app/assets/javascripts/scheduled_session.js b/web/app/assets/javascripts/scheduled_session.js.erb similarity index 93% rename from web/app/assets/javascripts/scheduled_session.js rename to web/app/assets/javascripts/scheduled_session.js.erb index c401eb4ed..e45059c72 100644 --- a/web/app/assets/javascripts/scheduled_session.js +++ b/web/app/assets/javascripts/scheduled_session.js.erb @@ -17,7 +17,7 @@ var MAX_GENRES = 1; var createSessionSettings = { - createType: 'start-scheduled', + createType: '<%= MusicSession::CREATE_TYPE_START_SCHEDULED %>', timezone: {}, recurring_mode: {}, language: {}, @@ -139,14 +139,14 @@ }); } - if (createSessionSettings.createType == 'start-scheduled' && createSessionSettings.session_count == 0) + if (createSessionSettings.createType == '<%= MusicSession::CREATE_TYPE_START_SCHEDULED%>' && createSessionSettings.session_count == 0) $editScheduledSessions.hide(); - else if (createSessionSettings.createType == 'start-scheduled' && createSessionSettings.session_count > 0) + else if (createSessionSettings.createType == '<%= MusicSession::CREATE_TYPE_START_SCHEDULED%>' && createSessionSettings.session_count > 0) $editScheduledSessions.show(); var $btnNext = $screen.find('.btn-next'); - if (step == STEP_SELECT_TYPE && createSessionSettings.createType == 'start-scheduled' && createSessionSettings.selectedSessionId == null) { + if (step == STEP_SELECT_TYPE && createSessionSettings.createType == '<%= MusicSession::CREATE_TYPE_START_SCHEDULED%>' && createSessionSettings.selectedSessionId == null) { $btnNext.addClass('disabled'); } else { @@ -223,11 +223,11 @@ startType = 'Now!'; createSessionSettings.startType = "START SESSION"; } - else if (createSessionSettings.createType == 'rsvp') { + else if (createSessionSettings.createType == '<%= MusicSession::CREATE_TYPE_RSVP %>') { startType = 'To be determined after RSVPs received'; createSessionSettings.startType = "PUBLISH SESSION"; } - else if (createSessionSettings.createType == 'schedule-future') { + else if (createSessionSettings.createType == '<%= MusicSession::CREATE_TYPE_SCHEDULE_FUTURE %>') { startType = createSessionSettings.startDate + ',' + createSessionSettings.startTime + ', ' + createSessionSettings.timezone.label; @@ -289,7 +289,7 @@ } $('#session-invited-disp').html(sessionInvitedString); - if (createSessionSettings.createType == 'start-scheduled') { + if (createSessionSettings.createType == '<%= MusicSession::CREATE_TYPE_START_SCHEDULED%>') { var session = scheduledSessions[createSessionSettings.selectedSessionId]; if (session.approved_rsvps.length > 0) { var instruments_me = []; @@ -348,7 +348,7 @@ } function beforeMoveStep1() { - if (createSessionSettings.createType == 'start-scheduled') { + if (createSessionSettings.createType == '<%= MusicSession::CREATE_TYPE_START_SCHEDULED%>') { createSessionSettings.selectedSessionId = $scheduledSessions.find('.iradio_minimal.checked input[name="scheduled-session-info"]').attr('data-session-id'); var session = scheduledSessions[createSessionSettings.selectedSessionId]; @@ -394,7 +394,7 @@ } return false; } - else if (createSessionSettings.createType == 'quick-start') { + else if (createSessionSettings.createType == '<%= MusicSession::CREATE_TYPE_QUICK_START %>') { createSessionSettings.genresValues = ['Pop']; createSessionSettings.genres = ['pop']; createSessionSettings.timezone.label = "(GMT-06:00) Central Time (US & Canada)"; @@ -604,7 +604,7 @@ var data = {}; - if (createSessionSettings.createType == 'start-scheduled') { + if (createSessionSettings.createType == '<%= MusicSession::CREATE_TYPE_START_SCHEDULED%>') { data = scheduledSessions[createSessionSettings.selectedSessionId]; } else { @@ -636,11 +636,11 @@ data.legal_policy = createSessionSettings.session_policy; data.legal_terms = true; data.language = createSessionSettings.language.value; - if (createSessionSettings.createType == 'quick-start' || createSessionSettings.createType == 'immediately') { + if (createSessionSettings.createType == '<%= MusicSession::CREATE_TYPE_QUICK_START %>' || createSessionSettings.createType == '<%= MusicSession::CREATE_TYPE_IMMEDIATE %>') { data.start = new Date().toDateString() + ' ' + context.JK.formatUtcTime(new Date(), false); data.duration = "60"; } - else if (createSessionSettings.createType == 'rsvp') { + else if (createSessionSettings.createType == '<%= MusicSession::CREATE_TYPE_RSVP %>') { data.start = ""; data.duration = "0"; } else { @@ -666,6 +666,7 @@ data.music_notations = createSessionSettings.notations; data.timezone = createSessionSettings.timezone.value; data.open_rsvps = createSessionSettings.open_rsvps; + data.create_type = createSessionSettings.createType; data.rsvp_slots = []; $.each(getCreatorInstruments(), function(index, instrument) { @@ -698,7 +699,7 @@ context.location = '/client#/session/' + sessionId; }; - if (createSessionSettings.createType == 'start-scheduled') { + if (createSessionSettings.createType == '<%= MusicSession::CREATE_TYPE_START_SCHEDULED%>') { joinSession(createSessionSettings.selectedSessionId); $('#create-session-buttons .btn-next').off('click'); } @@ -709,7 +710,7 @@ $('#create-session-buttons .btn-next').off('click'); var newSessionId = response.id; - if (createSessionSettings.createType == 'quick-start' || createSessionSettings.createType == "immediately") { + if (createSessionSettings.createType == '<%= MusicSession::CREATE_TYPE_QUICK_START %>' || createSessionSettings.createType == "immediately") { joinSession(newSessionId); } else { @@ -765,7 +766,7 @@ for (var i = 0; i < TOTAL_STEPS; i++) { var $eachStep = $sessionSteps.find('.session-stepnumber[data-step-number="' + i + '"]'); - if (createSessionSettings.createType == 'start-scheduled') { + if (createSessionSettings.createType == '<%= MusicSession::CREATE_TYPE_START_SCHEDULED%>') { if (step == STEP_SELECT_TYPE) { if (createSessionSettings.session_count > 0 && i == STEP_SELECT_CONFIRM) { $eachStep.on('click', next); @@ -777,7 +778,7 @@ $eachStep.addClass('session-stephover'); } } - else if (createSessionSettings.createType == 'quick-start') { + else if (createSessionSettings.createType == '<%= MusicSession::CREATE_TYPE_QUICK_START %>') { if (step == STEP_SELECT_CONFIRM && i == STEP_SELECT_TYPE) { $eachStep.on('click', back); $eachStep.addClass('session-stephover'); @@ -825,7 +826,7 @@ $btnBack.hide(); } - if (step == STEP_SELECT_TYPE && createSessionSettings.createType == 'start-scheduled' && createSessionSettings.selectedSessionId == null) { + if (step == STEP_SELECT_TYPE && createSessionSettings.createType == '<%= MusicSession::CREATE_TYPE_START_SCHEDULED%>' && createSessionSettings.selectedSessionId == null) { $btnNext.addClass('disabled'); } else { @@ -851,7 +852,7 @@ } if ($(this).is('.disabled')) return false; - if ($.inArray(createSessionSettings.createType, ['start-scheduled', 'quick-start']) > -1) + if ($.inArray(createSessionSettings.createType, ['<%= MusicSession::CREATE_TYPE_START_SCHEDULED%>', '<%= MusicSession::CREATE_TYPE_QUICK_START %>']) > -1) step = STEP_SELECT_TYPE; else step--; @@ -866,9 +867,9 @@ // will this option result in a session being started? function willOptionStartSession() { - return createSessionSettings.createType == 'start-scheduled' || - createSessionSettings.createType == 'immediately' || - createSessionSettings.createType == 'quick-start'; + return createSessionSettings.createType == '<%= MusicSession::CREATE_TYPE_START_SCHEDULED%>' || + createSessionSettings.createType == '<%= MusicSession::CREATE_TYPE_IMMEDIATE %>' || + createSessionSettings.createType == '<%= MusicSession::CREATE_TYPE_QUICK_START %>'; } function next(event) { @@ -888,7 +889,7 @@ } if ($(this).is('.disabled')) return false; - if ($.inArray(createSessionSettings.createType, ['start-scheduled', 'quick-start']) > -1) + if ($.inArray(createSessionSettings.createType, ['<%= MusicSession::CREATE_TYPE_START_SCHEDULED%>', '<%= MusicSession::CREATE_TYPE_QUICK_START %>']) > -1) step = STEP_SELECT_CONFIRM; else step++; @@ -1077,7 +1078,7 @@ $screen.find('#create-session-steps .session-stepnumber').off('click'); $screen.find('#create-session-steps .session-stepnumber').removeClass('session-stephover'); - if ($.inArray(createSessionSettings.createType, ['start-scheduled', 'quick-start']) > -1) { + if ($.inArray(createSessionSettings.createType, ['<%= MusicSession::CREATE_TYPE_START_SCHEDULED%>', '<%= MusicSession::CREATE_TYPE_QUICK_START %>']) > -1) { if (step == STEP_SELECT_CONFIRM) { for (var i = 1; i < 4; i++) { $screen.find('#create-session-steps .session-stepnumber[data-step-number="' + i + '"]').hide(); @@ -1092,11 +1093,11 @@ } $screen.find('#create-session-steps .session-stepnumber[data-step-number="4"]').html("5"); var $nextStep = $screen.find('#create-session-steps .session-stepnumber[data-step-number="1"]'); - if (createSessionSettings.createType == 'quick-start') { + if (createSessionSettings.createType == '<%= MusicSession::CREATE_TYPE_QUICK_START %>') { $nextStep.on('click', next); $nextStep.addClass('session-stephover') } - else if (createSessionSettings.createType == 'start-scheduled' && createSessionSettings.session_count > 0) { + else if (createSessionSettings.createType == '<%= MusicSession::CREATE_TYPE_START_SCHEDULED%>' && createSessionSettings.session_count > 0) { $nextStep.on('click', next); $nextStep.addClass('session-stephover') } @@ -1124,7 +1125,7 @@ createSessionSettings.createType = checkedType; - if (createSessionSettings.createType == 'start-scheduled') { + if (createSessionSettings.createType == '<%= MusicSession::CREATE_TYPE_START_SCHEDULED%>') { $('#start-scheduled-wrapper').show(); $('#schedule-future-wrapper').hide(); createSessionSettings.timezone = {}; @@ -1134,7 +1135,7 @@ createSessionSettings.musician_access = {}; createSessionSettings.fans_access = {}; } - else if (createSessionSettings.createType == 'schedule-future') { + else if (createSessionSettings.createType == '<%= MusicSession::CREATE_TYPE_SCHEDULE_FUTURE %>') { $('#start-scheduled-wrapper').hide(); $('#schedule-future-wrapper').show(); } @@ -1145,7 +1146,7 @@ } var $btnNext = $('#create-session-buttons .btn-next'); - if (step == STEP_SELECT_TYPE && createSessionSettings.createType == 'start-scheduled' && createSessionSettings.selectedSessionId == null) { + if (step == STEP_SELECT_TYPE && createSessionSettings.createType == '<%= MusicSession::CREATE_TYPE_START_SCHEDULED%>' && createSessionSettings.selectedSessionId == null) { $btnNext.addClass('disabled') } else { diff --git a/web/app/assets/javascripts/session.js b/web/app/assets/javascripts/session.js index 5add060ae..a49148209 100644 --- a/web/app/assets/javascripts/session.js +++ b/web/app/assets/javascripts/session.js @@ -4,6 +4,7 @@ context.JK = context.JK || {}; context.JK.SessionScreen = function(app) { + var EVENTS = context.JK.EVENTS; var gearUtils = context.JK.GearUtils; var sessionUtils = context.JK.SessionUtils; var logger = context.JK.logger; @@ -35,7 +36,8 @@ var rateSessionDialog = null; var friendInput = null; var sessionPageDone = null; - + var $recordingManagerViewer = null; + var $screen = null; var rest = context.JK.Rest(); var RENDER_SESSION_DELAY = 750; // When I need to render a session, I have to wait a bit for the mixers to be there. @@ -1348,7 +1350,11 @@ rest.getRecording( {id: recordingId} ) .done(function(recording) { recordingFinishedDialog.setRecording(recording); - app.layout.showDialog('recordingFinished'); + app.layout.showDialog('recordingFinished').one(EVENTS.DIALOG_CLOSED, function(e, data) { + if(data.result && data.result.keep){ + context.JK.prodBubble($recordingManagerViewer, 'file-manager-poke', {}, {positions:['top', 'left', 'right', 'bottom'], offsetParent: $screen.parent()}) + } + }) }) .fail(app.ajaxError); } @@ -1462,6 +1468,8 @@ }; app.bindScreen('session', screenBindings); + $recordingManagerViewer = $('#recording-manager-viewer'); + $screen = $('#session-screen'); // make sure no previous plays are still going on by accident context.jamClient.SessionStopPlay(); if(context.jamClient.SessionRemoveAllPlayTracks) { diff --git a/web/app/assets/javascripts/sessionList.js b/web/app/assets/javascripts/sessionList.js index d58218dbf..a54ba7cec 100644 --- a/web/app/assets/javascripts/sessionList.js +++ b/web/app/assets/javascripts/sessionList.js @@ -122,6 +122,18 @@ $('a.more.slots', $parentRow).click(toggleSlots); $('a.more.rsvps', $parentRow).click(toggleRsvps); + $('.notation-link').click(function(evt) { + rest.getMusicNotation($(this).attr('data-notation-id')) + .done(function(result) { + window.open(result, '_blank'); + }) + .fail(function(xhr, textStatus, errorMessage) { + if (xhr.status === 403) { + app.ajaxError(xhr, textStatus, errorMessage); + } + }); + }); + if (showJoinLink) { // wire up the Join Link to the T&Cs dialog @@ -429,8 +441,9 @@ function createNotationFile(notation) { var notationVals = { notation_id: notation.id, - file_url: notation.file_url, - file_name: notation.file_name + file_url: notation.viewable ? notation.file_url + '?target=_blank' : '#', + file_name: notation.file_name, + link_class: notation.viewable ? '' : 'notation-link' }; return context.JK.fillTemplate($notationFileTemplate.html(), notationVals); diff --git a/web/app/assets/javascripts/sessionModel.js b/web/app/assets/javascripts/sessionModel.js index 82a8724b0..9bfb3409d 100644 --- a/web/app/assets/javascripts/sessionModel.js +++ b/web/app/assets/javascripts/sessionModel.js @@ -31,6 +31,7 @@ var sessionPageEnterDeferred = null; var sessionPageEnterTimeout = null; var startTime = null; + var joinDeferred = null; server.registerOnSocketClosed(onWebsocketDisconnected); @@ -123,10 +124,18 @@ */ function joinSession(sessionId) { logger.debug("SessionModel.joinSession(" + sessionId + ")"); - var deferred = joinSessionRest(sessionId); + joinDeferred = joinSessionRest(sessionId); + + joinDeferred + .done(function(response){ + + if(!inSession()) { + // the user has left the session before they got joined. We need to issue a leave again to the server to make sure they are out + logger.debug("user left before fully joined to session. telling server again that they have left") + leaveSessionRest(response.id); + return; + } - deferred - .done(function(response){ logger.debug("calling jamClient.JoinSession"); // on temporary disconnect scenarios, a user may already be in a session when they enter this path // so we avoid double counting @@ -153,7 +162,7 @@ updateCurrentSession(null); }); - return deferred; + return joinDeferred; } function performLeaveSession(deferred) { @@ -251,13 +260,15 @@ } // universal place to clean up, reset items - function sessionEnded() { + // fullyJoined means the user stayed in the screen until they had a successful rest.joinSession + // you might not get a fully joined if you join/leave really quickly before the REST API completes + function sessionEnded(fullyJoined) { //cleanup server.unregisterMessageCallback(context.JK.MessageType.SESSION_JOIN, trackChanges); server.unregisterMessageCallback(context.JK.MessageType.SESSION_DEPART, trackChanges); server.unregisterMessageCallback(context.JK.MessageType.TRACKS_CHANGED, trackChanges); - server.registerMessageCallback(context.JK.MessageType.HEARTBEAT_ACK, trackChanges); + server.unregisterMessageCallback(context.JK.MessageType.HEARTBEAT_ACK, trackChanges); if(sessionPageEnterDeferred != null) { sessionPageEnterDeferred.reject('session_over'); @@ -265,7 +276,10 @@ } userTracks = null; startTime = null; - $(document).trigger(EVENTS.SESSION_ENDED, {session: {id: currentSessionId}}); + joinDeferred = null; + if(fullyJoined) { + $(document).trigger(EVENTS.SESSION_ENDED, {session: {id: currentSessionId}}); + } currentSessionId = null; } @@ -280,8 +294,8 @@ currentSession = sessionData; // the 'beforeUpdate != null' makes sure we only do a clean up one time internally - if(sessionData == null && beforeUpdate != null) { - sessionEnded(); + if(sessionData == null) { + sessionEnded(beforeUpdate != null); } } @@ -538,51 +552,65 @@ if(inSession() && text == "RebuildAudioIoControl") { - if(sessionPageEnterDeferred) { - // this means we are still waiting for the BACKEND_MIXER_CHANGE that indicates we have user tracks built-out/ready - - // we will get at least one BACKEND_MIXER_CHANGE that corresponds to the backend doing a 'audio pause', which won't matter much - // so we need to check that we actaully have userTracks before considering ourselves done - var inputTracks = context.JK.TrackHelpers.getUserTracks(context.jamClient); - if(inputTracks.length > 0) { - logger.debug("obtained tracks at start of session") - sessionPageEnterDeferred.resolve(inputTracks); - sessionPageEnterDeferred = null; - } - - return; - } - // the backend will send these events rapid-fire back to back. // the server can still perform correctly, but it is nicer to wait 100 ms to let them all fall through if(backendMixerAlertThrottleTimer) {clearTimeout(backendMixerAlertThrottleTimer);} backendMixerAlertThrottleTimer = setTimeout(function() { - // this is a local change to our tracks. we need to tell the server about our updated track information - var inputTracks = context.JK.TrackHelpers.getUserTracks(context.jamClient); - // create a trackSync request based on backend data - var syncTrackRequest = {}; - syncTrackRequest.client_id = app.clientId; - syncTrackRequest.tracks = inputTracks; - syncTrackRequest.id = id(); + if(sessionPageEnterDeferred) { + // this means we are still waiting for the BACKEND_MIXER_CHANGE that indicates we have user tracks built-out/ready - rest.putTrackSyncChange(syncTrackRequest) - .done(function() { - }) - .fail(function(jqXHR) { - if(jqXHR.status != 404) { - app.notify({ - "title": "Can't Sync Local Tracks", - "text": "The client is unable to sync local track information with the server. You should rejoin the session to ensure a good experience.", - "icon_url": "/assets/content/icon_alert_big.png" - }); - } - else { - logger.debug("Unable to sync local tracks because session is gone.") + // we will get at least one BACKEND_MIXER_CHANGE that corresponds to the backend doing a 'audio pause', which won't matter much + // so we need to check that we actaully have userTracks before considering ourselves done + var inputTracks = context.JK.TrackHelpers.getUserTracks(context.jamClient); + if(inputTracks.length > 0) { + logger.debug("obtained tracks at start of session") + sessionPageEnterDeferred.resolve(inputTracks); + sessionPageEnterDeferred = null; + } + + return; + } + + // wait until we are fully in session before trying to sync tracks to server + if(joinDeferred) { + joinDeferred.done(function() { + + // double check that we are in session, since a bunch could have happened since then + if(!inSession()) { + logger.debug("dropping queued up sync tracks because no longer in session"); + return; } + // this is a local change to our tracks. we need to tell the server about our updated track information + var inputTracks = context.JK.TrackHelpers.getUserTracks(context.jamClient); + + // create a trackSync request based on backend data + var syncTrackRequest = {}; + syncTrackRequest.client_id = app.clientId; + syncTrackRequest.tracks = inputTracks; + syncTrackRequest.id = id(); + + rest.putTrackSyncChange(syncTrackRequest) + .done(function() { + }) + .fail(function(jqXHR) { + if(jqXHR.status != 404) { + app.notify({ + "title": "Can't Sync Local Tracks", + "text": "The client is unable to sync local track information with the server. You should rejoin the session to ensure a good experience.", + "icon_url": "/assets/content/icon_alert_big.png" + }); + } + else { + logger.debug("Unable to sync local tracks because session is gone.") + } + + }) }) + } + }, 100); } else if(inSession() && (text == 'RebuildMediaControl' || text == 'RebuildRemoteUserControl')) { diff --git a/web/app/assets/javascripts/session_utils.js b/web/app/assets/javascripts/session_utils.js index 725da855d..482aaeab1 100644 --- a/web/app/assets/javascripts/session_utils.js +++ b/web/app/assets/javascripts/session_utils.js @@ -77,34 +77,34 @@ description = 'me'; } else if (!full_score) { - latencyDescription = LATENCY.UNKNOWN.description; + latencyDescription = LATENCY.UNKNOWN.description; latencyStyle = LATENCY.UNKNOWN.style; - iconName = 'purple' - description = 'missing' + iconName = 'purple'; + description = 'missing'; } else if (full_score <= LATENCY.GOOD.max) { latencyDescription = LATENCY.GOOD.description; latencyStyle = LATENCY.GOOD.style; - iconName = 'green' - description = 'good' + iconName = 'green'; + description = 'good'; } else if (full_score <= LATENCY.MEDIUM.max) { latencyDescription = LATENCY.MEDIUM.description; latencyStyle = LATENCY.MEDIUM.style; iconName = 'yellow'; - description = 'fair' + description = 'fair'; } else if (full_score <= LATENCY.POOR.max) { latencyDescription = LATENCY.POOR.description; latencyStyle = LATENCY.POOR.style; - iconName = 'red' - description = 'poor' + iconName = 'red'; + description = 'poor'; } else { latencyStyle = LATENCY.UNACCEPTABLE.style; latencyDescription = LATENCY.UNACCEPTABLE.description; - iconName = 'blue' - description = 'unacceptable' + iconName = 'blue'; + description = 'unacceptable'; } return { diff --git a/web/app/assets/javascripts/sync_viewer.js.coffee b/web/app/assets/javascripts/sync_viewer.js.coffee new file mode 100644 index 000000000..51dd2637f --- /dev/null +++ b/web/app/assets/javascripts/sync_viewer.js.coffee @@ -0,0 +1,915 @@ +$ = jQuery +context = window +context.JK ||= {}; + +context.JK.SyncViewer = class SyncViewer + constructor: (@app) -> + @EVENTS = context.JK.EVENTS + @rest = context.JK.Rest() + @logger = context.JK.logger + @recordingUtils = context.JK.RecordingUtils + @since = 0 + @limit = 20 + @showing = false + @downloadCommandId = null + @downloadMetadata = null + @uploadCommandId = null + @uploadMetadata = null; + + init: () => + @root = $($('#template-sync-viewer').html()) + @inProgress = @root.find('.in-progress') + @downloadProgress = @inProgress.find('.download-progress') + @uploadProgress = @inProgress.find('.upload-progress') + @list = @root.find('.list') + @logList = @root.find('.log-list') + @templateRecordedTrack = $('#template-sync-viewer-recorded-track') + @templateStreamMix = $('#template-sync-viewer-stream-mix') + @templateMix = $('#template-sync-viewer-mix') + @templateNoSyncs = $('#template-sync-viewer-no-syncs') + @templateRecordingWrapperDetails = $('#template-sync-viewer-recording-wrapper-details') + @templateHoverRecordedTrack = $('#template-sync-viewer-hover-recorded-track') + @templateHoverMix = $('#template-sync-viewer-hover-mix') + @templateDownloadReset = $('#template-sync-viewer-download-progress-reset') + @templateUploadReset = $('#template-sync-viewer-upload-progress-reset') + @templateGenericCommand = $('#template-sync-viewer-generic-command') + @templateRecordedTrackCommand = $('#template-sync-viewer-recorded-track-command') + @templateLogItem = $('#template-sync-viewer-log-item') + @tabSelectors = @root.find('.dialog-tabs .tab') + @tabs = @root.find('.tab-content') + @logBadge = @tabSelectors.find('.badge') + @paginator = @root.find('.paginator-holder') + + @uploadStates = { + unknown: 'unknown', + too_many_upload_failures: 'too-many-upload-failures', + me_upload_soon: 'me-upload-soon', + them_upload_soon: 'them-upload-soon' + missing: 'missing', + me_uploaded: 'me-uploaded', + them_uploaded: 'them-uploaded' + } + @clientStates = { + unknown: 'unknown', + too_many_uploads: 'too-many-downloads', + hq: 'hq', + sq: 'sq', + missing: 'missing', + discarded: 'discarded' + } + + throw "no sync-viewer" if not @root.exists() + throw "no in-progress" if not @inProgress.exists() + throw "no list" if not @list.exists() + throw "no recorded track template" if not @templateRecordedTrack.exists() + throw "no stream mix template" if not @templateStreamMix.exists() + throw "no empty syncs template" if not @templateNoSyncs.exists() + + $(document).on(@EVENTS.FILE_MANAGER_CMD_START, this.fileManagerCmdStart) + $(document).on(@EVENTS.FILE_MANAGER_CMD_STOP, this.fileManagerCmdStop) + $(document).on(@EVENTS.FILE_MANAGER_CMD_PROGRESS, this.fileManagerCmdProgress) + $(document).on(@EVENTS.FILE_MANAGER_CMD_ASAP_UPDATE, this.fileManagerAsapCommandStatus) + + @tabSelectors.click((e) => + $tabSelected = $(e.target).closest('a.tab') + purpose = $tabSelected.attr('purpose') + + $otherTabSelectors = @tabSelectors.not('[purpose="' + purpose + '"]') + $otherTabs = @tabs.not('[purpose="' + purpose + '"]') + $tab = @tabs.filter('[purpose="' + purpose + '"]') + + $otherTabs.hide(); + $tab.show() + + $otherTabSelectors.removeClass('selected'); + $tabSelected.addClass('selected'); + + if purpose == 'log' + @logBadge.hide() + ) + + onShow: () => + @showing = true + this.load() + + onHide: () => + @showing = false + #$(document).off(@EVENTS.FILE_MANAGER_CMD_START, this.fileManagerCmdStart) + #$(document).off(@EVENTS.FILE_MANAGER_CMD_STOP, this.fileManagerCmdStop) + #$(document).off(@EVENTS.FILE_MANAGER_CMD_PROGRESS, this.fileManagerCmdProgress) + + getUserSyncs: (page) => + @rest.getUserSyncs({since: page * @limit, limit: @limit}) + .done(this.processUserSyncs) + + + load: () => + @list.empty() + @since = 0 + + this.renderHeader() + + this.getUserSyncs(0) + .done((response) => + $paginator = context.JK.Paginator.create(response.total_entries, @limit, 0, this.getUserSyncs) + @paginator.empty().append($paginator); + ) + + + renderHeader: () => + recordingManagerState = context.jamClient.GetRecordingManagerState() + if recordingManagerState.running + @uploadProgress.removeClass('quiet paused busy') + @downloadProgress.removeClass('quiet paused busy') + + if recordingManagerState.current_download + @downloadProgress.addClass('busy') + else + @downloadProgress.addClass('quiet') + @downloadProgress.find('.busy').empty() + + if recordingManagerState.current_upload + @uploadProgress.addClass('busy') + else + @uploadProgress.addClass('quiet') + @uploadProgress.find('.busy').empty() + else + @downloadProgress.removeClass('quiet paused busy').addClass('paused') + @uploadProgress.removeClass('quiet paused busy').addClass('paused') + @downloadProgress.find('.busy').empty() + @uploadProgress.find('.busy').empty() + + updateMixState: ($mix) => + serverInfo = $mix.data('server-info') + + mixInfo = @recordingUtils.createMixInfo(serverInfo) + + $mixState = $mix.find('.mix-state') + $mixStateMsg = $mixState.find('.msg') + $mixStateProgress = $mixState.find('.progress') + $mixState.removeClass('still-uploading discarded unknown mixed mixing waiting-to-mix error stream-mix').addClass(mixInfo.mixStateClass).attr('data-state', mixInfo.mixState).data('mix-state', mixInfo) + $mixStateMsg.text(mixInfo.mixStateMsg) + $mixStateProgress.css('width', '0') + + updateStreamMixState: ($streamMix) => + clientInfo = $streamMix.data('client-info') + serverInfo = $streamMix.data('server-info') + + # determine client state + clientStateMsg = 'UNKNOWN' + clientStateClass = 'unknown' + clientState = @clientStates.unknown + + if clientInfo? + if clientInfo.local_state == 'COMPRESSED' + clientStateMsg = 'STREAM QUALITY' + clientStateClass = 'sq' + clientState = @clientStates.sq + else if clientInfo.local_state == 'UNCOMPRESSED' + clientStateMsg = 'STREAM QUALITY' + clientStateClass = 'sq' + clientState = @clientStates.sq + else if clientInfo.local_state == 'MISSING' + clientStateMsg = 'MISSING' + clientStateClass = 'missing' + clientState = @clientStates.missing + + # determine upload state + uploadStateMsg = 'UNKNOWN' + uploadStateClass = 'unknown' + uploadState = @uploadStates.unknown + + if !serverInfo.fully_uploaded + if serverInfo.upload.too_many_upload_failures + uploadStateMsg = 'UPLOAD FAILURE' + uploadStateClass = 'error' + uploadState = @uploadStates.too_many_upload_failures + else + if clientInfo? + if clientInfo.local_state == 'UNCOMPRESSED' or clientInfo.local_state == 'COMPRESSED' + uploadStateMsg = 'PENDING UPLOAD' + uploadStateClass = 'upload-soon' + uploadState = @uploadStates.me_upload_soon + else + uploadStateMsg = 'MISSING' + uploadStateClass = 'missing' + uploadState = @uploadStates.missing + else + uploadStateMsg = 'MISSING' + uploadStateClass = 'missing' + uploadState = @uploadStates.missing + else + uploadStateMsg = 'UPLOADED' + uploadStateClass = 'uploaded' + uploadState = @uploadStates.me_uploaded + + $clientState = $streamMix.find('.client-state') + $clientStateMsg = $clientState.find('.msg') + $clientStateProgress = $clientState.find('.progress') + $uploadState = $streamMix.find('.upload-state') + $uploadStateMsg = $uploadState.find('.msg') + $uploadStateProgress = $uploadState.find('.progress') + + $clientState.removeClass('discarded missing sq hq unknown error').addClass(clientStateClass).attr('data-state', clientState).data('custom-class', clientStateClass) + $clientStateMsg.text(clientStateMsg) + $clientStateProgress.css('width', '0') + $uploadState.removeClass('upload-soon error unknown missing uploaded').addClass(uploadStateClass).attr('data-state', uploadState).data('custom-class', uploadStateClass) + $uploadStateMsg.text(uploadStateMsg) + $uploadStateProgress.css('width', '0') + + updateTrackState: ($track) => + clientInfo = $track.data('client-info') + serverInfo = $track.data('server-info') + + # determine client state + clientStateMsg = 'UNKNOWN' + clientStateClass = 'unknown' + clientState = @clientStates.unknown + + if serverInfo.download.should_download + if serverInfo.download.too_many_downloads + clientStateMsg = 'EXCESS DOWNLOADS' + clientStateClass = 'error' + clientState = @clientStates.too_many_uploads + else + if clientInfo? + if clientInfo.local_state == 'HQ' + clientStateMsg = 'HIGHEST QUALITY' + clientStateClass = 'hq' + clientState = @clientStates.hq + else + clientStateMsg = 'STREAM QUALITY' + clientStateClass = 'sq' + clientState = @clientStates.sq + else + clientStateMsg = 'MISSING' + clientStateClass = 'missing' + clientState = @clientStates.missing + else + clientStateMsg = 'DISCARDED' + clientStateClass = 'discarded' + clientState = @clientStates.discarded + + # determine upload state + uploadStateMsg = 'UNKNOWN' + uploadStateClass = 'unknown' + uploadState = @uploadStates.unknown + + if !serverInfo.fully_uploaded + if serverInfo.upload.too_many_upload_failures + uploadStateMsg = 'UPLOAD FAILURE' + uploadStateClass = 'error' + uploadState = @uploadStates.too_many_upload_failures + else + if serverInfo.user.id == context.JK.currentUserId + if clientInfo? + if clientInfo.local_state == 'HQ' + uploadStateMsg = 'PENDING UPLOAD' + uploadStateClass = 'upload-soon' + uploadState = @uploadStates.me_upload_soon + else + uploadStateMsg = 'MISSING' + uploadStateClass = 'missing' + uploadState = @uploadStates.missing + else + uploadStateMsg = 'MISSING' + uploadStateClass = 'missing' + uploadState = @uploadStates.missing + else + uploadStateMsg = 'PENDING UPLOAD' + uploadStateClass = 'upload-soon' + uploadState = @uploadStates.them_upload_soon + else + uploadStateMsg = 'UPLOADED' + uploadStateClass = 'uploaded' + if serverInfo.user.id == context.JK.currentUserId + uploadState = @uploadStates.me_uploaded + else + uploadState = @uploadStates.them_uploaded + + $clientState = $track.find('.client-state') + $clientStateMsg = $clientState.find('.msg') + $clientStateProgress = $clientState.find('.progress') + $uploadState = $track.find('.upload-state') + $uploadStateMsg = $uploadState.find('.msg') + $uploadStateProgress = $uploadState.find('.progress') + + $clientState.removeClass('discarded missing sq hq unknown error').addClass(clientStateClass).attr('data-state', clientState).data('custom-class', clientStateClass) + $clientStateMsg.text(clientStateMsg) + $clientStateProgress.css('width', '0') + $uploadState.removeClass('upload-soon error unknown missing uploaded').addClass(uploadStateClass).attr('data-state', uploadState).data('custom-class', uploadStateClass) + $uploadStateMsg.text(uploadStateMsg) + $uploadStateProgress.css('width', '0') + + associateClientInfo: (recording) => + for clientInfo in recording.local_tracks + $track = @list.find(".recorded-track[data-recording-id='#{recording.recording_id}'][data-client-track-id='#{clientInfo.client_track_id}']") + $track.data('client-info', clientInfo) + + $track = @list.find(".mix[data-recording-id='#{recording.recording_id}']") + $track.data('client-info', recording.mix) + + $track = @list.find(".stream-mix[data-recording-id='#{recording.recording_id}']") + $track.data('client-info', recording.stream_mix) + + displayStreamMixHover: ($streamMix) => + $clientState = $streamMix.find('.client-state') + $clientStateMsg = $clientState.find('.msg') + clientStateClass = $clientState.data('custom-class') + clientState = $clientState.attr('data-state') + clientInfo = $streamMix.data('client-info') + + $uploadState = $streamMix.find('.upload-state') + $uploadStateMsg = $uploadState.find('.msg') + uploadStateClass = $uploadState.data('custom-class') + uploadState = $uploadState.attr('data-state') + serverInfo = $streamMix.data('server-info') + + # decide on special case strings first + + summary = '' + if clientState == @clientStates.sq && uploadState == @uploadStates.me_upload_soon + summary = "We will attempt to upload your stream mix so that others can hear the recording on the JamKazam site, even before the final mix is done. It will upload shortly." + else if clientState == @clientStates.sq && uploadState == @uploadStates.me_uploaded + # we have the SQ version, and the other user has uploaded the HQ version... it's coming soon! + summary = "We already uploaded your stream mix so that others can hear the recording on the JamKazam site, even before the final mix is done. Since it's uploaded, there is nothing else left to do with the stream mix... you're all done!" + else if clientState == @clientStates.missing + summary = "You do not have the stream mix on your computer anymore. This can happen if you change the computer that you run JamKazam on. It's important to note that once a final mix for the recording is available, there is no value in the stream mix." + + clientStateDefinition = switch clientState + when @clientStates.sq then "The stream mix is always STREAM QUALITY, because it's the version of the recording that you heard in your earphones as you made the recording." + when @clientStates.missing then "MISSING means you do not have the stream mix anymore." + else 'There is no help for this state' + + uploadStateDefinition = switch uploadState + when @uploadStates.too_many_upload_failures then "Failed attempts at uploading this stream mix has happened an unusually large times. No more uploads will be attempted." + when @uploadStates.me_upload_soon then "PENDING UPLOAD means your JamKazam application will upload this stream mix soon." + when @uploadStates.me_uploaded then "UPLOADED means you have already uploaded this stream mix." + when @uploadStates.missing then "MISSING means your JamKazam application does not have this stream mix, and the server does not either." + + context._.template(@templateHoverRecordedTrack.html(), + {summary: summary, + clientStateDefinition: clientStateDefinition, + uploadStateDefinition: uploadStateDefinition, + clientStateMsg: $clientStateMsg.text(), + uploadStateMsg: $uploadStateMsg.text(), + clientStateClass: clientStateClass, + uploadStateClass: uploadStateClass} + {variable: 'data'}) + + displayTrackHover: ($recordedTrack) => + $clientState = $recordedTrack.find('.client-state') + $clientStateMsg = $clientState.find('.msg') + clientStateClass = $clientState.data('custom-class') + clientState = $clientState.attr('data-state') + clientInfo = $recordedTrack.data('client-info') + + $uploadState = $recordedTrack.find('.upload-state') + $uploadStateMsg = $uploadState.find('.msg') + uploadStateClass = $uploadState.data('custom-class') + uploadState = $uploadState.attr('data-state') + serverInfo = $recordedTrack.data('server-info') + + # decide on special case strings first + + summary = '' + if clientState == @clientStates.sq && uploadState == @uploadStates.them_upload_soon + # we have the SQ version, and the other user hasn't uploaded it yet + summary = "#{serverInfo.user.name} has not yet uploaded the high-quality version of this track. Once he or she does, JamKazam will download it and replace your stream-quality version." + else if clientState == @clientStates.missing && uploadState == @uploadStates.them_upload_soon + # we don't have any version of the track at all, and the other user hasn't uploaded it yet + summary = "#{serverInfo.user.name} has not yet uploaded the high-quality version of this track. Once he or she does, JamKazam will download it and this track will no longer be missing." + else if clientState == @clientStates.sq && uploadState == @uploadStates.them_uploaded + # we have the SQ version, and the other user has uploaded the HQ version... it's coming soon! + summary = "#{serverInfo.user.name} has uploaded the high-quality version of this track. JamKazam will soon download it and replace your stream-quality version." + else if clientState == @clientStates.missing && uploadState == @uploadStates.them_uploaded + # we have no version of the track at all, and the other user has uploaded the HQ version... it's coming soon! + summary = "#{serverInfo.user.name} has uploaded the high-quality version of this track. JamKazam will soon restore it and then this track will no longer be missing." + else if clientState == @clientStates.sq && uploadState == @uploadStates.me_uploaded + # we have the SQ version, and the other user has uploaded the HQ version... it's coming soon! + summary = "You have previously uploaded the high-quality version of this track. JamKazam will soon restore it and replace your stream-quality version." + else if clientState == @clientStates.missing && uploadState == @uploadStates.me_uploaded + # we have no version of the track at all, and the other user has uploaded the HQ version... it's coming soon! + summary = "You have previously uploaded the high-quality version of this track. JamKazam will soon restore it and then this track will no longer be missing." + else if clientState == @clientStates.discarded && (uploadState == @uploadStates.me_uploaded or uploadState == @uploadStates.them_uploaded) + # we decided not to keep the recording... so it's important to clarify why they are seeing it at all + summary = "When this recording was made, you elected to not keep it. JamKazam already uploaded your high-quality tracks for the recording, because at least one other person decided to keep the recording and needs your tracks to make a high-quality mix." + else if clientState == @clientStates.discarded + # we decided not to keep the recording... so it's important to clarify why they are seeing it at all + summary = "When this recording was made, you elected to not keep it. JamKazam will still try to upload your high-quality tracks for the recording, because at least one other person decided to keep the recording and needs your tracks to make a high-quality mix." + else if clientState == @clientStates.hq and ( uploadState == @uploadStates.them_uploaded or uploadState == @uploadStates.me_uploaded ) + summary = "Both you and the JamKazam server have the high-quality version of this track. Once all the other tracks for this recording are also synchronized, then the final mix can be made." + + clientStateDefinition = switch clientState + when @clientStates.too_many_downloads then "This track has been downloaded an unusually large number of times. No more downloads are allowed." + when @clientStates.hq then "HIGHEST QUALITY means you have the original version of this track, as recorded by the user that made it." + when @clientStates.sq then "STREAM QUALITY means you have the version of the track that you received over the internet in real-time." + when @clientStates.missing then "MISSING means you do not have this track anymore." + when @clientStates.discarded then "DISCARDED means you chose to not keep this recording when the recording was over." + else 'There is no help for this state' + + uploadStateDefinition = switch uploadState + when @uploadStates.too_many_upload_failures then "Failed attempts at uploading this track has happened an unusually large times. No more uploads will be attempted." + when @uploadStates.me_upload_soon then "PENDING UPLOAD means your JamKazam application will upload this track soon." + when @uploadStates.them_up_soon then "PENDING UPLOAD means #{serverInfo.user.name} will upload this track soon." + when @uploadStates.me_uploaded then "UPLOADED means you have already uploaded this track." + when @uploadStates.them_uploaded then "UPLOADED means #{serverInfo.user.name} has already uploaded this track." + when @uploadStates.missing then "MISSING means your JamKazam application does not have this track, and the server does not either." + + context._.template(@templateHoverRecordedTrack.html(), + {summary: summary, + clientStateDefinition: clientStateDefinition, + uploadStateDefinition: uploadStateDefinition, + clientStateMsg: $clientStateMsg.text(), + uploadStateMsg: $uploadStateMsg.text(), + clientStateClass: clientStateClass, + uploadStateClass: uploadStateClass} + {variable: 'data'}) + + onHoverOfStateIndicator: () -> + $recordedTrack = $(this).closest('.recorded-track.sync') + self = $recordedTrack.data('sync-viewer') + self.displayTrackHover($recordedTrack) + + onStreamMixHover: () -> + $streamMix = $(this).closest('.stream-mix.sync') + self = $streamMix.data('sync-viewer') + self.displayStreamMixHover($streamMix) + + resetDownloadProgress: () => + @downloadProgress + + resetUploadProgress: () => + @uploadProgress + + sendCommand: ($retry, cmd) => + + if context.JK.CurrentSessionModel and context.JK.CurrentSessionModel.inSession() + context.JK.confirmBubble($retry, 'sync-viewer-paused', {}, {offsetParent: $retry.closest('.dialog')}) + else + context.jamClient.OnTrySyncCommand(cmd) + context.JK.confirmBubble($retry, 'sync-viewer-retry', {}, {offsetParent: $retry.closest('.dialog')}) + + + retryDownloadRecordedTrack: (e) => + $retry = $(e.target) + $track = $retry.closest('.recorded-track') + serverInfo = $track.data('server-info') + + this.sendCommand($retry, { + type: 'recorded_track', + action: 'download' + queue: 'download', + recording_id: serverInfo.recording_id + track_id: serverInfo.client_track_id + }) + + return false + + retryUploadRecordedTrack: (e) => + $retry = $(e.target) + $track = $retry.closest('.recorded-track') + serverInfo = $track.data('server-info') + + this.sendCommand($retry, { + type: 'recorded_track', + action: 'upload' + queue: 'upload', + recording_id: serverInfo.recording_id + track_id: serverInfo.client_track_id + }) + + return false + + createMix: (userSync) => + recordingInfo = null + if userSync == 'fake' + recordingInfo = arguments[1] + userSync = { recording_id: recordingInfo.id, duration: recordingInfo.duration, fake:true } + $mix = $(context._.template(@templateMix.html(), userSync, {variable: 'data'})) + else + $mix = $(context._.template(@templateMix.html(), userSync, {variable: 'data'})) + + $mix.data('server-info', userSync) + $mix.data('sync-viewer', this) + $mix.data('view-context', 'sync') + $mixState = $mix.find('.mix-state') + this.updateMixState($mix) + context.JK.hoverBubble($mixState, @recordingUtils.onMixHover, {width:'450px', closeWhenOthersOpen: true, positions:['left'], trigger:['hoverIntent', 'none']}) + $mix + + createTrack: (userSync) => + $track = $(context._.template(@templateRecordedTrack.html(), userSync, {variable: 'data'})) + $track.data('server-info', userSync) + $track.data('sync-viewer', this) + $clientState = $track.find('.client-state') + $uploadState = $track.find('.upload-state') + $clientState.find('.retry').click(this.retryDownloadRecordedTrack) + $uploadState.find('.retry').click(this.retryUploadRecordedTrack) + context.JK.bindHoverEvents($track) + context.JK.bindInstrumentHover($track, {positions:['top'], shrinkToFit: true}); + context.JK.hoverBubble($clientState, this.onHoverOfStateIndicator, {width:'450px', closeWhenOthersOpen: true, positions:['left']}) + context.JK.hoverBubble($uploadState, this.onHoverOfStateIndicator, {width:'450px', closeWhenOthersOpen: true, positions:['right']}) + $clientState.addClass('is-native-client') if context.jamClient.IsNativeClient() + $uploadState.addClass('is-native-client') if context.jamClient.IsNativeClient() + $track + + createStreamMix: (userSync) => + $track = $(context._.template(@templateStreamMix.html(), userSync, {variable: 'data'})) + $track.data('server-info', userSync) + $track.data('sync-viewer', this) + $clientState = $track.find('.client-state') + $uploadState = $track.find('.upload-state') + $uploadState.find('.retry').click(this.retryUploadRecordedTrack) + context.JK.hoverBubble($clientState, this.onStreamMixHover, {width:'450px', closeWhenOthersOpen: true, positions:['left']}) + context.JK.hoverBubble($uploadState, this.onStreamMixHover, {width:'450px', closeWhenOthersOpen: true, positions:['right']}) + $clientState.addClass('is-native-client') if context.jamClient.IsNativeClient() + $uploadState.addClass('is-native-client') if context.jamClient.IsNativeClient() + $track + + exportRecording: (e) => + $export = $(e.target) + if context.JK.CurrentSessionModel and context.JK.CurrentSessionModel.inSession() + context.JK.confirmBubble($export, 'sync-viewer-paused', {}, {offsetParent: $export.closest('.dialog')}) + return + + recordingId = $export.closest('.details').attr('data-recording-id') + if !recordingId? or recordingId == "" + throw "exportRecording can't find data-recording-id" + + cmd = + { type: 'export_recording', + action: 'export' + queue: 'upload', + recording_id: recordingId} + + logger.debug("enqueueing export") + context.jamClient.OnTrySyncCommand(cmd) + return false; + + + createRecordingWrapper: ($toWrap, recordingInfo) => + recordingInfo.recording_landing_url = "/recordings/#{recordingInfo.id}" + $wrapperDetails = $(context._.template(@templateRecordingWrapperDetails.html(), recordingInfo, {variable: 'data'})) + $wrapper = $('
') + $toWrap.wrapAll($wrapper) + $wrapper = $toWrap.closest('.recording-holder') + $wrapperDetails.prependTo($wrapper) + $mix = $wrapper.find('.mix.sync') + if $mix.length == 0 + # create a virtual mix so that the UI is consistent + $wrapper.append(this.createMix('fake', recordingInfo)) + + $wrapper.find('a.export').click(this.exportRecording) + + separateByRecording: () => + $recordedTracks = @list.find('.sync') + + currentRecordingId = null; + + queue = $([]); + + for recordedTrack in $recordedTracks + $recordedTrack = $(recordedTrack) + recordingId = $recordedTrack.attr('data-recording-id') + if recordingId != currentRecordingId + if queue.length > 0 + this.createRecordingWrapper(queue, $(queue.get(0)).data('server-info').recording) + queue = $([]) + + currentRecordingId = recordingId + queue = queue.add(recordedTrack) + + if queue.length > 0 + this.createRecordingWrapper(queue, $(queue.get(0)).data('server-info').recording) + + processUserSyncs: (response) => + + @list.empty() + + # check if no entries + if @since == 0 and response.entries.length == 0 + @list.append(context._.template(@templateNoSyncs.html(), {}, {variable: 'data'})) + else + recordings = {} # collect all unique recording + for userSync in response.entries + if userSync.type == 'recorded_track' + @list.append(this.createTrack(userSync)) + else if userSync.type == 'mix' + @list.append(this.createMix(userSync)) + else if userSync.type == 'stream_mix' + @list.append(this.createStreamMix(userSync)) + + recordings[userSync.recording_id] = userSync.recording + recordingsToResolve = [] + # resolve each track against backend data: + for recording_id, recording of recordings + recordingsToResolve.push(recording) + + clientRecordings = context.jamClient.GetLocalRecordingState(recordings: recordingsToResolve) + + if clientRecordings.error? + alert(clientRecordings.error) + else + this.associateClientInfo(turp) for turp in clientRecordings.recordings + + for track in @list.find('.recorded-track.sync') + this.updateTrackState($(track)) + for streamMix in @list.find('.stream-mix.sync') + this.updateStreamMixState($(streamMix)) + + this.separateByRecording() + + @since = response.next + + resolveTrack: (commandMetadata) => + recordingId = commandMetadata['recording_id'] + clientTrackId = commandMetadata['track_id'] + + matchingTrack = @list.find(".recorded-track[data-recording-id='#{recordingId}'][data-client-track-id='#{clientTrackId}']") + if matchingTrack.length == 0 + return @rest.getRecordedTrack({recording_id: recordingId, track_id: clientTrackId}) + else + deferred = $.Deferred(); + deferred.resolve(matchingTrack.data('server-info')) + return deferred + + renderFullUploadRecordedTrack: (serverInfo) => + $track = $(context._.template(@templateRecordedTrackCommand.html(), $.extend(serverInfo, {action:'UPLOADING'}), {variable: 'data'})) + $busy = @uploadProgress.find('.busy') + $busy.empty().append($track) + @uploadProgress.find('.progress').css('width', '0%') + + renderFullDownloadRecordedTrack: (serverInfo) => + $track = $(context._.template(@templateRecordedTrackCommand.html(), $.extend(serverInfo, {action:'DOWNLOADING'}), {variable: 'data'})) + $busy = @downloadProgress.find('.busy') + $busy.empty().append($track) + @downloadProgress.find('.progress').css('width', '0%') + + # this will either show a generic placeholder, or immediately show the whole track + renderDownloadRecordedTrack: (commandId, commandMetadata) => + # try to find the info in the list; if we can't find it, then resolve it + deferred = this.resolveTrack(commandMetadata) + if deferred.state() == 'pending' + this.renderGeneric(commandId, 'download', commandMetadata) + + deferred.done(this.renderFullDownloadRecordedTrack).fail(()=> @logger.error("unable to fetch recorded_track info") ) + + + renderUploadRecordedTrack: (commandId, commandMetadata) => + # try to find the info in the list; if we can't find it, then resolve it + deferred = this.resolveTrack(commandMetadata) + if deferred.state() == 'pending' + this.renderGeneric(commandId, 'upload', commandMetadata) + + deferred.done(this.renderFullUploadRecordedTrack).fail(()=> @logger.error("unable to fetch recorded_track info") ) + + renderGeneric: (commandId, category, commandMetadata) => + commandMetadata.displayType = this.displayName(commandMetadata) + + $generic = $(context._.template(@templateGenericCommand.html(), commandMetadata, {variable: 'data'})) + if category == 'download' + $busy = @downloadProgress.find('.busy') + $busy.empty().append($generic) + else if category == 'upload' + $busy = @uploadProgress.find('.busy') + $busy.empty().append($generic) + else + @logger.error("unknown category #{category}") + + + renderStartCommand: (commandId, commandType, commandMetadata) => + + #console.log("renderStartCommand", arguments) + unless commandMetadata? + managerState = context.jamClient.GetRecordingManagerState() + if commandType == 'download' + commandMetadata = managerState.current_download + else if commandType == 'upload' + commandMetadata = managerState.current_upload + else + @logger.error("unknown commandType #{commandType}") + + unless commandMetadata? + # we still have no metadata. we have to give up + @logger.error("no metadata found for current command #{commandId} #{commandType}. bailing out") + return + + if commandMetadata.queue == 'download' + @downloadCommandId = commandId + @downloadMetadata = commandMetadata + @downloadProgress.removeClass('quiet paused busy') + @downloadProgress.addClass('busy') + if commandMetadata.type == 'recorded_track' and commandMetadata.action == 'download' + this.renderDownloadRecordedTrack(commandId, commandMetadata) + else + this.renderGeneric(commandId, 'download', commandMetadata) + else if commandMetadata.queue == 'upload' + @uploadCommandId = commandId + @uploadMetadata = commandMetadata + @uploadProgress.removeClass('quiet paused busy') + @uploadProgress.addClass('busy') + if commandMetadata.type == 'recorded_track' and commandMetadata.action == 'upload' + this.renderUploadRecordedTrack(commandId, commandMetadata) + else + this.renderGeneric(commandId, 'upload', commandMetadata) + + renderSingleRecording: (userSyncs) => + return if userSyncs.entries.length == 0 + clientRecordings = context.jamClient.GetLocalRecordingState(recordings: [userSyncs.entries[0].recording]) + for userSync in userSyncs.entries + if userSync.type == 'recorded_track' + $track = @list.find(".sync[data-id='#{userSync.id}']") + continue if $track.length == 0 + $track.data('server-info', userSync) + this.associateClientInfo(clientRecordings.recordings[0]) + this.updateTrackState($track) + else if userSync.type == 'mix' + # check if there is a virtual mix 1st; if so, update it + $mix = @list.find(".mix.virtual[data-recording-id='#{userSync.recording.id}']") + if $mix.length == 0 + $mix = @list.find(".sync[data-id='#{userSync.id}']") + continue if $mix.length == 0 + $newMix = this.createMix(userSync) + this.associateClientInfo(clientRecordings.recordings[0]) + $mix.replaceWith($newMix) + else if userSync.type == 'stream_mix' + $streamMix = @list.find(".sync[data-id='#{userSync.id}']") + continue if $streamMix.length == 0 + $streamMix.data('server-info', userSync) + this.associateClientInfo(clientRecordings.recordings[0]) + this.updateStreamMixState($streamMix) + + updateSingleRecording: (recording_id) => + @rest.getUserSyncs({recording_id: recording_id}).done(this.renderSingleRecording) + + updateSingleRecordedTrack: ($track) => + serverInfo = $track.data('server-info') + @rest.getUserSync({user_sync_id: serverInfo.id}) + .done((userSync) => + # associate new server-info with this track + $track.data('server-info', userSync) + # associate new client-info with this track + clientRecordings = context.jamClient.GetLocalRecordingState(recordings: [userSync.recording]) + this.associateClientInfo(clientRecordings.recordings[0]) + + this.updateTrackState($track) + ) + .fail(@app.ajaxError) + + updateProgressOnSync: ($track, queue, percentage) => + state = if queue == 'upload' then '.upload-state' else '.client-state' + $progress = $track.find("#{state} .progress") + $progress.css('width', percentage + '%') + + renderFinishCommand: (commandId, data) => + + reason = data.commandReason + success = data.commandSuccess + + if commandId == @downloadCommandId + + this.logResult(@downloadMetadata, success, reason, false) + recordingId = @downloadMetadata['recording_id'] + this.updateSingleRecording(recordingId) if recordingId? + + else if commandId == @uploadCommandId + + this.logResult(@uploadMetadata, success, reason, false) + recordingId = @uploadMetadata['recording_id'] + this.updateSingleRecording(recordingId) if recordingId? + + else + @logger.error("unknown commandId in renderFinishCommand") + + # refresh the header when done. we need to leave this callback to let the command fully switch to off + #setTimeout(this.renderHeader, 1) + + this.renderHeader() + + renderPercentage: (commandId, commandType, percentage) => + + if commandId == @downloadCommandId + $progress = @downloadProgress.find('.progress') + $progress.css('width', percentage + '%') + + if @downloadMetadata.type == 'recorded_track' + clientTrackId = @downloadMetadata['track_id'] + recordingId = @downloadMetadata['recording_id'] + $matchingTrack = @list.find(".recorded-track.sync[data-recording-id='#{recordingId}'][data-client-track-id='#{clientTrackId}']") + if $matchingTrack.length > 0 + this.updateProgressOnSync($matchingTrack, 'download', percentage) + + else if commandId == @uploadCommandId + $progress = @uploadProgress.find('.progress') + $progress.css('width', percentage + '%') + + if @uploadMetadata.type == 'recorded_track' and @uploadMetadata.action == 'upload' + clientTrackId = @uploadMetadata['track_id'] + recordingId = @uploadMetadata['recording_id'] + $matchingTrack = @list.find(".recorded-track.sync[data-recording-id='#{recordingId}'][data-client-track-id='#{clientTrackId}']") + if $matchingTrack.length > 0 + this.updateProgressOnSync($matchingTrack, 'upload', percentage) + else if @uploadMetadata.type == 'stream_mix' and @uploadMetadata.action == 'upload' + recordingId = @uploadMetadata['recording_id'] + $matchingStreamMix = @list.find(".stream-mix.sync[data-recording-id='#{recordingId}']") + if $matchingStreamMix.length > 0 + this.updateProgressOnSync($matchingStreamMix, 'upload', percentage) + + else + @logger.error("unknown commandId in renderFinishCommand") + + + fileManagerCmdStart: (e, data) => + #console.log("fileManagerCmdStart", data) + commandId = data['commandId'] + commandType = data['commandType'] + commandMetadata = data['commandMetadata'] + + category = commandType == 'download' ? 'download' : 'upload' + + if category == 'download' && (@downloadCommandId != null && @downloadCommandId != commandId) + @logger.warn("received command-start for download but previous command did not send stop") + this.renderFinishCommand(commandId, category) + else if @uploadCommandId != null && @uploadCommandId != commandId + @logger.warn("received command-start for upload but previous command did not send stop") + this.renderFinishCommand(commandId, category) + + this.renderStartCommand(commandId, commandType, commandMetadata) + + fileManagerCmdStop: (e, data) => + #console.log("fileManagerCmdStop", data) + commandId = data['commandId'] + + if commandId == @downloadCommandId + category = 'download' + this.renderFinishCommand(commandId, data) + @downloadCommandId = null + @downloadMetadata = null; + else if commandId == @uploadCommandId + category = 'upload' + this.renderFinishCommand(commandId, data) + @uploadCommandId = null + @uploadMetadata = null; + else + @logger.warn("received command-stop for unknown command: #{commandId} #{@downloadCommandId} #{@uploadCommandId}" ) + + fileManagerCmdProgress: (e, data) => + #console.log("fileManagerCmdProgress", data) + commandId = data['commandId'] + + if commandId == @downloadCommandId + category = 'download' + this.renderPercentage(commandId, category, data.percentage) + + else if commandId == @uploadCommandId + category = 'upload' + this.renderPercentage(commandId, category, data.percentage) + else + @logger.warn("received command-percentage for unknown command") + + fileManagerAsapCommandStatus: (e, data) => + this.logResult(data.commandMetadata, false, data.commandReason, true) + + displayName: (metadata) => + if metadata.type == 'recorded_track' && metadata.action == 'download' + return 'DOWNLOADING TRACK' + else if metadata.type == 'recorded_track' && metadata.action == 'upload' + return 'UPLOADING TRACK' + else if metadata.type == 'mix' && metadata.action == 'download' + return 'DOWNLOADING MIX' + else if metadata.type == 'recorded_track' && metadata.action == 'convert' + return 'COMPRESSING TRACK' + else if metadata.type == 'recorded_track' && metadata.action == 'delete' + return 'CLEANUP TRACK' + else if metadata.type == 'stream_mix' && metadata.action == 'upload' + return 'UPLOADING STREAM MIX' + else + return "#{metadata.action} #{metadata.type}".toUpperCase() + + + shownTab: () => + @tabSelectors.filter('.selected') + + # create a log in the Log tab + logResult: (metadata, success, reason, isAsap) => + + # if an error comes in, and the log tab is not already showing, increment the badge + if not success and (!@showing || this.shownTab().attr('purpose') != 'log') + @logBadge.css('display', 'inline-block') + if @showing # don't do animation unless user can see it + @logBadge.pulse({'background-color' : '#868686'}, {pulses: 2}, () => @logBadge.css('background-color', '#980006')) + + displayReason = switch reason + when 'no-match-in-queue' then 'restart JamKazam' + when 'already-done' then 'ignored, already done' + when 'failed-convert' then 'failed previously' + else reason + + displaySuccess = if success then 'yes' else 'no' + $log = context._.template(@templateLogItem.html(), {isAsap: isAsap, command: this.displayName(metadata), success: success, displaySuccess: displaySuccess, detail: displayReason, when: new Date()}, {variable: 'data'}) + + @logList.prepend($log) + + + diff --git a/web/app/assets/javascripts/utils.js b/web/app/assets/javascripts/utils.js index 2afdd2f53..993d2139c 100644 --- a/web/app/assets/javascripts/utils.js +++ b/web/app/assets/javascripts/utils.js @@ -78,7 +78,7 @@ "trombone": "trombone", "trumpet": "trumpet", "tuba": "tuba", - "ukulele": "ukelele", + "ukulele": "ukulele", "upright bass": "upright_bass", "viola": "viola", "violin": "violin", @@ -95,6 +95,12 @@ instrumentIconMap256[instrumentId] = {asset: "/assets/content/icon_instrument_" + icon + "256.png", name: instrumentId}; }); + context.JK.helpBubbleFunctionHelper = function(originalFunc) { + var helpText = originalFunc.apply(this); + var holder = $('
'); + holder.append(helpText); + return holder; + } /** * Associates a help bubble on hover (by default) with the specified $element, using jquery.bt.js (BeautyTips) * @param $element The element that should show the help when hovered @@ -111,18 +117,48 @@ } $element.on('remove', function() { - $element.btOff(); + $element.btOff(); // if the element goes away for some reason, get rid of the bubble too }) + var holder = null; + if (context._.isFunction(templateName)) { + holder = function wrapper() { + return context.JK.helpBubbleFunctionHelper.apply(this, [templateName]) + } + } + else { + var $template = $('#template-help-' + templateName) + if($template.length == 0) { + var helpText = templateName; + } + else { + var helpText = context._.template($template.html(), data, { variable: 'data' }); + } - var $template = $('#template-help-' + templateName); - if($template.length == 0) throw "no template by the name " + templateName; - var helpText = context._.template($template.html(), data, { variable: 'data' }); - var holder = $('
'); - holder.append(helpText); - context.JK.hoverBubble($element, helpText, options); + holder = $('
'); + holder = holder.append(helpText).html() + } + + context.JK.hoverBubble($element, holder, options); } + /** + * Meant to show a little bubble to confirm something happened, in a way less obtrusive than a app.notify + * @param $element The element that should show the help when hovered + * @param templateName the name of the help template (without the '#template-help' prefix). Add to _help.html.erb + * @param data (optional) data for your template, if applicable + * @param options (optional) You can override the default BeautyTips options: https://github.com/dillon-sellars/BeautyTips + */ + context.JK.confirmBubble = function($element, templateName, data, options) { + if(!options) options = {}; + options.spikeGirth = 0; + options.spikeLength = 0; + options.shrinkToFit = true + options.duration = 3000 + options.cornerRadius = 5 + + return context.JK.prodBubble($element, templateName, data, options); + } /** * Associates a help bubble immediately with the specified $element, using jquery.bt.js (BeautyTips) * By 'prod' it means to literally prod the user, to make them aware of something important because they did something else @@ -162,6 +198,7 @@ $element.btOff(); } }) + return $element; } /** * Associates a bubble on hover (by default) with the specified $element, using jquery.bt.js (BeautyTips) @@ -203,7 +240,14 @@ options = defaultOpts; } - $element.bt(text, options); + if(typeof text != 'string') { + options.contentSelector = text; + $element.bt(options); + } + else { + $element.bt(text, options); + } + } context.JK.bindProfileClickEvents = function($parent, dialogsToClose) { @@ -524,7 +568,7 @@ } context.JK.formatDateTime = function (dateString) { - var date = new Date(dateString); + var date = dateString instanceof Date ? dateString : new Date(dateString); return context.JK.padString(date.getMonth() + 1, 2) + "/" + context.JK.padString(date.getDate(), 2) + "/" + date.getFullYear() + " - " + date.toLocaleTimeString(); } diff --git a/web/app/assets/javascripts/web/web.js b/web/app/assets/javascripts/web/web.js index a3d159a15..f3e91abd4 100644 --- a/web/app/assets/javascripts/web/web.js +++ b/web/app/assets/javascripts/web/web.js @@ -19,6 +19,7 @@ //= require jquery.ba-bbq //= require jquery.icheck //= require jquery.bt +//= require jquery.exists //= require AAA_Log //= require AAC_underscore //= require alert @@ -47,6 +48,7 @@ //= require ga //= require jam_rest //= require session_utils +//= require recording_utils //= require helpBubbleHelper //= require facebook_rest //= require landing/init diff --git a/web/app/assets/stylesheets/client/account.css.scss b/web/app/assets/stylesheets/client/account.css.scss index 81d700c12..74183442c 100644 --- a/web/app/assets/stylesheets/client/account.css.scss +++ b/web/app/assets/stylesheets/client/account.css.scss @@ -115,7 +115,7 @@ background-color: #C5C5C5; border: medium none; box-shadow: 2px 2px 3px 0 #888888 inset; - color: #666666; + color: #000; font-size: 14px; height: 178px; overflow: auto; diff --git a/web/app/assets/stylesheets/client/band.css.scss b/web/app/assets/stylesheets/client/band.css.scss index 4da4130d3..d2e8504d5 100644 --- a/web/app/assets/stylesheets/client/band.css.scss +++ b/web/app/assets/stylesheets/client/band.css.scss @@ -13,7 +13,7 @@ border:none; -webkit-box-shadow: inset 2px 2px 3px 0px #888; box-shadow: inset 2px 2px 3px 0px #888; - color:#666; + color:#000; overflow:auto; font-size:14px; } diff --git a/web/app/assets/stylesheets/client/client.css b/web/app/assets/stylesheets/client/client.css index 68b4073ce..75d262cbe 100644 --- a/web/app/assets/stylesheets/client/client.css +++ b/web/app/assets/stylesheets/client/client.css @@ -60,4 +60,5 @@ *= require web/sessions *= require jquery.Jcrop *= require icheck/minimal/minimal + *= require users/syncViewer */ \ No newline at end of file diff --git a/web/app/assets/stylesheets/client/common.css.scss b/web/app/assets/stylesheets/client/common.css.scss index fdd5027de..856ad5f21 100644 --- a/web/app/assets/stylesheets/client/common.css.scss +++ b/web/app/assets/stylesheets/client/common.css.scss @@ -44,6 +44,12 @@ $latencyBadgePoor: #980006; $latencyBadgeUnacceptable: #868686; $latencyBadgeUnknown: #868686; +$good: #71a43b; +$unknown: #868686; +$poor: #980006; +$error: #980006; +$fair: #cc9900; + @mixin border_box_sizing { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; @@ -65,6 +71,55 @@ $latencyBadgeUnknown: #868686; background-clip: padding-box; /* stops bg color from leaking outside the border: */ } +/** IE10 and above only */ +@mixin vertical-align-row { + display: -webkit-box; + display: -moz-box; + display: -ms-flexbox; + display: -webkit-flex; + display: flex; + + -webkit-flex-pack:space-around; + -webkit-justify-content:space-around; + -moz-justify-content:space-around; + -ms-flex-pack:space-around; + justify-content:space-around; + + -webkit-flex-line-pack:center; + -ms-flex-line-pack:center; + -webkit-align-content:center; + align-content:center; + + -webkit-flex-direction:row; + -moz-flex-direction:row; + -ms-flex-direction:row; + flex-direction:row; +} + +@mixin vertical-align-column { + display: -webkit-box; + display: -moz-box; + display: -ms-flexbox; + display: -webkit-flex; + display: flex; + + -webkit-flex-pack:space-around; + -webkit-justify-content:space-around; + -moz-justify-content:space-around; + -ms-flex-pack:space-around; + justify-content:space-around; + + -webkit-flex-line-pack:center; + -ms-flex-line-pack:center; + -webkit-align-content:center; + align-content:center; + + -webkit-flex-direction:column; + -moz-flex-direction:column; + -ms-flex-direction:column; + flex-direction:column; +} + // Single side border-radius @mixin border-top-radius($radius) { @@ -122,3 +177,115 @@ $latencyBadgeUnknown: #868686; } } + + +@mixin client-state-box { + .client-state { + position:relative; + text-align:center; + padding:3px; + @include border_box_sizing; + color:white; + + &.unknown { + background-color: $error; + } + + &.error { + background-color: $error; + &.is-native-client { .retry { display:inline-block; } } + } + + &.hq { + background-color: $good; + } + + &.sq { + background-color: $good; + &.is-native-client { .retry { display:inline-block; } } + } + + &.missing { + background-color: $error; + &.is-native-client { .retry { display:inline-block; } } + } + + &.discarded { + background-color: $unknown; + } + + .retry { + display:none; + position:absolute; + line-height:28px; + top:4px; + right:8px; + z-index:1; + } + } +} + +@mixin upload-state-box { + + .upload-state { + position:relative; + text-align:center; + padding:3px; + @include border_box_sizing; + color:white; + + &.unknown { + background-color: $unknown; + } + + &.error { + background-color: $error; + &.is-native-client { .retry { display:inline-block; } } + } + + &.missing { + background-color: $error; + } + + &.upload-soon { + background-color: $fair; + &.is-native-client { .retry { display:inline-block; } } + } + + &.uploaded { + background-color: $good; + } + + .retry { + display:none; + position:absolute; + line-height:28px; + visibility: middle; + top:4px; + right:8px; + } + } +} + + +@mixin mix-state-box { + + .mix-state { + position:relative; + text-align:center; + padding:3px; + @include border_box_sizing; + color:white; + + &.still-uploading { background-color: $fair; } + &.discard {background-color: $unknown; } + &.unknown { background-color: $unknown; } + &.error { background-color: $error; } + &.mixed { background-color: $good; } + &.mixing {background-color: $good; } + &.waiting-to-mix {background-color: $good; } + &.stream-mix { background-color: $fair; } + } +} + + diff --git a/web/app/assets/stylesheets/client/content.css.scss b/web/app/assets/stylesheets/client/content.css.scss index 68434368c..9bee28a72 100644 --- a/web/app/assets/stylesheets/client/content.css.scss +++ b/web/app/assets/stylesheets/client/content.css.scss @@ -222,7 +222,6 @@ border:none; -webkit-box-shadow: inset 2px 2px 3px 0px #888; box-shadow: inset 2px 2px 3px 0px #888; - color:#666; } } diff --git a/web/app/assets/stylesheets/client/createSession.css.scss b/web/app/assets/stylesheets/client/createSession.css.scss index a4cbec1dd..83eeba993 100644 --- a/web/app/assets/stylesheets/client/createSession.css.scss +++ b/web/app/assets/stylesheets/client/createSession.css.scss @@ -209,7 +209,7 @@ border: none; -webkit-box-shadow: inset 2px 2px 3px 0px #888; box-shadow: inset 2px 2px 3px 0px #888; - color: #666; + color: #000; overflow: auto; font-size: 14px; diff --git a/web/app/assets/stylesheets/client/ftue.css.scss b/web/app/assets/stylesheets/client/ftue.css.scss index ef81f1a39..1082b843e 100644 --- a/web/app/assets/stylesheets/client/ftue.css.scss +++ b/web/app/assets/stylesheets/client/ftue.css.scss @@ -528,14 +528,14 @@ div[layout-id="ftue3"] { border:none; -webkit-box-shadow: inset 2px 2px 3px 0px #888; box-shadow: inset 2px 2px 3px 0px #888; - color:#666; + color:#000; overflow:auto; font-size:14px; } .ftue-instrumentlist select, .ftue-instrumentlist .easydropdown { width:100%; - color:#666; + color:#000; } table.audiogeartable { diff --git a/web/app/assets/stylesheets/client/help.css.scss b/web/app/assets/stylesheets/client/help.css.scss index 32074d802..4755d711f 100644 --- a/web/app/assets/stylesheets/client/help.css.scss +++ b/web/app/assets/stylesheets/client/help.css.scss @@ -1,4 +1,6 @@ -.screen, body.web { +@import "client/common"; + +body.jam, body.web, .dialog{ .bt-wrapper { .bt-content { @@ -43,6 +45,110 @@ } } + .help-hover-recorded-tracks, .help-hover-stream-mix { + + font-size:12px; + padding:5px; + @include border_box_sizing; + width:450px; + + .sync-definition { + padding:0 10px; + } + + .client-box { + float:left; + width:50%; + min-width:200px; + @include border_box_sizing; + } + + .upload-box { + float:left; + width:50%; + min-width:200px; + @include border_box_sizing; + + } + + @include client-state-box; + .client-state { + width:100%; + margin:5px 0 10px; + font-size:16px; + } + + @include upload-state-box; + .upload-state { + width: 100%; + margin:5px 0 10px; + font-size:16px; + } + + .client-state-info, .upload-state-info { + text-align:center; + font-size:12px; + } + + .client-state-definition { + margin-bottom:20px; + } + + .upload-state-definition { + margin-bottom:20px; + } + .summary { + margin-bottom:10px; + + .title { + text-align:center; + font-size:16px; + margin:10px 0 5px; + } + } + } + + .help-hover-mix { + + font-size:12px; + padding:5px; + @include border_box_sizing; + width:450px; + + .mix-box { + float:left; + width:100%; + min-width:400px; + @include border_box_sizing; + } + + @include mix-state-box; + .mix-state { + width:100%; + margin:5px 0 10px; + font-size:16px; + //background-color:black ! important; + } + + .mix-state-info { + text-align:center; + font-size:12px; + } + + .mix-state-definition { + margin-bottom:20px; + } + + .summary { + margin-bottom:10px; + + .title { + text-align:center; + font-size:16px; + margin:10px 0 5px; + } + } + } } } } \ No newline at end of file diff --git a/web/app/assets/stylesheets/client/hoverBubble.css.scss b/web/app/assets/stylesheets/client/hoverBubble.css.scss index a53fff3b8..b8d6ec315 100644 --- a/web/app/assets/stylesheets/client/hoverBubble.css.scss +++ b/web/app/assets/stylesheets/client/hoverBubble.css.scss @@ -1,3 +1,5 @@ +@import 'common'; + .bubble { width:350px; min-height:200px; @@ -74,4 +76,48 @@ -moz-border-radius:12px; border-radius:12px; } + + .musician-latency { + margin-right:35px; + position:relative; + width:350px; + } + + .latency-holder { + position:absolute; + width:100%; + text-align:center; + } + + .latency { + min-width: 50px; + display:inline-block; + padding:4px; + font-family:Arial, Helvetica, sans-serif; + font-weight:200; + font-size:11px; + text-align:center; + @include border-radius(2px); + color:white; + } + + .latency-unknown { + background-color:$latencyBadgeUnknown; + } + + .latency-unacceptable { + background-color:$latencyBadgeUnacceptable; + } + + .latency-good { + background-color:$latencyBadgeGood; + } + + .latency-fair{ + background-color:$latencyBadgeFair; + } + + .latency-poor { + background-color:$latencyBadgePoor; + } } \ No newline at end of file diff --git a/web/app/assets/stylesheets/client/jamkazam.css.scss b/web/app/assets/stylesheets/client/jamkazam.css.scss index 46df063a6..8ccd7a022 100644 --- a/web/app/assets/stylesheets/client/jamkazam.css.scss +++ b/web/app/assets/stylesheets/client/jamkazam.css.scss @@ -302,7 +302,6 @@ input[type="button"] { .search-box { float:left; - width:140px; margin-left: 10px; -webkit-border-radius: 6px; border-radius: 6px; @@ -321,7 +320,6 @@ input[type="button"] { input[type="text"], input[type="password"]{ background-color:$ColorTextBoxBackground; border:none; - color:#666; padding:3px; font-size:15px; } diff --git a/web/app/assets/stylesheets/client/recordingManager.css.scss b/web/app/assets/stylesheets/client/recordingManager.css.scss index 5aa630d64..729e19b1e 100644 --- a/web/app/assets/stylesheets/client/recordingManager.css.scss +++ b/web/app/assets/stylesheets/client/recordingManager.css.scss @@ -2,12 +2,34 @@ color: #CCCCCC; font-size: 11px; - margin: 0 auto; + margin: -5px auto 0 ; position: absolute; text-align: center; left: 17%; width: 50%; - z-index:-1; + + // if it's the native client, then show the File Manager span. if it's not (normal browser) hide it. + // even if it's the native client, once a command is running, hide File Manager + &.native-client { + .recording-manager-launcher { + display:inline-block; + } + &.running { + .recording-manager-launcher { + display:none; + } + .recording-manager-command { + display:inline; + } + } + } + + .recording-manager-launcher { + width:100%; + margin:5px 10px; + display:none; + cursor:pointer; + } .recording-manager-command { -webkit-box-sizing: border-box; @@ -16,7 +38,9 @@ box-sizing: border-box; width:33%; margin:5px 10px; - visibility: hidden; + display:none; + visible:hidden; + cursor:pointer; .percent { margin-left:3px; diff --git a/web/app/assets/stylesheets/client/screen_common.css.scss b/web/app/assets/stylesheets/client/screen_common.css.scss index 30cc32a06..5f8247d2d 100644 --- a/web/app/assets/stylesheets/client/screen_common.css.scss +++ b/web/app/assets/stylesheets/client/screen_common.css.scss @@ -143,7 +143,6 @@ textarea { border:none; -webkit-box-shadow: inset 2px 2px 3px 0px #888; box-shadow: inset 2px 2px 3px 0px #888; - color:#333; } @@ -388,7 +387,7 @@ small, .small {font-size:11px;} .overlay-small { width:300px; - height:160px; + //height:160px; position:absolute; left:50%; top:20%; @@ -400,7 +399,7 @@ small, .small {font-size:11px;} .overlay-inner { width:250px; - height:130px; + //height:130px; padding:25px; font-size:15px; color:#aaa; @@ -429,6 +428,16 @@ small, .small {font-size:11px;} margin:0; } } + +.help-launcher { + font-weight:bold; + font-size:12px; + line-height:12px; + position:absolute; + top:3px; + right:3px; + cursor:pointer; +} .white {color:#fff;} .lightgrey {color:#ccc;} .grey {color:#999;} diff --git a/web/app/assets/stylesheets/client/session.css.scss b/web/app/assets/stylesheets/client/session.css.scss index 90b2f3d97..0a7e00e86 100644 --- a/web/app/assets/stylesheets/client/session.css.scss +++ b/web/app/assets/stylesheets/client/session.css.scss @@ -49,10 +49,11 @@ font-size:11px; height:18px; vertical-align:top; - margin-left:15px; } + .recording-controls { + display:none; position: absolute; bottom: 0; height: 25px; @@ -60,6 +61,9 @@ .play-button { top:2px; } + .recording-current { + top:3px ! important; + } } .playback-mode-buttons { @@ -675,17 +679,6 @@ table.vu td { font-size:18px; } -.recording-controls { - display:none; - - .play-button { - outline:none; - } - - .play-button img.pausebutton { - display:none; - } -} .playback-mode-buttons { display:none; @@ -762,3 +755,15 @@ table.vu td { .rate-thumbsdown.selected { background-image:url('/assets/content/icon_thumbsdown_big_on.png'); } + + +.recording-controls { + + .play-button { + outline:none; + } + + .play-button img.pausebutton { + display:none; + } +} \ No newline at end of file diff --git a/web/app/assets/stylesheets/dialogs/gettingStartDialog.css.scss b/web/app/assets/stylesheets/dialogs/gettingStartDialog.css.scss index 9e768b3e2..a3ada5d95 100644 --- a/web/app/assets/stylesheets/dialogs/gettingStartDialog.css.scss +++ b/web/app/assets/stylesheets/dialogs/gettingStartDialog.css.scss @@ -1,6 +1,6 @@ @import "client/common"; -#whatsnext-dialog, #getting-started-dialog { +#getting-started-dialog { height:auto; width:auto; diff --git a/web/app/assets/stylesheets/dialogs/syncViewerDialog.css.scss b/web/app/assets/stylesheets/dialogs/syncViewerDialog.css.scss new file mode 100644 index 000000000..4c51332e9 --- /dev/null +++ b/web/app/assets/stylesheets/dialogs/syncViewerDialog.css.scss @@ -0,0 +1,3 @@ +#all-syncs-dialog { + height:660px; +} \ No newline at end of file diff --git a/web/app/assets/stylesheets/easydropdown_jk.css.scss b/web/app/assets/stylesheets/easydropdown_jk.css.scss index 4b2ff52b6..47e43c108 100644 --- a/web/app/assets/stylesheets/easydropdown_jk.css.scss +++ b/web/app/assets/stylesheets/easydropdown_jk.css.scss @@ -106,15 +106,12 @@ body.jam { .dropdown-wrapper li { padding: 5px 5px; font-size:15px; - - color: #666666; } .dropdown-wrapper li { margin:0; padding:3px; font-size:15px; - color: #666666; &.focus { background-color: #ed3618; @@ -151,8 +148,6 @@ body.jam div.dropdown { .selected, .dropdown li { padding: 5px 5px; font-size:15px; - - color: #666666; } .selected:after { box-shadow: none; @@ -166,7 +161,6 @@ body.jam div.dropdown { margin:0; padding:3px; font-size:15px; - color: #666666; &.focus { background-color: #ed3618; diff --git a/web/app/assets/stylesheets/users/syncViewer.css.scss b/web/app/assets/stylesheets/users/syncViewer.css.scss new file mode 100644 index 000000000..5ed5c471f --- /dev/null +++ b/web/app/assets/stylesheets/users/syncViewer.css.scss @@ -0,0 +1,287 @@ +@import "client/common"; + +.sync-viewer { + width: 100%; + + .list { + height:400px; + overflow:auto; + border-style:solid; + border-width:0 0 1px 0; + border-color:#AAAAAA; + } + + .knobs { + + } + .headline { + height:40px; + @include border_box_sizing; + @include vertical-align-row; + + .download-progress, .upload-progress { + width:200px; + line-height:30px; + .paused { + display:none; + color:#777; + font-size:11px; + } + .quiet { + display:none; + color:#777; + font-size:11px; + } + &.paused { + .paused { + display:inline-block; + } + } + + &.quiet { + .quiet{ + display:inline-block; + } + } + &.busy { + .busy { + display:inline-block; + width:100%; + } + } + } + + .in-progress { + @include border_box_sizing; + @include vertical-align-row; + text-align:center; + + .sync { + line-height:20px; + height:30px; + + .type { + position:relative; + width:100%; + font-size: 10px; + } + .text { + z-index:1; + } + .avatar-tiny { + margin-top:-4px; + z-index:1; + } + .instrument-icon { + margin-top:-3px; + z-index:1; + } + } + } + } + + + .list-header { + width:100%; + height:16px; + font-size:12px; + .type-info { + float:left; + width:26%; + @include border_box_sizing; + @include vertical-align-column; + } + .client-state-info { + float:left; + padding: 0 4px; + width:37%; + @include border_box_sizing; + @include vertical-align-column; + } + .upload-state-info { + float:left; + width:37%; + @include border_box_sizing; + @include vertical-align-column; + } + + .special { + font-size:12px; + border-width:1px 1px 0 1px; + border-style:solid; + border-color:#cccccc; + width:100%; + text-align:center; + @include border_box_sizing; + } + + .special-text { + width:100%; + text-align:center; + @include border_box_sizing; + } + } + + .sync { + margin:3px 0; + display:inline-block; + @include border_box_sizing; + padding:3px; + background-color:black; + width:100%; + line-height:28px; + @include border-radius(2px); + + @include vertical-align-row; + } + + .type { + float:left; + width:26%; + color:white; + padding:3px; + @include border_box_sizing; + @include vertical-align-row; + + .instrument-icon { + width:24px; + height:24px; + } + } + + .msg { + z-index:1; + } + + .progress { + position:absolute; + background-color:$ColorScreenPrimary; + height:100%; + top:0px; + left:0; + } + + @include mix-state-box; + .mix-state { + position:relative; + float:left; + width:74%; + @include vertical-align-row; + } + + @include client-state-box; + .client-state { + position:relative; + float:left; + width:37%; + @include vertical-align-row; + } + + @include upload-state-box; + .upload-state { + position:relative; + float:left; + width: 37%; + @include vertical-align-row; + } + + .recording-holder { + margin-top:10px; + padding: 5px 0 0 0; + width:100%; + @include border_box_sizing; + @include vertical-align-column; + + .export { + float:right; + margin-right:3px; + font-size:12px; + } + .timeago { + float:right; + font-size:12px; + } + } + + .log-list { + height:392px; + overflow:auto; + border-style:solid; + border-width:0 0 1px 0; + border-color:#AAAAAA; + } + + .log { + + @include border_box_sizing; + @include border-radius(2px); + width:100%; + margin:3px 0; + display:inline-block; + padding:3px; + background-color:black; + height:20px; + font-size:12px; + color:white; + + &.success-false { + background-color:$error; + } + + .command { + float:left; + width:33%; + text-align:center; + position:relative; + + img { + position:absolute; + left:0; + top:-1px; + } + } + + .success { + float:left; + width:33%; + text-align:center; + } + + .detail { + float:left; + width:33%; + text-align:center; + } + } + + .badge { + display:none; + margin-left:5px; + height:11px; + width:12px; + color:white; + font-size:10px; + padding-top:2px; + background-color:$error; + -webkit-border-radius:6px; + -moz-border-radius:6px; + border-radius:6px; + vertical-align: top; + } + + .tab-content[purpose="log"] { + display:none; + + .list-header { + .list-column { + float:left; + width:33%; + text-align:center; + } + } + } + + .paginator-holder { + text-align:center; + } +} \ No newline at end of file diff --git a/web/app/assets/stylesheets/web/audioWidgets.css.scss b/web/app/assets/stylesheets/web/audioWidgets.css.scss index 1fcd93f85..55871e7ba 100644 --- a/web/app/assets/stylesheets/web/audioWidgets.css.scss +++ b/web/app/assets/stylesheets/web/audioWidgets.css.scss @@ -25,6 +25,8 @@ text-align: center; @include border_box_sizing; height: 36px; + display:inline-block; + white-space:nowrap; .recording-status { font-size:15px; @@ -34,8 +36,8 @@ font-family:Arial, Helvetica, sans-serif; display:inline-block; font-size:18px; - float:right; - top:3px; + position:absolute; + //top:3px; right:4px; } @@ -49,7 +51,10 @@ display:none; } } - &.no-mix { + + &:not(.has-mix) { + + border-width: 0; // override screen_common's .error .play-button { display:none; @@ -109,6 +114,7 @@ } } + .feed-entry { position:relative; display:block; @@ -172,7 +178,8 @@ .recording-controls { .recording-position { width:70%; - margin-left:0; + margin-left:-29px; + } .recording-playback { diff --git a/web/app/assets/stylesheets/web/recordings.css.scss b/web/app/assets/stylesheets/web/recordings.css.scss index bf15d9ce6..b843a9df2 100644 --- a/web/app/assets/stylesheets/web/recordings.css.scss +++ b/web/app/assets/stylesheets/web/recordings.css.scss @@ -6,7 +6,6 @@ padding:8px 5px 8px 10px; width:98%; position:relative; - text-align:center; } .landing-details .recording-controls, .landing-details .recording-controls { @@ -64,11 +63,11 @@ .recording-current { font-family:Arial, Helvetica, sans-serif; - display:inline-block; + display:inline; font-size:18px; - float:right; top:3px; right:4px; + position:absolute; } #btnPlayPause { diff --git a/web/app/controllers/api_claimed_recordings_controller.rb b/web/app/controllers/api_claimed_recordings_controller.rb index 04cef8d3f..725209843 100644 --- a/web/app/controllers/api_claimed_recordings_controller.rb +++ b/web/app/controllers/api_claimed_recordings_controller.rb @@ -14,8 +14,6 @@ class ApiClaimedRecordingsController < ApiController if !@claimed_recording.is_public && @claimed_recording.user_id != current_user.id raise PermissionError, 'this claimed recording is not public' end - - @claimed_recording end def update @@ -40,10 +38,21 @@ class ApiClaimedRecordingsController < ApiController raise PermissionError, 'this claimed recording is not public' end - mix = @claimed_recording.recording.mixes.first! - params[:type] ||= 'ogg' - redirect_to mix.sign_url(120, params[:type]) + + mix = @claimed_recording.recording.mix + + if mix && mix.completed + redirect_to mix.sign_url(120, params[:type]) + else + quick_mix = @claimed_recording.recording.stream_mix + + if quick_mix + redirect_to quick_mix.sign_url(120, params[:type]) + else + render :json => {}, :status => 404 + end + end end private diff --git a/web/app/controllers/api_configs_controller.rb b/web/app/controllers/api_configs_controller.rb new file mode 100644 index 000000000..5d096802e --- /dev/null +++ b/web/app/controllers/api_configs_controller.rb @@ -0,0 +1,14 @@ +class ApiConfigsController < ApiController + + respond_to :json + + def index + configs = + { + websocket_gateway_uri: APP_CONFIG.websocket_gateway_uri + } + render :json => configs, :status => 200 + end + + +end diff --git a/web/app/controllers/api_music_notations_controller.rb b/web/app/controllers/api_music_notations_controller.rb index 896c20b63..25997b24b 100644 --- a/web/app/controllers/api_music_notations_controller.rb +++ b/web/app/controllers/api_music_notations_controller.rb @@ -19,15 +19,20 @@ class ApiMusicNotationsController < ApiController @music_notations.push music_notation end if params[:files] - respond_with @music_notations, responder: ApiResponder, :statue => 201 + respond_with @music_notations, responder: ApiResponder, :status => 201 end def download @music_notation = MusicNotation.find(params[:id]) - unless @music_notation.music_session.nil? || @music_notation.music_session.can_join?(current_user, true) - raise PermissionError, ValidationMessages::PERMISSION_VALIDATION_ERROR - end - redirect_to @music_notation.sign_url + unless @music_notation.music_session.nil? || @music_notation.music_session.can_join?(current_user, true) + render :text => "Permission denied", status:403 + return + end + if '_blank'==params[:target] + redirect_to @music_notation.sign_url + else + render :text => @music_notation.sign_url + end end -end \ No newline at end of file +end diff --git a/web/app/controllers/api_recordings_controller.rb b/web/app/controllers/api_recordings_controller.rb index ba16d8d6e..abd4dc5c3 100644 --- a/web/app/controllers/api_recordings_controller.rb +++ b/web/app/controllers/api_recordings_controller.rb @@ -4,6 +4,7 @@ class ApiRecordingsController < ApiController before_filter :lookup_recording, :only => [ :show, :stop, :claim, :discard, :keep ] before_filter :lookup_recorded_track, :only => [ :download, :upload_next_part, :upload_sign, :upload_part_complete, :upload_complete ] before_filter :lookup_recorded_video, :only => [ :video_upload_sign, :video_upload_start, :video_upload_complete ] + before_filter :lookup_stream_mix, :only => [ :upload_next_part_stream_mix, :upload_sign_stream_mix, :upload_part_complete_stream_mix, :upload_complete_stream_mix ] respond_to :json @@ -36,6 +37,10 @@ class ApiRecordingsController < ApiController def show end + def show_recorded_track + @recorded_track = RecordedTrack.find_by_recording_id_and_client_track_id(params[:id], params[:track_id]) + end + def download raise PermissionError, ValidationMessages::PERMISSION_VALIDATION_ERROR unless @recorded_track.can_download?(current_user) @@ -151,7 +156,7 @@ class ApiRecordingsController < ApiController render :json => {}, :status => 200 end - def upload_next_part + def upload_next_part # track length = params[:length] md5 = params[:md5] @@ -175,11 +180,11 @@ class ApiRecordingsController < ApiController end - def upload_sign + def upload_sign # track render :json => @recorded_track.upload_sign(params[:md5]), :status => 200 end - def upload_part_complete + def upload_part_complete # track part = params[:part] offset = params[:offset] @@ -193,7 +198,7 @@ class ApiRecordingsController < ApiController end end - def upload_complete + def upload_complete # track @recorded_track.upload_complete @recorded_track.recording.upload_complete @@ -233,6 +238,61 @@ class ApiRecordingsController < ApiController render :json => response, :status => 200 end + + def upload_next_part_stream_mix + length = params[:length] + md5 = params[:md5] + + @quick_mix.upload_next_part(length, md5) + + if @quick_mix.errors.any? + + response.status = :unprocessable_entity + # this is not typical, but please don't change this line unless you are sure it won't break anything + # this is needed because after_rollback in the RecordedTrackObserver touches the model and something about it's + # state doesn't cause errors to shoot out like normal. + render :json => { :errors => @quick_mix.errors }, :status => 422 + else + result = { + :part => @quick_mix.next_part_to_upload, + :offset => @quick_mix.file_offset.to_s + } + + render :json => result, :status => 200 + end + + end + + def upload_sign_stream_mix + render :json => @quick_mix.upload_sign(params[:md5]), :status => 200 + end + + def upload_part_complete_stream_mix + part = params[:part] + offset = params[:offset] + + @quick_mix.upload_part_complete(part, offset) + + if @quick_mix.errors.any? + response.status = :unprocessable_entity + respond_with @quick_mix + else + render :json => {}, :status => 200 + end + end + + def upload_complete_stream_mix + @quick_mix.upload_complete + + if @quick_mix.errors.any? + response.status = :unprocessable_entity + respond_with @quick_mix + return + else + render :json => {}, :status => 200 + end + end + private def lookup_recording @@ -250,4 +310,9 @@ class ApiRecordingsController < ApiController raise PermissionError, ValidationMessages::PERMISSION_VALIDATION_ERROR unless @recorded_video.recording.has_access?(current_user) end + def lookup_stream_mix + @quick_mix = QuickMix.find_by_recording_id_and_user_id!(params[:id], current_user.id) + raise PermissionError, ValidationMessages::PERMISSION_VALIDATION_ERROR unless @quick_mix.recording.has_access?(current_user) + end + end # class diff --git a/web/app/controllers/api_user_syncs_controller.rb b/web/app/controllers/api_user_syncs_controller.rb new file mode 100644 index 000000000..32fbbe395 --- /dev/null +++ b/web/app/controllers/api_user_syncs_controller.rb @@ -0,0 +1,41 @@ +# abstracts the idea of downloading / uploading files to JamKazam. +# Recordings, JamTracks, and Video are this + +class ApiUserSyncsController < ApiController + + before_filter :api_signed_in_user, :except => [ ] + before_filter :auth_user + + respond_to :json + + @@log = Logging.logger[ApiUserSyncsController] + + + def show + @user_sync = UserSync.show(params[:user_sync_id], current_user.id) + + if @user_sync.nil? + raise ActiveRecord::RecordNotFound + end + + render "api_user_syncs/show", :layout => nil + end + + # returns all downloads and uploads for a user, meaning it should return: + # all recorded_tracks (audio and video/soon) + # all mixes + # all jamtracks (soon) + def index + data = UserSync.index( + {user_id:current_user.id, + recording_id: params[:recording_id], + offset: params[:since], + limit: params[:limit]}) + + + + @user_syncs = data[:query] + @next = data[:next] + render "api_user_syncs/index", :layout => nil + end +end diff --git a/web/app/controllers/recordings_controller.rb b/web/app/controllers/recordings_controller.rb index 650c6971f..2f92c64c0 100644 --- a/web/app/controllers/recordings_controller.rb +++ b/web/app/controllers/recordings_controller.rb @@ -3,7 +3,11 @@ class RecordingsController < ApplicationController respond_to :html def show - @claimed_recording = ClaimedRecording.find(params[:id]) + @claimed_recording = ClaimedRecording.find_by_id(params[:id]) + if @claimed_recording.nil? + recording = Recording.find(params[:id]) + @claimed_recording = recording.candidate_claimed_recording + end render :layout => "web" end diff --git a/web/app/helpers/feeds_helper.rb b/web/app/helpers/feeds_helper.rb index fb128dc7b..38abfff85 100644 --- a/web/app/helpers/feeds_helper.rb +++ b/web/app/helpers/feeds_helper.rb @@ -119,5 +119,4 @@ module FeedsHelper def recording_genre(recording) recording.candidate_claimed_recording.genre.description end - end diff --git a/web/app/helpers/recording_helper.rb b/web/app/helpers/recording_helper.rb index 0c7b4030d..cbad1805c 100644 --- a/web/app/helpers/recording_helper.rb +++ b/web/app/helpers/recording_helper.rb @@ -45,4 +45,11 @@ module RecordingHelper def description_for_claimed_recording(claimed_recording) truncate(claimed_recording.name, length:250) end + + def listen_mix_url(recording) + { + mp3_url: claimed_recording_download_url(recording.candidate_claimed_recording.id, 'mp3'), + ogg_url: claimed_recording_download_url(recording.candidate_claimed_recording.id, 'ogg') + } + end end diff --git a/web/app/views/api_claimed_recordings/show.rabl b/web/app/views/api_claimed_recordings/show.rabl index 5210fcbc9..6be19dee3 100644 --- a/web/app/views/api_claimed_recordings/show.rabl +++ b/web/app/views/api_claimed_recordings/show.rabl @@ -12,6 +12,11 @@ node :share_url do |claimed_recording| end end + +node :mix do |claimed_recording| + listen_mix_url(claimed_recording.recording) if claimed_recording.has_mix? +end + child(:recording => :recording) { attributes :id, :created_at, :duration, :comment_count, :like_count, :play_count @@ -39,14 +44,3 @@ child(:recording => :recording) { } } } - -if :has_mix? - node do |claimed_recording| - { - mix: { - mp3_url: claimed_recording_download_url(claimed_recording.id, 'mp3'), - ogg_url: claimed_recording_download_url(claimed_recording.id, 'ogg') - } - } - end -end \ No newline at end of file diff --git a/web/app/views/api_feeds/show.rabl b/web/app/views/api_feeds/show.rabl index bdf21d1c7..06a6df897 100644 --- a/web/app/views/api_feeds/show.rabl +++ b/web/app/views/api_feeds/show.rabl @@ -78,7 +78,7 @@ glue :recording do 'recording' end - attributes :id, :band, :created_at, :duration, :comment_count, :like_count, :play_count, :has_mix? + attributes :id, :band, :created_at, :duration, :comment_count, :like_count, :play_count, :has_mix?, :mix_state node do |recording| { @@ -96,6 +96,13 @@ glue :recording do } end + node :mix do |recording| + { + state: recording.mix_state, + error: recording.mix_error + } + end unless @object.mix.nil? + child(:owner => :owner) { attributes :id, :name, :location, :photo_url } @@ -153,18 +160,9 @@ glue :recording do end end - if :has_mix? - node do |claimed_recording| - { - mix: { - mp3_url: claimed_recording_download_url(claimed_recording.id, 'mp3'), - ogg_url: claimed_recording_download_url(claimed_recording.id, 'ogg') - } - } - end + node :mix do |claimed_recording| + listen_mix_url(claimed_recording.recording) if claimed_recording.has_mix? end - - } end diff --git a/web/app/views/api_music_sessions/show.rabl b/web/app/views/api_music_sessions/show.rabl index 274246985..98f642a7f 100644 --- a/web/app/views/api_music_sessions/show.rabl +++ b/web/app/views/api_music_sessions/show.rabl @@ -57,53 +57,49 @@ else } # only show join_requests if the current_user is in the session - node(:join_requests, :if => lambda { |music_session| music_session.users.exists?(current_user) } ) do |music_session| - child(:join_requests => :join_requests) { - attributes :id, :text - child(:user => :user) { - attributes :id, :name - } + child({:join_requests => :join_requests}, :if => lambda { |music_session| music_session.users.exists?(current_user) } ) { + attributes :id, :text + child(:user => :user) { + attributes :id, :name } - end + } # only show currently playing recording data if the current_user is in the session - node(:claimed_recording, :if => lambda { |music_session| music_session.users.exists?(current_user) } ) do |music_session| - child(:claimed_recording => :claimed_recording) { - attributes :id, :name, :description, :is_public + child({:claimed_recording => :claimed_recording}, :if => lambda { |music_session| music_session.users.exists?(current_user) }) { + attributes :id, :name, :description, :is_public - child(:recording => :recording) { - attributes :id, :created_at, :duration - child(:band => :band) { - attributes :id, :name - } + child(:recording => :recording) { + attributes :id, :created_at, :duration + child(:band => :band) { + attributes :id, :name + } - child(:mixes => :mixes) { - attributes :id, :is_completed + child(:mixes => :mixes) { + attributes :id, :is_completed - node :mp3_url do |mix| - mix[:mp3_url] - end + node :mp3_url do |mix| + mix[:mp3_url] + end - node :ogg_url do |mix| - mix[:ogg_url] - end - } + node :ogg_url do |mix| + mix[:ogg_url] + end + } - child(:recorded_tracks => :recorded_tracks) { - attributes :id, :fully_uploaded, :client_track_id, :client_id, :instrument_id + child(:recorded_tracks => :recorded_tracks) { + attributes :id, :fully_uploaded, :client_track_id, :client_id, :instrument_id - node :url do |recorded_track| - recorded_track[:url] - end + node :url do |recorded_track| + recorded_track[:url] + end - child(:user => :user) { - attributes :id, :first_name, :last_name, :city, :state, :country, :photo_url - } + child(:user => :user) { + attributes :id, :first_name, :last_name, :city, :state, :country, :photo_url } } } - end + } # only show mount info if fan_access is public. Eventually we'll also need to show this in other scenarios, like if invited child({:mount => :mount}, :if => lambda { |music_session| music_session.fan_access}) { diff --git a/web/app/views/api_music_sessions/show_history.rabl b/web/app/views/api_music_sessions/show_history.rabl index 9d732d843..e027c0874 100644 --- a/web/app/views/api_music_sessions/show_history.rabl +++ b/web/app/views/api_music_sessions/show_history.rabl @@ -85,7 +85,9 @@ else attributes :id, :file_name node do |music_notation| - { file_url: "/api/music_notations/#{music_notation.id}" } + { file_url: "/api/music_notations/#{music_notation.id}", + viewable: music_notation.music_session.can_join?(current_user, true) + } end } diff --git a/web/app/views/api_recordings/show.rabl b/web/app/views/api_recordings/show.rabl index 8b75f0384..78392c0b1 100644 --- a/web/app/views/api_recordings/show.rabl +++ b/web/app/views/api_recordings/show.rabl @@ -2,6 +2,17 @@ object @recording attributes :id, :band, :created_at, :duration, :comment_count, :like_count, :play_count +node :mix do |recording| + if recording.mix + { + id: recording.mix.id + } + else + nil + end +end + + child(:band => :band) { attributes :id, :name, :location, :photo_url } @@ -11,11 +22,9 @@ child(:owner => :owner) { } child(:recorded_tracks => :recorded_tracks) { - attributes :id, :fully_uploaded, :client_track_id, :client_id, :instrument_id - - child(:user => :user) { - attributes :id, :first_name, :last_name, :city, :state, :country, :location, :photo_url - } + node do |recorded_track| + partial("api_recordings/show_recorded_track", :object => recorded_track) + end } child(:comments => :comments) { @@ -26,6 +35,16 @@ child(:comments => :comments) { } } +# returns the current_user's version of the recording, i.e., their associated claimed_recording if present +node :my do |recording| + claim = recording.claim_for_user(current_user) || recording.candidate_claimed_recording + if claim + { name: claim.name, description: claim.description, genre: claim.genre.id, genre_name: claim.genre.description } + else + nil + end +end + child(:claimed_recordings => :claimed_recordings) { attributes :id, :name, :description, :is_public, :genre_id, :has_mix?, :user_id @@ -36,14 +55,7 @@ child(:claimed_recordings => :claimed_recordings) { end end - if :has_mix? - node do |claimed_recording| - { - mix: { - mp3_url: claimed_recording_download_url(claimed_recording.id, 'mp3'), - ogg_url: claimed_recording_download_url(claimed_recording.id, 'ogg') - } - } - end + node :mix do |claimed_recording| + listen_mix_url(claimed_recording.recording) if claimed_recording.has_mix? end } diff --git a/web/app/views/api_recordings/show_recorded_track.rabl b/web/app/views/api_recordings/show_recorded_track.rabl new file mode 100644 index 000000000..f5f73cc90 --- /dev/null +++ b/web/app/views/api_recordings/show_recorded_track.rabl @@ -0,0 +1,7 @@ +object @recorded_track + +attributes :id, :fully_uploaded, :client_track_id, :client_id, :instrument_id, :recording_id + +child(:user => :user) { + attributes :id, :first_name, :last_name, :city, :state, :country, :location, :photo_url +} \ No newline at end of file diff --git a/web/app/views/api_user_syncs/index.rabl b/web/app/views/api_user_syncs/index.rabl new file mode 100644 index 000000000..097e4f96f --- /dev/null +++ b/web/app/views/api_user_syncs/index.rabl @@ -0,0 +1,15 @@ + + +node :next do |page| + @next +end + +node :entries do |page| + partial "api_user_syncs/show", object: @user_syncs +end + +node :total_entries do |page| + @user_syncs.total_entries +end + + diff --git a/web/app/views/api_user_syncs/show.rabl b/web/app/views/api_user_syncs/show.rabl new file mode 100644 index 000000000..0c63ba010 --- /dev/null +++ b/web/app/views/api_user_syncs/show.rabl @@ -0,0 +1,103 @@ +object @user_sync + +glue :recorded_track do + + @object.current_user = current_user + + node :type do |i| + 'recorded_track' + end + + attributes :id, :recording_id, :client_id, :track_id, :client_track_id, :md5, :length, :download_count, :instrument_id, :fully_uploaded, :upload_failures, :part_failures, :created_at + + node :user do |recorded_track| + partial("api_users/show_minimal", :object => recorded_track.user) + end + + node :recording do |recorded_track| + partial("api_recordings/show", :object => recorded_track.recording) + end + + + node :upload do |recorded_track| + { + should_upload: true, + too_many_upload_failures: recorded_track.too_many_upload_failures? + } + end + + node :download do |recorded_track| + { + should_download: recorded_track.can_download?(current_user), + too_many_downloads: recorded_track.too_many_downloads? + } + end + +end + +glue :mix do + + @object.current_user = current_user + + node :type do |i| + 'mix' + end + + attributes :id, :recording_id, :started_at, :completed_at, :completed, :should_retry, :download_count, :state + + node :recording do |mix| + partial("api_recordings/show", :object => mix.recording) + end + + node do |mix| + { + duration: mix.recording.duration, + error: mix.error + } + end + + node :download do |mix| + { + should_download: mix.can_download?(current_user), + too_many_downloads: mix.too_many_downloads? + } + end + +end + + +glue :quick_mix do + + @object.current_user = current_user + + node :type do |i| + 'stream_mix' + end + + attributes :id, :recording_id, :fully_uploaded, :upload_failures, :part_failures, :created_at + + node :user do |quick_mix| + partial("api_users/show_minimal", :object => quick_mix.user) + end + + node :recording do |quick_mix| + partial("api_recordings/show", :object => quick_mix.recording) + end + + + node :upload do |quick_mix| + { + should_upload: true, + too_many_upload_failures: quick_mix.too_many_upload_failures? + } + end + + node :download do |quick_mix| + { + should_download: false, + too_many_downloads: false + } + end + +end + diff --git a/web/app/views/api_users/show.rabl b/web/app/views/api_users/show.rabl index b2827fdba..fd8b9b87e 100644 --- a/web/app/views/api_users/show.rabl +++ b/web/app/views/api_users/show.rabl @@ -30,6 +30,12 @@ elsif current_user node :pending_friend_request do |uu| current_user.pending_friend_request?(@user) end + node :my_audio_latency do |user| + current_user.last_jam_audio_latency.round if current_user.last_jam_audio_latency + end + node :internet_score do |user| + current_user.score_info(user) + end end child :friends => :friends do diff --git a/web/app/views/api_users/show_minimal.rabl b/web/app/views/api_users/show_minimal.rabl new file mode 100644 index 000000000..3846a746a --- /dev/null +++ b/web/app/views/api_users/show_minimal.rabl @@ -0,0 +1,3 @@ +object @user + +attributes :id, :first_name, :last_name, :photo_url, :name diff --git a/web/app/views/clients/_account_identity.html.erb b/web/app/views/clients/_account_identity.html.erb index 9b8866b96..1afe12c19 100644 --- a/web/app/views/clients/_account_identity.html.erb +++ b/web/app/views/clients/_account_identity.html.erb @@ -82,6 +82,7 @@ diff --git a/web/app/views/clients/_findSession.html.erb b/web/app/views/clients/_findSession.html.erb index 4f2b383bc..094794387 100644 --- a/web/app/views/clients/_findSession.html.erb +++ b/web/app/views/clients/_findSession.html.erb @@ -245,7 +245,7 @@ + + + + + + + + diff --git a/web/app/views/clients/_help_launcher.html.slim b/web/app/views/clients/_help_launcher.html.slim new file mode 100644 index 000000000..09c428b72 --- /dev/null +++ b/web/app/views/clients/_help_launcher.html.slim @@ -0,0 +1,2 @@ +.help-launcher + | ? \ No newline at end of file diff --git a/web/app/views/clients/_hoverMusician.html.erb b/web/app/views/clients/_hoverMusician.html.erb index 0a185a3ed..dd1994d6d 100644 --- a/web/app/views/clients/_hoverMusician.html.erb +++ b/web/app/views/clients/_hoverMusician.html.erb @@ -115,6 +115,11 @@
{biography}

+
+ Your latency to {first_name} is:  {latency_badge} +
+
+
FOLLOWING:

{followings} diff --git a/web/app/views/clients/_musicians.html.erb b/web/app/views/clients/_musicians.html.erb index 60279346f..cd626c8f0 100644 --- a/web/app/views/clients/_musicians.html.erb +++ b/web/app/views/clients/_musicians.html.erb @@ -50,7 +50,7 @@
-
+
Your latency
to {musician_first_name} is:
{latency_badge} diff --git a/web/app/views/clients/_play_controls.html.erb b/web/app/views/clients/_play_controls.html.erb index 7ee2042d4..88e088018 100644 --- a/web/app/views/clients/_play_controls.html.erb +++ b/web/app/views/clients/_play_controls.html.erb @@ -1,5 +1,5 @@ -
+
diff --git a/web/app/views/clients/_recordingManager.html.erb b/web/app/views/clients/_recordingManager.html.erb index 6a1f7f2b4..8553d47b7 100644 --- a/web/app/views/clients/_recordingManager.html.erb +++ b/web/app/views/clients/_recordingManager.html.erb @@ -1,4 +1,7 @@ + + File Manager + converting0 diff --git a/web/app/views/clients/_scheduledSession.html.erb b/web/app/views/clients/_scheduledSession.html.erb index 00b3ac295..349ecc77f 100644 --- a/web/app/views/clients/_scheduledSession.html.erb +++ b/web/app/views/clients/_scheduledSession.html.erb @@ -27,35 +27,35 @@
    -
  • +
  • -
  • +
  • -
  • +
  • -
  • +
  • -
  • +
a"; - - all = div.getElementsByTagName( "*" ); - a = div.getElementsByTagName( "a" )[ 0 ]; - - // Can't get basic test support - if ( !all || !all.length || !a ) { - return {}; - } - - // First batch of supports tests - select = document.createElement( "select" ); - opt = select.appendChild( document.createElement("option") ); - input = div.getElementsByTagName( "input" )[ 0 ]; - - support = { - // IE strips leading whitespace when .innerHTML is used - leadingWhitespace: ( div.firstChild.nodeType === 3 ), - - // Make sure that tbody elements aren't automatically inserted - // IE will insert them into empty tables - tbody: !div.getElementsByTagName("tbody").length, - - // Make sure that link elements get serialized correctly by innerHTML - // This requires a wrapper element in IE - htmlSerialize: !!div.getElementsByTagName("link").length, - - // Get the style information from getAttribute - // (IE uses .cssText instead) - style: /top/.test( a.getAttribute("style") ), - - // Make sure that URLs aren't manipulated - // (IE normalizes it by default) - hrefNormalized: ( a.getAttribute("href") === "/a" ), - - // Make sure that element opacity exists - // (IE uses filter instead) - // Use a regex to work around a WebKit issue. See #5145 - opacity: /^0.55/.test( a.style.opacity ), - - // Verify style float existence - // (IE uses styleFloat instead of cssFloat) - cssFloat: !!a.style.cssFloat, - - // Make sure that if no value is specified for a checkbox - // that it defaults to "on". - // (WebKit defaults to "" instead) - checkOn: ( input.value === "on" ), - - // Make sure that a selected-by-default option has a working selected property. - // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) - optSelected: opt.selected, - - // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) - getSetAttribute: div.className !== "t", - - // Tests for enctype support on a form(#6743) - enctype: !!document.createElement("form").enctype, - - // Makes sure cloning an html5 element does not cause problems - // Where outerHTML is undefined, this still works - html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav>", - - // Will be defined later - submitBubbles: true, - changeBubbles: true, - focusinBubbles: false, - deleteExpando: true, - noCloneEvent: true, - inlineBlockNeedsLayout: false, - shrinkWrapBlocks: false, - reliableMarginRight: true, - pixelMargin: true - }; - - // jQuery.boxModel DEPRECATED in 1.3, use jQuery.support.boxModel instead - jQuery.boxModel = support.boxModel = (document.compatMode === "CSS1Compat"); - - // Make sure checked status is properly cloned - input.checked = true; - support.noCloneChecked = input.cloneNode( true ).checked; - - // Make sure that the options inside disabled selects aren't marked as disabled - // (WebKit marks them as disabled) - select.disabled = true; - support.optDisabled = !opt.disabled; - - // Test to see if it's possible to delete an expando from an element - // Fails in Internet Explorer - try { - delete div.test; - } catch( e ) { - support.deleteExpando = false; - } - - if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { - div.attachEvent( "onclick", function() { - // Cloning a node shouldn't copy over any - // bound event handlers (IE does this) - support.noCloneEvent = false; - }); - div.cloneNode( true ).fireEvent( "onclick" ); - } - - // Check if a radio maintains its value - // after being appended to the DOM - input = document.createElement("input"); - input.value = "t"; - input.setAttribute("type", "radio"); - support.radioValue = input.value === "t"; - - input.setAttribute("checked", "checked"); - - // #11217 - WebKit loses check when the name is after the checked attribute - input.setAttribute( "name", "t" ); - - div.appendChild( input ); - fragment = document.createDocumentFragment(); - fragment.appendChild( div.lastChild ); - - // WebKit doesn't clone checked state correctly in fragments - support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; - - // Check if a disconnected checkbox will retain its checked - // value of true after appended to the DOM (IE6/7) - support.appendChecked = input.checked; - - fragment.removeChild( input ); - fragment.appendChild( div ); - - // Technique from Juriy Zaytsev - // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ - // We only care about the case where non-standard event systems - // are used, namely in IE. Short-circuiting here helps us to - // avoid an eval call (in setAttribute) which can cause CSP - // to go haywire. See: https://developer.mozilla.org/en/Security/CSP - if ( div.attachEvent ) { - for ( i in { - submit: 1, - change: 1, - focusin: 1 - }) { - eventName = "on" + i; - isSupported = ( eventName in div ); - if ( !isSupported ) { - div.setAttribute( eventName, "return;" ); - isSupported = ( typeof div[ eventName ] === "function" ); - } - support[ i + "Bubbles" ] = isSupported; - } - } - - fragment.removeChild( div ); - - // Null elements to avoid leaks in IE - fragment = select = opt = div = input = null; - - // Run tests that need a body at doc ready - jQuery(function() { - var container, outer, inner, table, td, offsetSupport, - marginDiv, conMarginTop, style, html, positionTopLeftWidthHeight, - paddingMarginBorderVisibility, paddingMarginBorder, - body = document.getElementsByTagName("body")[0]; - - if ( !body ) { - // Return for frameset docs that don't have a body - return; - } - - conMarginTop = 1; - paddingMarginBorder = "padding:0;margin:0;border:"; - positionTopLeftWidthHeight = "position:absolute;top:0;left:0;width:1px;height:1px;"; - paddingMarginBorderVisibility = paddingMarginBorder + "0;visibility:hidden;"; - style = "style='" + positionTopLeftWidthHeight + paddingMarginBorder + "5px solid #000;"; - html = "
" + - "" + - "
"; - - container = document.createElement("div"); - container.style.cssText = paddingMarginBorderVisibility + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px"; - body.insertBefore( container, body.firstChild ); - - // Construct the test element - div = document.createElement("div"); - container.appendChild( div ); - - // Check if table cells still have offsetWidth/Height when they are set - // to display:none and there are still other visible table cells in a - // table row; if so, offsetWidth/Height are not reliable for use when - // determining if an element has been hidden directly using - // display:none (it is still safe to use offsets if a parent element is - // hidden; don safety goggles and see bug #4512 for more information). - // (only IE 8 fails this test) - div.innerHTML = "
t
"; - tds = div.getElementsByTagName( "td" ); - isSupported = ( tds[ 0 ].offsetHeight === 0 ); - - tds[ 0 ].style.display = ""; - tds[ 1 ].style.display = "none"; - - // Check if empty table cells still have offsetWidth/Height - // (IE <= 8 fail this test) - support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); - - // Check if div with explicit width and no margin-right incorrectly - // gets computed margin-right based on width of container. For more - // info see bug #3333 - // Fails in WebKit before Feb 2011 nightlies - // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right - if ( window.getComputedStyle ) { - div.innerHTML = ""; - marginDiv = document.createElement( "div" ); - marginDiv.style.width = "0"; - marginDiv.style.marginRight = "0"; - div.style.width = "2px"; - div.appendChild( marginDiv ); - support.reliableMarginRight = - ( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0; - } - - if ( typeof div.style.zoom !== "undefined" ) { - // Check if natively block-level elements act like inline-block - // elements when setting their display to 'inline' and giving - // them layout - // (IE < 8 does this) - div.innerHTML = ""; - div.style.width = div.style.padding = "1px"; - div.style.border = 0; - div.style.overflow = "hidden"; - div.style.display = "inline"; - div.style.zoom = 1; - support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); - - // Check if elements with layout shrink-wrap their children - // (IE 6 does this) - div.style.display = "block"; - div.style.overflow = "visible"; - div.innerHTML = "
"; - support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); - } - - div.style.cssText = positionTopLeftWidthHeight + paddingMarginBorderVisibility; - div.innerHTML = html; - - outer = div.firstChild; - inner = outer.firstChild; - td = outer.nextSibling.firstChild.firstChild; - - offsetSupport = { - doesNotAddBorder: ( inner.offsetTop !== 5 ), - doesAddBorderForTableAndCells: ( td.offsetTop === 5 ) - }; - - inner.style.position = "fixed"; - inner.style.top = "20px"; - - // safari subtracts parent border width here which is 5px - offsetSupport.fixedPosition = ( inner.offsetTop === 20 || inner.offsetTop === 15 ); - inner.style.position = inner.style.top = ""; - - outer.style.overflow = "hidden"; - outer.style.position = "relative"; - - offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 ); - offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop ); - - if ( window.getComputedStyle ) { - div.style.marginTop = "1%"; - support.pixelMargin = ( window.getComputedStyle( div, null ) || { marginTop: 0 } ).marginTop !== "1%"; - } - - if ( typeof container.style.zoom !== "undefined" ) { - container.style.zoom = 1; - } - - body.removeChild( container ); - marginDiv = div = container = null; - - jQuery.extend( support, offsetSupport ); - }); - - return support; -})(); - - - - -var rbrace = /^(?:\{.*\}|\[.*\])$/, - rmultiDash = /([A-Z])/g; - -jQuery.extend({ - cache: {}, - - // Please use with caution - uuid: 0, - - // Unique for each copy of jQuery on the page - // Non-digits removed to match rinlinejQuery - expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), - - // The following elements throw uncatchable exceptions if you - // attempt to add expando properties to them. - noData: { - "embed": true, - // Ban all objects except for Flash (which handle expandos) - "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", - "applet": true - }, - - hasData: function( elem ) { - elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; - return !!elem && !isEmptyDataObject( elem ); - }, - - data: function( elem, name, data, pvt /* Internal Use Only */ ) { - if ( !jQuery.acceptData( elem ) ) { - return; - } - - var privateCache, thisCache, ret, - internalKey = jQuery.expando, - getByName = typeof name === "string", - - // We have to handle DOM nodes and JS objects differently because IE6-7 - // can't GC object references properly across the DOM-JS boundary - isNode = elem.nodeType, - - // Only DOM nodes need the global jQuery cache; JS object data is - // attached directly to the object so GC can occur automatically - cache = isNode ? jQuery.cache : elem, - - // Only defining an ID for JS objects if its cache already exists allows - // the code to shortcut on the same path as a DOM node with no cache - id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey, - isEvents = name === "events"; - - // Avoid doing any more work than we need to when trying to get data on an - // object that has no data at all - if ( (!id || !cache[id] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined ) { - return; - } - - if ( !id ) { - // Only DOM nodes need a new unique ID for each element since their data - // ends up in the global cache - if ( isNode ) { - elem[ internalKey ] = id = ++jQuery.uuid; - } else { - id = internalKey; - } - } - - if ( !cache[ id ] ) { - cache[ id ] = {}; - - // Avoids exposing jQuery metadata on plain JS objects when the object - // is serialized using JSON.stringify - if ( !isNode ) { - cache[ id ].toJSON = jQuery.noop; - } - } - - // An object can be passed to jQuery.data instead of a key/value pair; this gets - // shallow copied over onto the existing cache - if ( typeof name === "object" || typeof name === "function" ) { - if ( pvt ) { - cache[ id ] = jQuery.extend( cache[ id ], name ); - } else { - cache[ id ].data = jQuery.extend( cache[ id ].data, name ); - } - } - - privateCache = thisCache = cache[ id ]; - - // jQuery data() is stored in a separate object inside the object's internal data - // cache in order to avoid key collisions between internal data and user-defined - // data. - if ( !pvt ) { - if ( !thisCache.data ) { - thisCache.data = {}; - } - - thisCache = thisCache.data; - } - - if ( data !== undefined ) { - thisCache[ jQuery.camelCase( name ) ] = data; - } - - // Users should not attempt to inspect the internal events object using jQuery.data, - // it is undocumented and subject to change. But does anyone listen? No. - if ( isEvents && !thisCache[ name ] ) { - return privateCache.events; - } - - // Check for both converted-to-camel and non-converted data property names - // If a data property was specified - if ( getByName ) { - - // First Try to find as-is property data - ret = thisCache[ name ]; - - // Test for null|undefined property data - if ( ret == null ) { - - // Try to find the camelCased property - ret = thisCache[ jQuery.camelCase( name ) ]; - } - } else { - ret = thisCache; - } - - return ret; - }, - - removeData: function( elem, name, pvt /* Internal Use Only */ ) { - if ( !jQuery.acceptData( elem ) ) { - return; - } - - var thisCache, i, l, - - // Reference to internal data cache key - internalKey = jQuery.expando, - - isNode = elem.nodeType, - - // See jQuery.data for more information - cache = isNode ? jQuery.cache : elem, - - // See jQuery.data for more information - id = isNode ? elem[ internalKey ] : internalKey; - - // If there is already no cache entry for this object, there is no - // purpose in continuing - if ( !cache[ id ] ) { - return; - } - - if ( name ) { - - thisCache = pvt ? cache[ id ] : cache[ id ].data; - - if ( thisCache ) { - - // Support array or space separated string names for data keys - if ( !jQuery.isArray( name ) ) { - - // try the string as a key before any manipulation - if ( name in thisCache ) { - name = [ name ]; - } else { - - // split the camel cased version by spaces unless a key with the spaces exists - name = jQuery.camelCase( name ); - if ( name in thisCache ) { - name = [ name ]; - } else { - name = name.split( " " ); - } - } - } - - for ( i = 0, l = name.length; i < l; i++ ) { - delete thisCache[ name[i] ]; - } - - // If there is no data left in the cache, we want to continue - // and let the cache object itself get destroyed - if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { - return; - } - } - } - - // See jQuery.data for more information - if ( !pvt ) { - delete cache[ id ].data; - - // Don't destroy the parent cache unless the internal data object - // had been the only thing left in it - if ( !isEmptyDataObject(cache[ id ]) ) { - return; - } - } - - // Browsers that fail expando deletion also refuse to delete expandos on - // the window, but it will allow it on all other JS objects; other browsers - // don't care - // Ensure that `cache` is not a window object #10080 - if ( jQuery.support.deleteExpando || !cache.setInterval ) { - delete cache[ id ]; - } else { - cache[ id ] = null; - } - - // We destroyed the cache and need to eliminate the expando on the node to avoid - // false lookups in the cache for entries that no longer exist - if ( isNode ) { - // IE does not allow us to delete expando properties from nodes, - // nor does it have a removeAttribute function on Document nodes; - // we must handle all of these cases - if ( jQuery.support.deleteExpando ) { - delete elem[ internalKey ]; - } else if ( elem.removeAttribute ) { - elem.removeAttribute( internalKey ); - } else { - elem[ internalKey ] = null; - } - } - }, - - // For internal use only. - _data: function( elem, name, data ) { - return jQuery.data( elem, name, data, true ); - }, - - // A method for determining if a DOM node can handle the data expando - acceptData: function( elem ) { - if ( elem.nodeName ) { - var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; - - if ( match ) { - return !(match === true || elem.getAttribute("classid") !== match); - } - } - - return true; - } -}); - -jQuery.fn.extend({ - data: function( key, value ) { - var parts, part, attr, name, l, - elem = this[0], - i = 0, - data = null; - - // Gets all values - if ( key === undefined ) { - if ( this.length ) { - data = jQuery.data( elem ); - - if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { - attr = elem.attributes; - for ( l = attr.length; i < l; i++ ) { - name = attr[i].name; - - if ( name.indexOf( "data-" ) === 0 ) { - name = jQuery.camelCase( name.substring(5) ); - - dataAttr( elem, name, data[ name ] ); - } - } - jQuery._data( elem, "parsedAttrs", true ); - } - } - - return data; - } - - // Sets multiple values - if ( typeof key === "object" ) { - return this.each(function() { - jQuery.data( this, key ); - }); - } - - parts = key.split( ".", 2 ); - parts[1] = parts[1] ? "." + parts[1] : ""; - part = parts[1] + "!"; - - return jQuery.access( this, function( value ) { - - if ( value === undefined ) { - data = this.triggerHandler( "getData" + part, [ parts[0] ] ); - - // Try to fetch any internally stored data first - if ( data === undefined && elem ) { - data = jQuery.data( elem, key ); - data = dataAttr( elem, key, data ); - } - - return data === undefined && parts[1] ? - this.data( parts[0] ) : - data; - } - - parts[1] = value; - this.each(function() { - var self = jQuery( this ); - - self.triggerHandler( "setData" + part, parts ); - jQuery.data( this, key, value ); - self.triggerHandler( "changeData" + part, parts ); - }); - }, null, value, arguments.length > 1, null, false ); - }, - - removeData: function( key ) { - return this.each(function() { - jQuery.removeData( this, key ); - }); - } -}); - -function dataAttr( elem, key, data ) { - // If nothing was found internally, try to fetch any - // data from the HTML5 data-* attribute - if ( data === undefined && elem.nodeType === 1 ) { - - var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); - - data = elem.getAttribute( name ); - - if ( typeof data === "string" ) { - try { - data = data === "true" ? true : - data === "false" ? false : - data === "null" ? null : - jQuery.isNumeric( data ) ? +data : - rbrace.test( data ) ? jQuery.parseJSON( data ) : - data; - } catch( e ) {} - - // Make sure we set the data so it isn't changed later - jQuery.data( elem, key, data ); - - } else { - data = undefined; - } - } - - return data; -} - -// checks a cache object for emptiness -function isEmptyDataObject( obj ) { - for ( var name in obj ) { - - // if the public data object is empty, the private is still empty - if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { - continue; - } - if ( name !== "toJSON" ) { - return false; - } - } - - return true; -} - - - - -function handleQueueMarkDefer( elem, type, src ) { - var deferDataKey = type + "defer", - queueDataKey = type + "queue", - markDataKey = type + "mark", - defer = jQuery._data( elem, deferDataKey ); - if ( defer && - ( src === "queue" || !jQuery._data(elem, queueDataKey) ) && - ( src === "mark" || !jQuery._data(elem, markDataKey) ) ) { - // Give room for hard-coded callbacks to fire first - // and eventually mark/queue something else on the element - setTimeout( function() { - if ( !jQuery._data( elem, queueDataKey ) && - !jQuery._data( elem, markDataKey ) ) { - jQuery.removeData( elem, deferDataKey, true ); - defer.fire(); - } - }, 0 ); - } -} - -jQuery.extend({ - - _mark: function( elem, type ) { - if ( elem ) { - type = ( type || "fx" ) + "mark"; - jQuery._data( elem, type, (jQuery._data( elem, type ) || 0) + 1 ); - } - }, - - _unmark: function( force, elem, type ) { - if ( force !== true ) { - type = elem; - elem = force; - force = false; - } - if ( elem ) { - type = type || "fx"; - var key = type + "mark", - count = force ? 0 : ( (jQuery._data( elem, key ) || 1) - 1 ); - if ( count ) { - jQuery._data( elem, key, count ); - } else { - jQuery.removeData( elem, key, true ); - handleQueueMarkDefer( elem, type, "mark" ); - } - } - }, - - queue: function( elem, type, data ) { - var q; - if ( elem ) { - type = ( type || "fx" ) + "queue"; - q = jQuery._data( elem, type ); - - // Speed up dequeue by getting out quickly if this is just a lookup - if ( data ) { - if ( !q || jQuery.isArray(data) ) { - q = jQuery._data( elem, type, jQuery.makeArray(data) ); - } else { - q.push( data ); - } - } - return q || []; - } - }, - - dequeue: function( elem, type ) { - type = type || "fx"; - - var queue = jQuery.queue( elem, type ), - fn = queue.shift(), - hooks = {}; - - // If the fx queue is dequeued, always remove the progress sentinel - if ( fn === "inprogress" ) { - fn = queue.shift(); - } - - if ( fn ) { - // Add a progress sentinel to prevent the fx queue from being - // automatically dequeued - if ( type === "fx" ) { - queue.unshift( "inprogress" ); - } - - jQuery._data( elem, type + ".run", hooks ); - fn.call( elem, function() { - jQuery.dequeue( elem, type ); - }, hooks ); - } - - if ( !queue.length ) { - jQuery.removeData( elem, type + "queue " + type + ".run", true ); - handleQueueMarkDefer( elem, type, "queue" ); - } - } -}); - -jQuery.fn.extend({ - queue: function( type, data ) { - var setter = 2; - - if ( typeof type !== "string" ) { - data = type; - type = "fx"; - setter--; - } - - if ( arguments.length < setter ) { - return jQuery.queue( this[0], type ); - } - - return data === undefined ? - this : - this.each(function() { - var queue = jQuery.queue( this, type, data ); - - if ( type === "fx" && queue[0] !== "inprogress" ) { - jQuery.dequeue( this, type ); - } - }); - }, - dequeue: function( type ) { - return this.each(function() { - jQuery.dequeue( this, type ); - }); - }, - // Based off of the plugin by Clint Helfers, with permission. - // http://blindsignals.com/index.php/2009/07/jquery-delay/ - delay: function( time, type ) { - time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; - type = type || "fx"; - - return this.queue( type, function( next, hooks ) { - var timeout = setTimeout( next, time ); - hooks.stop = function() { - clearTimeout( timeout ); - }; - }); - }, - clearQueue: function( type ) { - return this.queue( type || "fx", [] ); - }, - // Get a promise resolved when queues of a certain type - // are emptied (fx is the type by default) - promise: function( type, object ) { - if ( typeof type !== "string" ) { - object = type; - type = undefined; - } - type = type || "fx"; - var defer = jQuery.Deferred(), - elements = this, - i = elements.length, - count = 1, - deferDataKey = type + "defer", - queueDataKey = type + "queue", - markDataKey = type + "mark", - tmp; - function resolve() { - if ( !( --count ) ) { - defer.resolveWith( elements, [ elements ] ); - } - } - while( i-- ) { - if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) || - ( jQuery.data( elements[ i ], queueDataKey, undefined, true ) || - jQuery.data( elements[ i ], markDataKey, undefined, true ) ) && - jQuery.data( elements[ i ], deferDataKey, jQuery.Callbacks( "once memory" ), true ) )) { - count++; - tmp.add( resolve ); - } - } - resolve(); - return defer.promise( object ); - } -}); - - - - -var rclass = /[\n\t\r]/g, - rspace = /\s+/, - rreturn = /\r/g, - rtype = /^(?:button|input)$/i, - rfocusable = /^(?:button|input|object|select|textarea)$/i, - rclickable = /^a(?:rea)?$/i, - rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, - getSetAttribute = jQuery.support.getSetAttribute, - nodeHook, boolHook, fixSpecified; - -jQuery.fn.extend({ - attr: function( name, value ) { - return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); - }, - - removeAttr: function( name ) { - return this.each(function() { - jQuery.removeAttr( this, name ); - }); - }, - - prop: function( name, value ) { - return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); - }, - - removeProp: function( name ) { - name = jQuery.propFix[ name ] || name; - return this.each(function() { - // try/catch handles cases where IE balks (such as removing a property on window) - try { - this[ name ] = undefined; - delete this[ name ]; - } catch( e ) {} - }); - }, - - addClass: function( value ) { - var classNames, i, l, elem, - setClass, c, cl; - - if ( jQuery.isFunction( value ) ) { - return this.each(function( j ) { - jQuery( this ).addClass( value.call(this, j, this.className) ); - }); - } - - if ( value && typeof value === "string" ) { - classNames = value.split( rspace ); - - for ( i = 0, l = this.length; i < l; i++ ) { - elem = this[ i ]; - - if ( elem.nodeType === 1 ) { - if ( !elem.className && classNames.length === 1 ) { - elem.className = value; - - } else { - setClass = " " + elem.className + " "; - - for ( c = 0, cl = classNames.length; c < cl; c++ ) { - if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { - setClass += classNames[ c ] + " "; - } - } - elem.className = jQuery.trim( setClass ); - } - } - } - } - - return this; - }, - - removeClass: function( value ) { - var classNames, i, l, elem, className, c, cl; - - if ( jQuery.isFunction( value ) ) { - return this.each(function( j ) { - jQuery( this ).removeClass( value.call(this, j, this.className) ); - }); - } - - if ( (value && typeof value === "string") || value === undefined ) { - classNames = ( value || "" ).split( rspace ); - - for ( i = 0, l = this.length; i < l; i++ ) { - elem = this[ i ]; - - if ( elem.nodeType === 1 && elem.className ) { - if ( value ) { - className = (" " + elem.className + " ").replace( rclass, " " ); - for ( c = 0, cl = classNames.length; c < cl; c++ ) { - className = className.replace(" " + classNames[ c ] + " ", " "); - } - elem.className = jQuery.trim( className ); - - } else { - elem.className = ""; - } - } - } - } - - return this; - }, - - toggleClass: function( value, stateVal ) { - var type = typeof value, - isBool = typeof stateVal === "boolean"; - - if ( jQuery.isFunction( value ) ) { - return this.each(function( i ) { - jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); - }); - } - - return this.each(function() { - if ( type === "string" ) { - // toggle individual class names - var className, - i = 0, - self = jQuery( this ), - state = stateVal, - classNames = value.split( rspace ); - - while ( (className = classNames[ i++ ]) ) { - // check each className given, space seperated list - state = isBool ? state : !self.hasClass( className ); - self[ state ? "addClass" : "removeClass" ]( className ); - } - - } else if ( type === "undefined" || type === "boolean" ) { - if ( this.className ) { - // store className if set - jQuery._data( this, "__className__", this.className ); - } - - // toggle whole className - this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; - } - }); - }, - - hasClass: function( selector ) { - var className = " " + selector + " ", - i = 0, - l = this.length; - for ( ; i < l; i++ ) { - if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { - return true; - } - } - - return false; - }, - - val: function( value ) { - var hooks, ret, isFunction, - elem = this[0]; - - if ( !arguments.length ) { - if ( elem ) { - hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; - - if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { - return ret; - } - - ret = elem.value; - - return typeof ret === "string" ? - // handle most common string cases - ret.replace(rreturn, "") : - // handle cases where value is null/undef or number - ret == null ? "" : ret; - } - - return; - } - - isFunction = jQuery.isFunction( value ); - - return this.each(function( i ) { - var self = jQuery(this), val; - - if ( this.nodeType !== 1 ) { - return; - } - - if ( isFunction ) { - val = value.call( this, i, self.val() ); - } else { - val = value; - } - - // Treat null/undefined as ""; convert numbers to string - if ( val == null ) { - val = ""; - } else if ( typeof val === "number" ) { - val += ""; - } else if ( jQuery.isArray( val ) ) { - val = jQuery.map(val, function ( value ) { - return value == null ? "" : value + ""; - }); - } - - hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; - - // If set returns undefined, fall back to normal setting - if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { - this.value = val; - } - }); - } -}); - -jQuery.extend({ - valHooks: { - option: { - get: function( elem ) { - // attributes.value is undefined in Blackberry 4.7 but - // uses .value. See #6932 - var val = elem.attributes.value; - return !val || val.specified ? elem.value : elem.text; - } - }, - select: { - get: function( elem ) { - var value, i, max, option, - index = elem.selectedIndex, - values = [], - options = elem.options, - one = elem.type === "select-one"; - - // Nothing was selected - if ( index < 0 ) { - return null; - } - - // Loop through all the selected options - i = one ? index : 0; - max = one ? index + 1 : options.length; - for ( ; i < max; i++ ) { - option = options[ i ]; - - // Don't return options that are disabled or in a disabled optgroup - if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && - (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { - - // Get the specific value for the option - value = jQuery( option ).val(); - - // We don't need an array for one selects - if ( one ) { - return value; - } - - // Multi-Selects return an array - values.push( value ); - } - } - - // Fixes Bug #2551 -- select.val() broken in IE after form.reset() - if ( one && !values.length && options.length ) { - return jQuery( options[ index ] ).val(); - } - - return values; - }, - - set: function( elem, value ) { - var values = jQuery.makeArray( value ); - - jQuery(elem).find("option").each(function() { - this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; - }); - - if ( !values.length ) { - elem.selectedIndex = -1; - } - return values; - } - } - }, - - attrFn: { - val: true, - css: true, - html: true, - text: true, - data: true, - width: true, - height: true, - offset: true - }, - - attr: function( elem, name, value, pass ) { - var ret, hooks, notxml, - nType = elem.nodeType; - - // don't get/set attributes on text, comment and attribute nodes - if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { - return; - } - - if ( pass && name in jQuery.attrFn ) { - return jQuery( elem )[ name ]( value ); - } - - // Fallback to prop when attributes are not supported - if ( typeof elem.getAttribute === "undefined" ) { - return jQuery.prop( elem, name, value ); - } - - notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); - - // All attributes are lowercase - // Grab necessary hook if one is defined - if ( notxml ) { - name = name.toLowerCase(); - hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); - } - - if ( value !== undefined ) { - - if ( value === null ) { - jQuery.removeAttr( elem, name ); - return; - - } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { - return ret; - - } else { - elem.setAttribute( name, "" + value ); - return value; - } - - } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { - return ret; - - } else { - - ret = elem.getAttribute( name ); - - // Non-existent attributes return null, we normalize to undefined - return ret === null ? - undefined : - ret; - } - }, - - removeAttr: function( elem, value ) { - var propName, attrNames, name, l, isBool, - i = 0; - - if ( value && elem.nodeType === 1 ) { - attrNames = value.toLowerCase().split( rspace ); - l = attrNames.length; - - for ( ; i < l; i++ ) { - name = attrNames[ i ]; - - if ( name ) { - propName = jQuery.propFix[ name ] || name; - isBool = rboolean.test( name ); - - // See #9699 for explanation of this approach (setting first, then removal) - // Do not do this for boolean attributes (see #10870) - if ( !isBool ) { - jQuery.attr( elem, name, "" ); - } - elem.removeAttribute( getSetAttribute ? name : propName ); - - // Set corresponding property to false for boolean attributes - if ( isBool && propName in elem ) { - elem[ propName ] = false; - } - } - } - } - }, - - attrHooks: { - type: { - set: function( elem, value ) { - // We can't allow the type property to be changed (since it causes problems in IE) - if ( rtype.test( elem.nodeName ) && elem.parentNode ) { - jQuery.error( "type property can't be changed" ); - } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { - // Setting the type on a radio button after the value resets the value in IE6-9 - // Reset value to it's default in case type is set after value - // This is for element creation - var val = elem.value; - elem.setAttribute( "type", value ); - if ( val ) { - elem.value = val; - } - return value; - } - } - }, - // Use the value property for back compat - // Use the nodeHook for button elements in IE6/7 (#1954) - value: { - get: function( elem, name ) { - if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { - return nodeHook.get( elem, name ); - } - return name in elem ? - elem.value : - null; - }, - set: function( elem, value, name ) { - if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { - return nodeHook.set( elem, value, name ); - } - // Does not return so that setAttribute is also used - elem.value = value; - } - } - }, - - propFix: { - tabindex: "tabIndex", - readonly: "readOnly", - "for": "htmlFor", - "class": "className", - maxlength: "maxLength", - cellspacing: "cellSpacing", - cellpadding: "cellPadding", - rowspan: "rowSpan", - colspan: "colSpan", - usemap: "useMap", - frameborder: "frameBorder", - contenteditable: "contentEditable" - }, - - prop: function( elem, name, value ) { - var ret, hooks, notxml, - nType = elem.nodeType; - - // don't get/set properties on text, comment and attribute nodes - if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { - return; - } - - notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); - - if ( notxml ) { - // Fix name and attach hooks - name = jQuery.propFix[ name ] || name; - hooks = jQuery.propHooks[ name ]; - } - - if ( value !== undefined ) { - if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { - return ret; - - } else { - return ( elem[ name ] = value ); - } - - } else { - if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { - return ret; - - } else { - return elem[ name ]; - } - } - }, - - propHooks: { - tabIndex: { - get: function( elem ) { - // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set - // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ - var attributeNode = elem.getAttributeNode("tabindex"); - - return attributeNode && attributeNode.specified ? - parseInt( attributeNode.value, 10 ) : - rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? - 0 : - undefined; - } - } - } -}); - -// Add the tabIndex propHook to attrHooks for back-compat (different case is intentional) -jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex; - -// Hook for boolean attributes -boolHook = { - get: function( elem, name ) { - // Align boolean attributes with corresponding properties - // Fall back to attribute presence where some booleans are not supported - var attrNode, - property = jQuery.prop( elem, name ); - return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? - name.toLowerCase() : - undefined; - }, - set: function( elem, value, name ) { - var propName; - if ( value === false ) { - // Remove boolean attributes when set to false - jQuery.removeAttr( elem, name ); - } else { - // value is true since we know at this point it's type boolean and not false - // Set boolean attributes to the same name and set the DOM property - propName = jQuery.propFix[ name ] || name; - if ( propName in elem ) { - // Only set the IDL specifically if it already exists on the element - elem[ propName ] = true; - } - - elem.setAttribute( name, name.toLowerCase() ); - } - return name; - } -}; - -// IE6/7 do not support getting/setting some attributes with get/setAttribute -if ( !getSetAttribute ) { - - fixSpecified = { - name: true, - id: true, - coords: true - }; - - // Use this for any attribute in IE6/7 - // This fixes almost every IE6/7 issue - nodeHook = jQuery.valHooks.button = { - get: function( elem, name ) { - var ret; - ret = elem.getAttributeNode( name ); - return ret && ( fixSpecified[ name ] ? ret.nodeValue !== "" : ret.specified ) ? - ret.nodeValue : - undefined; - }, - set: function( elem, value, name ) { - // Set the existing or create a new attribute node - var ret = elem.getAttributeNode( name ); - if ( !ret ) { - ret = document.createAttribute( name ); - elem.setAttributeNode( ret ); - } - return ( ret.nodeValue = value + "" ); - } - }; - - // Apply the nodeHook to tabindex - jQuery.attrHooks.tabindex.set = nodeHook.set; - - // Set width and height to auto instead of 0 on empty string( Bug #8150 ) - // This is for removals - jQuery.each([ "width", "height" ], function( i, name ) { - jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { - set: function( elem, value ) { - if ( value === "" ) { - elem.setAttribute( name, "auto" ); - return value; - } - } - }); - }); - - // Set contenteditable to false on removals(#10429) - // Setting to empty string throws an error as an invalid value - jQuery.attrHooks.contenteditable = { - get: nodeHook.get, - set: function( elem, value, name ) { - if ( value === "" ) { - value = "false"; - } - nodeHook.set( elem, value, name ); - } - }; -} - - -// Some attributes require a special call on IE -if ( !jQuery.support.hrefNormalized ) { - jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { - jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { - get: function( elem ) { - var ret = elem.getAttribute( name, 2 ); - return ret === null ? undefined : ret; - } - }); - }); -} - -if ( !jQuery.support.style ) { - jQuery.attrHooks.style = { - get: function( elem ) { - // Return undefined in the case of empty string - // Normalize to lowercase since IE uppercases css property names - return elem.style.cssText.toLowerCase() || undefined; - }, - set: function( elem, value ) { - return ( elem.style.cssText = "" + value ); - } - }; -} - -// Safari mis-reports the default selected property of an option -// Accessing the parent's selectedIndex property fixes it -if ( !jQuery.support.optSelected ) { - jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { - get: function( elem ) { - var parent = elem.parentNode; - - if ( parent ) { - parent.selectedIndex; - - // Make sure that it also works with optgroups, see #5701 - if ( parent.parentNode ) { - parent.parentNode.selectedIndex; - } - } - return null; - } - }); -} - -// IE6/7 call enctype encoding -if ( !jQuery.support.enctype ) { - jQuery.propFix.enctype = "encoding"; -} - -// Radios and checkboxes getter/setter -if ( !jQuery.support.checkOn ) { - jQuery.each([ "radio", "checkbox" ], function() { - jQuery.valHooks[ this ] = { - get: function( elem ) { - // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified - return elem.getAttribute("value") === null ? "on" : elem.value; - } - }; - }); -} -jQuery.each([ "radio", "checkbox" ], function() { - jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { - set: function( elem, value ) { - if ( jQuery.isArray( value ) ) { - return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); - } - } - }); -}); - - - - -var rformElems = /^(?:textarea|input|select)$/i, - rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/, - rhoverHack = /(?:^|\s)hover(\.\S+)?\b/, - rkeyEvent = /^key/, - rmouseEvent = /^(?:mouse|contextmenu)|click/, - rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, - rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/, - quickParse = function( selector ) { - var quick = rquickIs.exec( selector ); - if ( quick ) { - // 0 1 2 3 - // [ _, tag, id, class ] - quick[1] = ( quick[1] || "" ).toLowerCase(); - quick[3] = quick[3] && new RegExp( "(?:^|\\s)" + quick[3] + "(?:\\s|$)" ); - } - return quick; - }, - quickIs = function( elem, m ) { - var attrs = elem.attributes || {}; - return ( - (!m[1] || elem.nodeName.toLowerCase() === m[1]) && - (!m[2] || (attrs.id || {}).value === m[2]) && - (!m[3] || m[3].test( (attrs[ "class" ] || {}).value )) - ); - }, - hoverHack = function( events ) { - return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); - }; - -/* - * Helper functions for managing events -- not part of the public interface. - * Props to Dean Edwards' addEvent library for many of the ideas. - */ -jQuery.event = { - - add: function( elem, types, handler, data, selector ) { - - var elemData, eventHandle, events, - t, tns, type, namespaces, handleObj, - handleObjIn, quick, handlers, special; - - // Don't attach events to noData or text/comment nodes (allow plain objects tho) - if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { - return; - } - - // Caller can pass in an object of custom data in lieu of the handler - if ( handler.handler ) { - handleObjIn = handler; - handler = handleObjIn.handler; - selector = handleObjIn.selector; - } - - // Make sure that the handler has a unique ID, used to find/remove it later - if ( !handler.guid ) { - handler.guid = jQuery.guid++; - } - - // Init the element's event structure and main handler, if this is the first - events = elemData.events; - if ( !events ) { - elemData.events = events = {}; - } - eventHandle = elemData.handle; - if ( !eventHandle ) { - elemData.handle = eventHandle = function( e ) { - // Discard the second event of a jQuery.event.trigger() and - // when an event is called after a page has unloaded - return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? - jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : - undefined; - }; - // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events - eventHandle.elem = elem; - } - - // Handle multiple events separated by a space - // jQuery(...).bind("mouseover mouseout", fn); - types = jQuery.trim( hoverHack(types) ).split( " " ); - for ( t = 0; t < types.length; t++ ) { - - tns = rtypenamespace.exec( types[t] ) || []; - type = tns[1]; - namespaces = ( tns[2] || "" ).split( "." ).sort(); - - // If event changes its type, use the special event handlers for the changed type - special = jQuery.event.special[ type ] || {}; - - // If selector defined, determine special event api type, otherwise given type - type = ( selector ? special.delegateType : special.bindType ) || type; - - // Update special based on newly reset type - special = jQuery.event.special[ type ] || {}; - - // handleObj is passed to all event handlers - handleObj = jQuery.extend({ - type: type, - origType: tns[1], - data: data, - handler: handler, - guid: handler.guid, - selector: selector, - quick: selector && quickParse( selector ), - namespace: namespaces.join(".") - }, handleObjIn ); - - // Init the event handler queue if we're the first - handlers = events[ type ]; - if ( !handlers ) { - handlers = events[ type ] = []; - handlers.delegateCount = 0; - - // Only use addEventListener/attachEvent if the special events handler returns false - if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { - // Bind the global event handler to the element - if ( elem.addEventListener ) { - elem.addEventListener( type, eventHandle, false ); - - } else if ( elem.attachEvent ) { - elem.attachEvent( "on" + type, eventHandle ); - } - } - } - - if ( special.add ) { - special.add.call( elem, handleObj ); - - if ( !handleObj.handler.guid ) { - handleObj.handler.guid = handler.guid; - } - } - - // Add to the element's handler list, delegates in front - if ( selector ) { - handlers.splice( handlers.delegateCount++, 0, handleObj ); - } else { - handlers.push( handleObj ); - } - - // Keep track of which events have ever been used, for event optimization - jQuery.event.global[ type ] = true; - } - - // Nullify elem to prevent memory leaks in IE - elem = null; - }, - - global: {}, - - // Detach an event or set of events from an element - remove: function( elem, types, handler, selector, mappedTypes ) { - - var elemData = jQuery.hasData( elem ) && jQuery._data( elem ), - t, tns, type, origType, namespaces, origCount, - j, events, special, handle, eventType, handleObj; - - if ( !elemData || !(events = elemData.events) ) { - return; - } - - // Once for each type.namespace in types; type may be omitted - types = jQuery.trim( hoverHack( types || "" ) ).split(" "); - for ( t = 0; t < types.length; t++ ) { - tns = rtypenamespace.exec( types[t] ) || []; - type = origType = tns[1]; - namespaces = tns[2]; - - // Unbind all events (on this namespace, if provided) for the element - if ( !type ) { - for ( type in events ) { - jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); - } - continue; - } - - special = jQuery.event.special[ type ] || {}; - type = ( selector? special.delegateType : special.bindType ) || type; - eventType = events[ type ] || []; - origCount = eventType.length; - namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.)?") + "(\\.|$)") : null; - - // Remove matching events - for ( j = 0; j < eventType.length; j++ ) { - handleObj = eventType[ j ]; - - if ( ( mappedTypes || origType === handleObj.origType ) && - ( !handler || handler.guid === handleObj.guid ) && - ( !namespaces || namespaces.test( handleObj.namespace ) ) && - ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { - eventType.splice( j--, 1 ); - - if ( handleObj.selector ) { - eventType.delegateCount--; - } - if ( special.remove ) { - special.remove.call( elem, handleObj ); - } - } - } - - // Remove generic event handler if we removed something and no more handlers exist - // (avoids potential for endless recursion during removal of special event handlers) - if ( eventType.length === 0 && origCount !== eventType.length ) { - if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { - jQuery.removeEvent( elem, type, elemData.handle ); - } - - delete events[ type ]; - } - } - - // Remove the expando if it's no longer used - if ( jQuery.isEmptyObject( events ) ) { - handle = elemData.handle; - if ( handle ) { - handle.elem = null; - } - - // removeData also checks for emptiness and clears the expando if empty - // so use it instead of delete - jQuery.removeData( elem, [ "events", "handle" ], true ); - } - }, - - // Events that are safe to short-circuit if no handlers are attached. - // Native DOM events should not be added, they may have inline handlers. - customEvent: { - "getData": true, - "setData": true, - "changeData": true - }, - - trigger: function( event, data, elem, onlyHandlers ) { - // Don't do events on text and comment nodes - if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { - return; - } - - // Event object or event type - var type = event.type || event, - namespaces = [], - cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType; - - // focus/blur morphs to focusin/out; ensure we're not firing them right now - if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { - return; - } - - if ( type.indexOf( "!" ) >= 0 ) { - // Exclusive events trigger only for the exact event (no namespaces) - type = type.slice(0, -1); - exclusive = true; - } - - if ( type.indexOf( "." ) >= 0 ) { - // Namespaced trigger; create a regexp to match event type in handle() - namespaces = type.split("."); - type = namespaces.shift(); - namespaces.sort(); - } - - if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { - // No jQuery handlers for this event type, and it can't have inline handlers - return; - } - - // Caller can pass in an Event, Object, or just an event type string - event = typeof event === "object" ? - // jQuery.Event object - event[ jQuery.expando ] ? event : - // Object literal - new jQuery.Event( type, event ) : - // Just the event type (string) - new jQuery.Event( type ); - - event.type = type; - event.isTrigger = true; - event.exclusive = exclusive; - event.namespace = namespaces.join( "." ); - event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)") : null; - ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; - - // Handle a global trigger - if ( !elem ) { - - // TODO: Stop taunting the data cache; remove global events and always attach to document - cache = jQuery.cache; - for ( i in cache ) { - if ( cache[ i ].events && cache[ i ].events[ type ] ) { - jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); - } - } - return; - } - - // Clean up the event in case it is being reused - event.result = undefined; - if ( !event.target ) { - event.target = elem; - } - - // Clone any incoming data and prepend the event, creating the handler arg list - data = data != null ? jQuery.makeArray( data ) : []; - data.unshift( event ); - - // Allow special events to draw outside the lines - special = jQuery.event.special[ type ] || {}; - if ( special.trigger && special.trigger.apply( elem, data ) === false ) { - return; - } - - // Determine event propagation path in advance, per W3C events spec (#9951) - // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) - eventPath = [[ elem, special.bindType || type ]]; - if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { - - bubbleType = special.delegateType || type; - cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; - old = null; - for ( ; cur; cur = cur.parentNode ) { - eventPath.push([ cur, bubbleType ]); - old = cur; - } - - // Only add window if we got to document (e.g., not plain obj or detached DOM) - if ( old && old === elem.ownerDocument ) { - eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); - } - } - - // Fire handlers on the event path - for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { - - cur = eventPath[i][0]; - event.type = eventPath[i][1]; - - handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); - if ( handle ) { - handle.apply( cur, data ); - } - // Note that this is a bare JS function and not a jQuery handler - handle = ontype && cur[ ontype ]; - if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === false ) { - event.preventDefault(); - } - } - event.type = type; - - // If nobody prevented the default action, do it now - if ( !onlyHandlers && !event.isDefaultPrevented() ) { - - if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && - !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { - - // Call a native DOM method on the target with the same name name as the event. - // Can't use an .isFunction() check here because IE6/7 fails that test. - // Don't do default actions on window, that's where global variables be (#6170) - // IE<9 dies on focus/blur to hidden element (#1486) - if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { - - // Don't re-trigger an onFOO event when we call its FOO() method - old = elem[ ontype ]; - - if ( old ) { - elem[ ontype ] = null; - } - - // Prevent re-triggering of the same event, since we already bubbled it above - jQuery.event.triggered = type; - elem[ type ](); - jQuery.event.triggered = undefined; - - if ( old ) { - elem[ ontype ] = old; - } - } - } - } - - return event.result; - }, - - dispatch: function( event ) { - - // Make a writable jQuery.Event from the native event object - event = jQuery.event.fix( event || window.event ); - - var handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), - delegateCount = handlers.delegateCount, - args = [].slice.call( arguments, 0 ), - run_all = !event.exclusive && !event.namespace, - special = jQuery.event.special[ event.type ] || {}, - handlerQueue = [], - i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related; - - // Use the fix-ed jQuery.Event rather than the (read-only) native event - args[0] = event; - event.delegateTarget = this; - - // Call the preDispatch hook for the mapped type, and let it bail if desired - if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { - return; - } - - // Determine handlers that should run if there are delegated events - // Avoid non-left-click bubbling in Firefox (#3861) - if ( delegateCount && !(event.button && event.type === "click") ) { - - // Pregenerate a single jQuery object for reuse with .is() - jqcur = jQuery(this); - jqcur.context = this.ownerDocument || this; - - for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { - - // Don't process events on disabled elements (#6911, #8165) - if ( cur.disabled !== true ) { - selMatch = {}; - matches = []; - jqcur[0] = cur; - for ( i = 0; i < delegateCount; i++ ) { - handleObj = handlers[ i ]; - sel = handleObj.selector; - - if ( selMatch[ sel ] === undefined ) { - selMatch[ sel ] = ( - handleObj.quick ? quickIs( cur, handleObj.quick ) : jqcur.is( sel ) - ); - } - if ( selMatch[ sel ] ) { - matches.push( handleObj ); - } - } - if ( matches.length ) { - handlerQueue.push({ elem: cur, matches: matches }); - } - } - } - } - - // Add the remaining (directly-bound) handlers - if ( handlers.length > delegateCount ) { - handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); - } - - // Run delegates first; they may want to stop propagation beneath us - for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { - matched = handlerQueue[ i ]; - event.currentTarget = matched.elem; - - for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { - handleObj = matched.matches[ j ]; - - // Triggered event must either 1) be non-exclusive and have no namespace, or - // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). - if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { - - event.data = handleObj.data; - event.handleObj = handleObj; - - ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) - .apply( matched.elem, args ); - - if ( ret !== undefined ) { - event.result = ret; - if ( ret === false ) { - event.preventDefault(); - event.stopPropagation(); - } - } - } - } - } - - // Call the postDispatch hook for the mapped type - if ( special.postDispatch ) { - special.postDispatch.call( this, event ); - } - - return event.result; - }, - - // Includes some event props shared by KeyEvent and MouseEvent - // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** - props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), - - fixHooks: {}, - - keyHooks: { - props: "char charCode key keyCode".split(" "), - filter: function( event, original ) { - - // Add which for key events - if ( event.which == null ) { - event.which = original.charCode != null ? original.charCode : original.keyCode; - } - - return event; - } - }, - - mouseHooks: { - props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), - filter: function( event, original ) { - var eventDoc, doc, body, - button = original.button, - fromElement = original.fromElement; - - // Calculate pageX/Y if missing and clientX/Y available - if ( event.pageX == null && original.clientX != null ) { - eventDoc = event.target.ownerDocument || document; - doc = eventDoc.documentElement; - body = eventDoc.body; - - event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); - event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); - } - - // Add relatedTarget, if necessary - if ( !event.relatedTarget && fromElement ) { - event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; - } - - // Add which for click: 1 === left; 2 === middle; 3 === right - // Note: button is not normalized, so don't use it - if ( !event.which && button !== undefined ) { - event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); - } - - return event; - } - }, - - fix: function( event ) { - if ( event[ jQuery.expando ] ) { - return event; - } - - // Create a writable copy of the event object and normalize some properties - var i, prop, - originalEvent = event, - fixHook = jQuery.event.fixHooks[ event.type ] || {}, - copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; - - event = jQuery.Event( originalEvent ); - - for ( i = copy.length; i; ) { - prop = copy[ --i ]; - event[ prop ] = originalEvent[ prop ]; - } - - // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) - if ( !event.target ) { - event.target = originalEvent.srcElement || document; - } - - // Target should not be a text node (#504, Safari) - if ( event.target.nodeType === 3 ) { - event.target = event.target.parentNode; - } - - // For mouse/key events; add metaKey if it's not there (#3368, IE6/7/8) - if ( event.metaKey === undefined ) { - event.metaKey = event.ctrlKey; - } - - return fixHook.filter? fixHook.filter( event, originalEvent ) : event; - }, - - special: { - ready: { - // Make sure the ready event is setup - setup: jQuery.bindReady - }, - - load: { - // Prevent triggered image.load events from bubbling to window.load - noBubble: true - }, - - focus: { - delegateType: "focusin" - }, - blur: { - delegateType: "focusout" - }, - - beforeunload: { - setup: function( data, namespaces, eventHandle ) { - // We only want to do this special case on windows - if ( jQuery.isWindow( this ) ) { - this.onbeforeunload = eventHandle; - } - }, - - teardown: function( namespaces, eventHandle ) { - if ( this.onbeforeunload === eventHandle ) { - this.onbeforeunload = null; - } - } - } - }, - - simulate: function( type, elem, event, bubble ) { - // Piggyback on a donor event to simulate a different one. - // Fake originalEvent to avoid donor's stopPropagation, but if the - // simulated event prevents default then we do the same on the donor. - var e = jQuery.extend( - new jQuery.Event(), - event, - { type: type, - isSimulated: true, - originalEvent: {} - } - ); - if ( bubble ) { - jQuery.event.trigger( e, null, elem ); - } else { - jQuery.event.dispatch.call( elem, e ); - } - if ( e.isDefaultPrevented() ) { - event.preventDefault(); - } - } -}; - -// Some plugins are using, but it's undocumented/deprecated and will be removed. -// The 1.7 special event interface should provide all the hooks needed now. -jQuery.event.handle = jQuery.event.dispatch; - -jQuery.removeEvent = document.removeEventListener ? - function( elem, type, handle ) { - if ( elem.removeEventListener ) { - elem.removeEventListener( type, handle, false ); - } - } : - function( elem, type, handle ) { - if ( elem.detachEvent ) { - elem.detachEvent( "on" + type, handle ); - } - }; - -jQuery.Event = function( src, props ) { - // Allow instantiation without the 'new' keyword - if ( !(this instanceof jQuery.Event) ) { - return new jQuery.Event( src, props ); - } - - // Event object - if ( src && src.type ) { - this.originalEvent = src; - this.type = src.type; - - // Events bubbling up the document may have been marked as prevented - // by a handler lower down the tree; reflect the correct value. - this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || - src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; - - // Event type - } else { - this.type = src; - } - - // Put explicitly provided properties onto the event object - if ( props ) { - jQuery.extend( this, props ); - } - - // Create a timestamp if incoming event doesn't have one - this.timeStamp = src && src.timeStamp || jQuery.now(); - - // Mark it as fixed - this[ jQuery.expando ] = true; -}; - -function returnFalse() { - return false; -} -function returnTrue() { - return true; -} - -// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding -// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html -jQuery.Event.prototype = { - preventDefault: function() { - this.isDefaultPrevented = returnTrue; - - var e = this.originalEvent; - if ( !e ) { - return; - } - - // if preventDefault exists run it on the original event - if ( e.preventDefault ) { - e.preventDefault(); - - // otherwise set the returnValue property of the original event to false (IE) - } else { - e.returnValue = false; - } - }, - stopPropagation: function() { - this.isPropagationStopped = returnTrue; - - var e = this.originalEvent; - if ( !e ) { - return; - } - // if stopPropagation exists run it on the original event - if ( e.stopPropagation ) { - e.stopPropagation(); - } - // otherwise set the cancelBubble property of the original event to true (IE) - e.cancelBubble = true; - }, - stopImmediatePropagation: function() { - this.isImmediatePropagationStopped = returnTrue; - this.stopPropagation(); - }, - isDefaultPrevented: returnFalse, - isPropagationStopped: returnFalse, - isImmediatePropagationStopped: returnFalse -}; - -// Create mouseenter/leave events using mouseover/out and event-time checks -jQuery.each({ - mouseenter: "mouseover", - mouseleave: "mouseout" -}, function( orig, fix ) { - jQuery.event.special[ orig ] = { - delegateType: fix, - bindType: fix, - - handle: function( event ) { - var target = this, - related = event.relatedTarget, - handleObj = event.handleObj, - selector = handleObj.selector, - ret; - - // For mousenter/leave call the handler if related is outside the target. - // NB: No relatedTarget if the mouse left/entered the browser window - if ( !related || (related !== target && !jQuery.contains( target, related )) ) { - event.type = handleObj.origType; - ret = handleObj.handler.apply( this, arguments ); - event.type = fix; - } - return ret; - } - }; -}); - -// IE submit delegation -if ( !jQuery.support.submitBubbles ) { - - jQuery.event.special.submit = { - setup: function() { - // Only need this for delegated form submit events - if ( jQuery.nodeName( this, "form" ) ) { - return false; - } - - // Lazy-add a submit handler when a descendant form may potentially be submitted - jQuery.event.add( this, "click._submit keypress._submit", function( e ) { - // Node name check avoids a VML-related crash in IE (#9807) - var elem = e.target, - form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; - if ( form && !form._submit_attached ) { - jQuery.event.add( form, "submit._submit", function( event ) { - event._submit_bubble = true; - }); - form._submit_attached = true; - } - }); - // return undefined since we don't need an event listener - }, - - postDispatch: function( event ) { - // If form was submitted by the user, bubble the event up the tree - if ( event._submit_bubble ) { - delete event._submit_bubble; - if ( this.parentNode && !event.isTrigger ) { - jQuery.event.simulate( "submit", this.parentNode, event, true ); - } - } - }, - - teardown: function() { - // Only need this for delegated form submit events - if ( jQuery.nodeName( this, "form" ) ) { - return false; - } - - // Remove delegated handlers; cleanData eventually reaps submit handlers attached above - jQuery.event.remove( this, "._submit" ); - } - }; -} - -// IE change delegation and checkbox/radio fix -if ( !jQuery.support.changeBubbles ) { - - jQuery.event.special.change = { - - setup: function() { - - if ( rformElems.test( this.nodeName ) ) { - // IE doesn't fire change on a check/radio until blur; trigger it on click - // after a propertychange. Eat the blur-change in special.change.handle. - // This still fires onchange a second time for check/radio after blur. - if ( this.type === "checkbox" || this.type === "radio" ) { - jQuery.event.add( this, "propertychange._change", function( event ) { - if ( event.originalEvent.propertyName === "checked" ) { - this._just_changed = true; - } - }); - jQuery.event.add( this, "click._change", function( event ) { - if ( this._just_changed && !event.isTrigger ) { - this._just_changed = false; - jQuery.event.simulate( "change", this, event, true ); - } - }); - } - return false; - } - // Delegated event; lazy-add a change handler on descendant inputs - jQuery.event.add( this, "beforeactivate._change", function( e ) { - var elem = e.target; - - if ( rformElems.test( elem.nodeName ) && !elem._change_attached ) { - jQuery.event.add( elem, "change._change", function( event ) { - if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { - jQuery.event.simulate( "change", this.parentNode, event, true ); - } - }); - elem._change_attached = true; - } - }); - }, - - handle: function( event ) { - var elem = event.target; - - // Swallow native change events from checkbox/radio, we already triggered them above - if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { - return event.handleObj.handler.apply( this, arguments ); - } - }, - - teardown: function() { - jQuery.event.remove( this, "._change" ); - - return rformElems.test( this.nodeName ); - } - }; -} - -// Create "bubbling" focus and blur events -if ( !jQuery.support.focusinBubbles ) { - jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { - - // Attach a single capturing handler while someone wants focusin/focusout - var attaches = 0, - handler = function( event ) { - jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); - }; - - jQuery.event.special[ fix ] = { - setup: function() { - if ( attaches++ === 0 ) { - document.addEventListener( orig, handler, true ); - } - }, - teardown: function() { - if ( --attaches === 0 ) { - document.removeEventListener( orig, handler, true ); - } - } - }; - }); -} - -jQuery.fn.extend({ - - on: function( types, selector, data, fn, /*INTERNAL*/ one ) { - var origFn, type; - - // Types can be a map of types/handlers - if ( typeof types === "object" ) { - // ( types-Object, selector, data ) - if ( typeof selector !== "string" ) { // && selector != null - // ( types-Object, data ) - data = data || selector; - selector = undefined; - } - for ( type in types ) { - this.on( type, selector, data, types[ type ], one ); - } - return this; - } - - if ( data == null && fn == null ) { - // ( types, fn ) - fn = selector; - data = selector = undefined; - } else if ( fn == null ) { - if ( typeof selector === "string" ) { - // ( types, selector, fn ) - fn = data; - data = undefined; - } else { - // ( types, data, fn ) - fn = data; - data = selector; - selector = undefined; - } - } - if ( fn === false ) { - fn = returnFalse; - } else if ( !fn ) { - return this; - } - - if ( one === 1 ) { - origFn = fn; - fn = function( event ) { - // Can use an empty set, since event contains the info - jQuery().off( event ); - return origFn.apply( this, arguments ); - }; - // Use same guid so caller can remove using origFn - fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); - } - return this.each( function() { - jQuery.event.add( this, types, fn, data, selector ); - }); - }, - one: function( types, selector, data, fn ) { - return this.on( types, selector, data, fn, 1 ); - }, - off: function( types, selector, fn ) { - if ( types && types.preventDefault && types.handleObj ) { - // ( event ) dispatched jQuery.Event - var handleObj = types.handleObj; - jQuery( types.delegateTarget ).off( - handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, - handleObj.selector, - handleObj.handler - ); - return this; - } - if ( typeof types === "object" ) { - // ( types-object [, selector] ) - for ( var type in types ) { - this.off( type, selector, types[ type ] ); - } - return this; - } - if ( selector === false || typeof selector === "function" ) { - // ( types [, fn] ) - fn = selector; - selector = undefined; - } - if ( fn === false ) { - fn = returnFalse; - } - return this.each(function() { - jQuery.event.remove( this, types, fn, selector ); - }); - }, - - bind: function( types, data, fn ) { - return this.on( types, null, data, fn ); - }, - unbind: function( types, fn ) { - return this.off( types, null, fn ); - }, - - live: function( types, data, fn ) { - jQuery( this.context ).on( types, this.selector, data, fn ); - return this; - }, - die: function( types, fn ) { - jQuery( this.context ).off( types, this.selector || "**", fn ); - return this; - }, - - delegate: function( selector, types, data, fn ) { - return this.on( types, selector, data, fn ); - }, - undelegate: function( selector, types, fn ) { - // ( namespace ) or ( selector, types [, fn] ) - return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector, fn ); - }, - - trigger: function( type, data ) { - return this.each(function() { - jQuery.event.trigger( type, data, this ); - }); - }, - triggerHandler: function( type, data ) { - if ( this[0] ) { - return jQuery.event.trigger( type, data, this[0], true ); - } - }, - - toggle: function( fn ) { - // Save reference to arguments for access in closure - var args = arguments, - guid = fn.guid || jQuery.guid++, - i = 0, - toggler = function( event ) { - // Figure out which function to execute - var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; - jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); - - // Make sure that clicks stop - event.preventDefault(); - - // and execute the function - return args[ lastToggle ].apply( this, arguments ) || false; - }; - - // link all the functions, so any of them can unbind this click handler - toggler.guid = guid; - while ( i < args.length ) { - args[ i++ ].guid = guid; - } - - return this.click( toggler ); - }, - - hover: function( fnOver, fnOut ) { - return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); - } -}); - -jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + - "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + - "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { - - // Handle event binding - jQuery.fn[ name ] = function( data, fn ) { - if ( fn == null ) { - fn = data; - data = null; - } - - return arguments.length > 0 ? - this.on( name, null, data, fn ) : - this.trigger( name ); - }; - - if ( jQuery.attrFn ) { - jQuery.attrFn[ name ] = true; - } - - if ( rkeyEvent.test( name ) ) { - jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; - } - - if ( rmouseEvent.test( name ) ) { - jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; - } -}); - - - -/*! - * Sizzle CSS Selector Engine - * Copyright 2011, The Dojo Foundation - * Released under the MIT, BSD, and GPL Licenses. - * More information: http://sizzlejs.com/ - */ -(function(){ - -var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, - expando = "sizcache" + (Math.random() + '').replace('.', ''), - done = 0, - toString = Object.prototype.toString, - hasDuplicate = false, - baseHasDuplicate = true, - rBackslash = /\\/g, - rReturn = /\r\n/g, - rNonWord = /\W/; - -// Here we check if the JavaScript engine is using some sort of -// optimization where it does not always call our comparision -// function. If that is the case, discard the hasDuplicate value. -// Thus far that includes Google Chrome. -[0, 0].sort(function() { - baseHasDuplicate = false; - return 0; -}); - -var Sizzle = function( selector, context, results, seed ) { - results = results || []; - context = context || document; - - var origContext = context; - - if ( context.nodeType !== 1 && context.nodeType !== 9 ) { - return []; - } - - if ( !selector || typeof selector !== "string" ) { - return results; - } - - var m, set, checkSet, extra, ret, cur, pop, i, - prune = true, - contextXML = Sizzle.isXML( context ), - parts = [], - soFar = selector; - - // Reset the position of the chunker regexp (start from head) - do { - chunker.exec( "" ); - m = chunker.exec( soFar ); - - if ( m ) { - soFar = m[3]; - - parts.push( m[1] ); - - if ( m[2] ) { - extra = m[3]; - break; - } - } - } while ( m ); - - if ( parts.length > 1 && origPOS.exec( selector ) ) { - - if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { - set = posProcess( parts[0] + parts[1], context, seed ); - - } else { - set = Expr.relative[ parts[0] ] ? - [ context ] : - Sizzle( parts.shift(), context ); - - while ( parts.length ) { - selector = parts.shift(); - - if ( Expr.relative[ selector ] ) { - selector += parts.shift(); - } - - set = posProcess( selector, set, seed ); - } - } - - } else { - // Take a shortcut and set the context if the root selector is an ID - // (but not if it'll be faster if the inner selector is an ID) - if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && - Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { - - ret = Sizzle.find( parts.shift(), context, contextXML ); - context = ret.expr ? - Sizzle.filter( ret.expr, ret.set )[0] : - ret.set[0]; - } - - if ( context ) { - ret = seed ? - { expr: parts.pop(), set: makeArray(seed) } : - Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); - - set = ret.expr ? - Sizzle.filter( ret.expr, ret.set ) : - ret.set; - - if ( parts.length > 0 ) { - checkSet = makeArray( set ); - - } else { - prune = false; - } - - while ( parts.length ) { - cur = parts.pop(); - pop = cur; - - if ( !Expr.relative[ cur ] ) { - cur = ""; - } else { - pop = parts.pop(); - } - - if ( pop == null ) { - pop = context; - } - - Expr.relative[ cur ]( checkSet, pop, contextXML ); - } - - } else { - checkSet = parts = []; - } - } - - if ( !checkSet ) { - checkSet = set; - } - - if ( !checkSet ) { - Sizzle.error( cur || selector ); - } - - if ( toString.call(checkSet) === "[object Array]" ) { - if ( !prune ) { - results.push.apply( results, checkSet ); - - } else if ( context && context.nodeType === 1 ) { - for ( i = 0; checkSet[i] != null; i++ ) { - if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { - results.push( set[i] ); - } - } - - } else { - for ( i = 0; checkSet[i] != null; i++ ) { - if ( checkSet[i] && checkSet[i].nodeType === 1 ) { - results.push( set[i] ); - } - } - } - - } else { - makeArray( checkSet, results ); - } - - if ( extra ) { - Sizzle( extra, origContext, results, seed ); - Sizzle.uniqueSort( results ); - } - - return results; -}; - -Sizzle.uniqueSort = function( results ) { - if ( sortOrder ) { - hasDuplicate = baseHasDuplicate; - results.sort( sortOrder ); - - if ( hasDuplicate ) { - for ( var i = 1; i < results.length; i++ ) { - if ( results[i] === results[ i - 1 ] ) { - results.splice( i--, 1 ); - } - } - } - } - - return results; -}; - -Sizzle.matches = function( expr, set ) { - return Sizzle( expr, null, null, set ); -}; - -Sizzle.matchesSelector = function( node, expr ) { - return Sizzle( expr, null, null, [node] ).length > 0; -}; - -Sizzle.find = function( expr, context, isXML ) { - var set, i, len, match, type, left; - - if ( !expr ) { - return []; - } - - for ( i = 0, len = Expr.order.length; i < len; i++ ) { - type = Expr.order[i]; - - if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { - left = match[1]; - match.splice( 1, 1 ); - - if ( left.substr( left.length - 1 ) !== "\\" ) { - match[1] = (match[1] || "").replace( rBackslash, "" ); - set = Expr.find[ type ]( match, context, isXML ); - - if ( set != null ) { - expr = expr.replace( Expr.match[ type ], "" ); - break; - } - } - } - } - - if ( !set ) { - set = typeof context.getElementsByTagName !== "undefined" ? - context.getElementsByTagName( "*" ) : - []; - } - - return { set: set, expr: expr }; -}; - -Sizzle.filter = function( expr, set, inplace, not ) { - var match, anyFound, - type, found, item, filter, left, - i, pass, - old = expr, - result = [], - curLoop = set, - isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); - - while ( expr && set.length ) { - for ( type in Expr.filter ) { - if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { - filter = Expr.filter[ type ]; - left = match[1]; - - anyFound = false; - - match.splice(1,1); - - if ( left.substr( left.length - 1 ) === "\\" ) { - continue; - } - - if ( curLoop === result ) { - result = []; - } - - if ( Expr.preFilter[ type ] ) { - match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); - - if ( !match ) { - anyFound = found = true; - - } else if ( match === true ) { - continue; - } - } - - if ( match ) { - for ( i = 0; (item = curLoop[i]) != null; i++ ) { - if ( item ) { - found = filter( item, match, i, curLoop ); - pass = not ^ found; - - if ( inplace && found != null ) { - if ( pass ) { - anyFound = true; - - } else { - curLoop[i] = false; - } - - } else if ( pass ) { - result.push( item ); - anyFound = true; - } - } - } - } - - if ( found !== undefined ) { - if ( !inplace ) { - curLoop = result; - } - - expr = expr.replace( Expr.match[ type ], "" ); - - if ( !anyFound ) { - return []; - } - - break; - } - } - } - - // Improper expression - if ( expr === old ) { - if ( anyFound == null ) { - Sizzle.error( expr ); - - } else { - break; - } - } - - old = expr; - } - - return curLoop; -}; - -Sizzle.error = function( msg ) { - throw new Error( "Syntax error, unrecognized expression: " + msg ); -}; - -/** - * Utility function for retreiving the text value of an array of DOM nodes - * @param {Array|Element} elem - */ -var getText = Sizzle.getText = function( elem ) { - var i, node, - nodeType = elem.nodeType, - ret = ""; - - if ( nodeType ) { - if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { - // Use textContent || innerText for elements - if ( typeof elem.textContent === 'string' ) { - return elem.textContent; - } else if ( typeof elem.innerText === 'string' ) { - // Replace IE's carriage returns - return elem.innerText.replace( rReturn, '' ); - } else { - // Traverse it's children - for ( elem = elem.firstChild; elem; elem = elem.nextSibling) { - ret += getText( elem ); - } - } - } else if ( nodeType === 3 || nodeType === 4 ) { - return elem.nodeValue; - } - } else { - - // If no nodeType, this is expected to be an array - for ( i = 0; (node = elem[i]); i++ ) { - // Do not traverse comment nodes - if ( node.nodeType !== 8 ) { - ret += getText( node ); - } - } - } - return ret; -}; - -var Expr = Sizzle.selectors = { - order: [ "ID", "NAME", "TAG" ], - - match: { - ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, - CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, - NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, - ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, - TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, - CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, - POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, - PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ - }, - - leftMatch: {}, - - attrMap: { - "class": "className", - "for": "htmlFor" - }, - - attrHandle: { - href: function( elem ) { - return elem.getAttribute( "href" ); - }, - type: function( elem ) { - return elem.getAttribute( "type" ); - } - }, - - relative: { - "+": function(checkSet, part){ - var isPartStr = typeof part === "string", - isTag = isPartStr && !rNonWord.test( part ), - isPartStrNotTag = isPartStr && !isTag; - - if ( isTag ) { - part = part.toLowerCase(); - } - - for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { - if ( (elem = checkSet[i]) ) { - while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} - - checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? - elem || false : - elem === part; - } - } - - if ( isPartStrNotTag ) { - Sizzle.filter( part, checkSet, true ); - } - }, - - ">": function( checkSet, part ) { - var elem, - isPartStr = typeof part === "string", - i = 0, - l = checkSet.length; - - if ( isPartStr && !rNonWord.test( part ) ) { - part = part.toLowerCase(); - - for ( ; i < l; i++ ) { - elem = checkSet[i]; - - if ( elem ) { - var parent = elem.parentNode; - checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; - } - } - - } else { - for ( ; i < l; i++ ) { - elem = checkSet[i]; - - if ( elem ) { - checkSet[i] = isPartStr ? - elem.parentNode : - elem.parentNode === part; - } - } - - if ( isPartStr ) { - Sizzle.filter( part, checkSet, true ); - } - } - }, - - "": function(checkSet, part, isXML){ - var nodeCheck, - doneName = done++, - checkFn = dirCheck; - - if ( typeof part === "string" && !rNonWord.test( part ) ) { - part = part.toLowerCase(); - nodeCheck = part; - checkFn = dirNodeCheck; - } - - checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); - }, - - "~": function( checkSet, part, isXML ) { - var nodeCheck, - doneName = done++, - checkFn = dirCheck; - - if ( typeof part === "string" && !rNonWord.test( part ) ) { - part = part.toLowerCase(); - nodeCheck = part; - checkFn = dirNodeCheck; - } - - checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); - } - }, - - find: { - ID: function( match, context, isXML ) { - if ( typeof context.getElementById !== "undefined" && !isXML ) { - var m = context.getElementById(match[1]); - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - return m && m.parentNode ? [m] : []; - } - }, - - NAME: function( match, context ) { - if ( typeof context.getElementsByName !== "undefined" ) { - var ret = [], - results = context.getElementsByName( match[1] ); - - for ( var i = 0, l = results.length; i < l; i++ ) { - if ( results[i].getAttribute("name") === match[1] ) { - ret.push( results[i] ); - } - } - - return ret.length === 0 ? null : ret; - } - }, - - TAG: function( match, context ) { - if ( typeof context.getElementsByTagName !== "undefined" ) { - return context.getElementsByTagName( match[1] ); - } - } - }, - preFilter: { - CLASS: function( match, curLoop, inplace, result, not, isXML ) { - match = " " + match[1].replace( rBackslash, "" ) + " "; - - if ( isXML ) { - return match; - } - - for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { - if ( elem ) { - if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { - if ( !inplace ) { - result.push( elem ); - } - - } else if ( inplace ) { - curLoop[i] = false; - } - } - } - - return false; - }, - - ID: function( match ) { - return match[1].replace( rBackslash, "" ); - }, - - TAG: function( match, curLoop ) { - return match[1].replace( rBackslash, "" ).toLowerCase(); - }, - - CHILD: function( match ) { - if ( match[1] === "nth" ) { - if ( !match[2] ) { - Sizzle.error( match[0] ); - } - - match[2] = match[2].replace(/^\+|\s*/g, ''); - - // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' - var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( - match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || - !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); - - // calculate the numbers (first)n+(last) including if they are negative - match[2] = (test[1] + (test[2] || 1)) - 0; - match[3] = test[3] - 0; - } - else if ( match[2] ) { - Sizzle.error( match[0] ); - } - - // TODO: Move to normal caching system - match[0] = done++; - - return match; - }, - - ATTR: function( match, curLoop, inplace, result, not, isXML ) { - var name = match[1] = match[1].replace( rBackslash, "" ); - - if ( !isXML && Expr.attrMap[name] ) { - match[1] = Expr.attrMap[name]; - } - - // Handle if an un-quoted value was used - match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); - - if ( match[2] === "~=" ) { - match[4] = " " + match[4] + " "; - } - - return match; - }, - - PSEUDO: function( match, curLoop, inplace, result, not ) { - if ( match[1] === "not" ) { - // If we're dealing with a complex expression, or a simple one - if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { - match[3] = Sizzle(match[3], null, null, curLoop); - - } else { - var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); - - if ( !inplace ) { - result.push.apply( result, ret ); - } - - return false; - } - - } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { - return true; - } - - return match; - }, - - POS: function( match ) { - match.unshift( true ); - - return match; - } - }, - - filters: { - enabled: function( elem ) { - return elem.disabled === false && elem.type !== "hidden"; - }, - - disabled: function( elem ) { - return elem.disabled === true; - }, - - checked: function( elem ) { - return elem.checked === true; - }, - - selected: function( elem ) { - // Accessing this property makes selected-by-default - // options in Safari work properly - if ( elem.parentNode ) { - elem.parentNode.selectedIndex; - } - - return elem.selected === true; - }, - - parent: function( elem ) { - return !!elem.firstChild; - }, - - empty: function( elem ) { - return !elem.firstChild; - }, - - has: function( elem, i, match ) { - return !!Sizzle( match[3], elem ).length; - }, - - header: function( elem ) { - return (/h\d/i).test( elem.nodeName ); - }, - - text: function( elem ) { - var attr = elem.getAttribute( "type" ), type = elem.type; - // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) - // use getAttribute instead to test this case - return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null ); - }, - - radio: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type; - }, - - checkbox: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type; - }, - - file: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "file" === elem.type; - }, - - password: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "password" === elem.type; - }, - - submit: function( elem ) { - var name = elem.nodeName.toLowerCase(); - return (name === "input" || name === "button") && "submit" === elem.type; - }, - - image: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "image" === elem.type; - }, - - reset: function( elem ) { - var name = elem.nodeName.toLowerCase(); - return (name === "input" || name === "button") && "reset" === elem.type; - }, - - button: function( elem ) { - var name = elem.nodeName.toLowerCase(); - return name === "input" && "button" === elem.type || name === "button"; - }, - - input: function( elem ) { - return (/input|select|textarea|button/i).test( elem.nodeName ); - }, - - focus: function( elem ) { - return elem === elem.ownerDocument.activeElement; - } - }, - setFilters: { - first: function( elem, i ) { - return i === 0; - }, - - last: function( elem, i, match, array ) { - return i === array.length - 1; - }, - - even: function( elem, i ) { - return i % 2 === 0; - }, - - odd: function( elem, i ) { - return i % 2 === 1; - }, - - lt: function( elem, i, match ) { - return i < match[3] - 0; - }, - - gt: function( elem, i, match ) { - return i > match[3] - 0; - }, - - nth: function( elem, i, match ) { - return match[3] - 0 === i; - }, - - eq: function( elem, i, match ) { - return match[3] - 0 === i; - } - }, - filter: { - PSEUDO: function( elem, match, i, array ) { - var name = match[1], - filter = Expr.filters[ name ]; - - if ( filter ) { - return filter( elem, i, match, array ); - - } else if ( name === "contains" ) { - return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0; - - } else if ( name === "not" ) { - var not = match[3]; - - for ( var j = 0, l = not.length; j < l; j++ ) { - if ( not[j] === elem ) { - return false; - } - } - - return true; - - } else { - Sizzle.error( name ); - } - }, - - CHILD: function( elem, match ) { - var first, last, - doneName, parent, cache, - count, diff, - type = match[1], - node = elem; - - switch ( type ) { - case "only": - case "first": - while ( (node = node.previousSibling) ) { - if ( node.nodeType === 1 ) { - return false; - } - } - - if ( type === "first" ) { - return true; - } - - node = elem; - - /* falls through */ - case "last": - while ( (node = node.nextSibling) ) { - if ( node.nodeType === 1 ) { - return false; - } - } - - return true; - - case "nth": - first = match[2]; - last = match[3]; - - if ( first === 1 && last === 0 ) { - return true; - } - - doneName = match[0]; - parent = elem.parentNode; - - if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) { - count = 0; - - for ( node = parent.firstChild; node; node = node.nextSibling ) { - if ( node.nodeType === 1 ) { - node.nodeIndex = ++count; - } - } - - parent[ expando ] = doneName; - } - - diff = elem.nodeIndex - last; - - if ( first === 0 ) { - return diff === 0; - - } else { - return ( diff % first === 0 && diff / first >= 0 ); - } - } - }, - - ID: function( elem, match ) { - return elem.nodeType === 1 && elem.getAttribute("id") === match; - }, - - TAG: function( elem, match ) { - return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match; - }, - - CLASS: function( elem, match ) { - return (" " + (elem.className || elem.getAttribute("class")) + " ") - .indexOf( match ) > -1; - }, - - ATTR: function( elem, match ) { - var name = match[1], - result = Sizzle.attr ? - Sizzle.attr( elem, name ) : - Expr.attrHandle[ name ] ? - Expr.attrHandle[ name ]( elem ) : - elem[ name ] != null ? - elem[ name ] : - elem.getAttribute( name ), - value = result + "", - type = match[2], - check = match[4]; - - return result == null ? - type === "!=" : - !type && Sizzle.attr ? - result != null : - type === "=" ? - value === check : - type === "*=" ? - value.indexOf(check) >= 0 : - type === "~=" ? - (" " + value + " ").indexOf(check) >= 0 : - !check ? - value && result !== false : - type === "!=" ? - value !== check : - type === "^=" ? - value.indexOf(check) === 0 : - type === "$=" ? - value.substr(value.length - check.length) === check : - type === "|=" ? - value === check || value.substr(0, check.length + 1) === check + "-" : - false; - }, - - POS: function( elem, match, i, array ) { - var name = match[2], - filter = Expr.setFilters[ name ]; - - if ( filter ) { - return filter( elem, i, match, array ); - } - } - } -}; - -var origPOS = Expr.match.POS, - fescape = function(all, num){ - return "\\" + (num - 0 + 1); - }; - -for ( var type in Expr.match ) { - Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); - Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); -} -// Expose origPOS -// "global" as in regardless of relation to brackets/parens -Expr.match.globalPOS = origPOS; - -var makeArray = function( array, results ) { - array = Array.prototype.slice.call( array, 0 ); - - if ( results ) { - results.push.apply( results, array ); - return results; - } - - return array; -}; - -// Perform a simple check to determine if the browser is capable of -// converting a NodeList to an array using builtin methods. -// Also verifies that the returned array holds DOM nodes -// (which is not the case in the Blackberry browser) -try { - Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; - -// Provide a fallback method if it does not work -} catch( e ) { - makeArray = function( array, results ) { - var i = 0, - ret = results || []; - - if ( toString.call(array) === "[object Array]" ) { - Array.prototype.push.apply( ret, array ); - - } else { - if ( typeof array.length === "number" ) { - for ( var l = array.length; i < l; i++ ) { - ret.push( array[i] ); - } - - } else { - for ( ; array[i]; i++ ) { - ret.push( array[i] ); - } - } - } - - return ret; - }; -} - -var sortOrder, siblingCheck; - -if ( document.documentElement.compareDocumentPosition ) { - sortOrder = function( a, b ) { - if ( a === b ) { - hasDuplicate = true; - return 0; - } - - if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { - return a.compareDocumentPosition ? -1 : 1; - } - - return a.compareDocumentPosition(b) & 4 ? -1 : 1; - }; - -} else { - sortOrder = function( a, b ) { - // The nodes are identical, we can exit early - if ( a === b ) { - hasDuplicate = true; - return 0; - - // Fallback to using sourceIndex (in IE) if it's available on both nodes - } else if ( a.sourceIndex && b.sourceIndex ) { - return a.sourceIndex - b.sourceIndex; - } - - var al, bl, - ap = [], - bp = [], - aup = a.parentNode, - bup = b.parentNode, - cur = aup; - - // If the nodes are siblings (or identical) we can do a quick check - if ( aup === bup ) { - return siblingCheck( a, b ); - - // If no parents were found then the nodes are disconnected - } else if ( !aup ) { - return -1; - - } else if ( !bup ) { - return 1; - } - - // Otherwise they're somewhere else in the tree so we need - // to build up a full list of the parentNodes for comparison - while ( cur ) { - ap.unshift( cur ); - cur = cur.parentNode; - } - - cur = bup; - - while ( cur ) { - bp.unshift( cur ); - cur = cur.parentNode; - } - - al = ap.length; - bl = bp.length; - - // Start walking down the tree looking for a discrepancy - for ( var i = 0; i < al && i < bl; i++ ) { - if ( ap[i] !== bp[i] ) { - return siblingCheck( ap[i], bp[i] ); - } - } - - // We ended someplace up the tree so do a sibling check - return i === al ? - siblingCheck( a, bp[i], -1 ) : - siblingCheck( ap[i], b, 1 ); - }; - - siblingCheck = function( a, b, ret ) { - if ( a === b ) { - return ret; - } - - var cur = a.nextSibling; - - while ( cur ) { - if ( cur === b ) { - return -1; - } - - cur = cur.nextSibling; - } - - return 1; - }; -} - -// Check to see if the browser returns elements by name when -// querying by getElementById (and provide a workaround) -(function(){ - // We're going to inject a fake input element with a specified name - var form = document.createElement("div"), - id = "script" + (new Date()).getTime(), - root = document.documentElement; - - form.innerHTML = ""; - - // Inject it into the root element, check its status, and remove it quickly - root.insertBefore( form, root.firstChild ); - - // The workaround has to do additional checks after a getElementById - // Which slows things down for other browsers (hence the branching) - if ( document.getElementById( id ) ) { - Expr.find.ID = function( match, context, isXML ) { - if ( typeof context.getElementById !== "undefined" && !isXML ) { - var m = context.getElementById(match[1]); - - return m ? - m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? - [m] : - undefined : - []; - } - }; - - Expr.filter.ID = function( elem, match ) { - var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); - - return elem.nodeType === 1 && node && node.nodeValue === match; - }; - } - - root.removeChild( form ); - - // release memory in IE - root = form = null; -})(); - -(function(){ - // Check to see if the browser returns only elements - // when doing getElementsByTagName("*") - - // Create a fake element - var div = document.createElement("div"); - div.appendChild( document.createComment("") ); - - // Make sure no comments are found - if ( div.getElementsByTagName("*").length > 0 ) { - Expr.find.TAG = function( match, context ) { - var results = context.getElementsByTagName( match[1] ); - - // Filter out possible comments - if ( match[1] === "*" ) { - var tmp = []; - - for ( var i = 0; results[i]; i++ ) { - if ( results[i].nodeType === 1 ) { - tmp.push( results[i] ); - } - } - - results = tmp; - } - - return results; - }; - } - - // Check to see if an attribute returns normalized href attributes - div.innerHTML = ""; - - if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && - div.firstChild.getAttribute("href") !== "#" ) { - - Expr.attrHandle.href = function( elem ) { - return elem.getAttribute( "href", 2 ); - }; - } - - // release memory in IE - div = null; -})(); - -if ( document.querySelectorAll ) { - (function(){ - var oldSizzle = Sizzle, - div = document.createElement("div"), - id = "__sizzle__"; - - div.innerHTML = "

"; - - // Safari can't handle uppercase or unicode characters when - // in quirks mode. - if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { - return; - } - - Sizzle = function( query, context, extra, seed ) { - context = context || document; - - // Only use querySelectorAll on non-XML documents - // (ID selectors don't work in non-HTML documents) - if ( !seed && !Sizzle.isXML(context) ) { - // See if we find a selector to speed up - var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); - - if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { - // Speed-up: Sizzle("TAG") - if ( match[1] ) { - return makeArray( context.getElementsByTagName( query ), extra ); - - // Speed-up: Sizzle(".CLASS") - } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { - return makeArray( context.getElementsByClassName( match[2] ), extra ); - } - } - - if ( context.nodeType === 9 ) { - // Speed-up: Sizzle("body") - // The body element only exists once, optimize finding it - if ( query === "body" && context.body ) { - return makeArray( [ context.body ], extra ); - - // Speed-up: Sizzle("#ID") - } else if ( match && match[3] ) { - var elem = context.getElementById( match[3] ); - - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - if ( elem && elem.parentNode ) { - // Handle the case where IE and Opera return items - // by name instead of ID - if ( elem.id === match[3] ) { - return makeArray( [ elem ], extra ); - } - - } else { - return makeArray( [], extra ); - } - } - - try { - return makeArray( context.querySelectorAll(query), extra ); - } catch(qsaError) {} - - // qSA works strangely on Element-rooted queries - // We can work around this by specifying an extra ID on the root - // and working up from there (Thanks to Andrew Dupont for the technique) - // IE 8 doesn't work on object elements - } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { - var oldContext = context, - old = context.getAttribute( "id" ), - nid = old || id, - hasParent = context.parentNode, - relativeHierarchySelector = /^\s*[+~]/.test( query ); - - if ( !old ) { - context.setAttribute( "id", nid ); - } else { - nid = nid.replace( /'/g, "\\$&" ); - } - if ( relativeHierarchySelector && hasParent ) { - context = context.parentNode; - } - - try { - if ( !relativeHierarchySelector || hasParent ) { - return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); - } - - } catch(pseudoError) { - } finally { - if ( !old ) { - oldContext.removeAttribute( "id" ); - } - } - } - } - - return oldSizzle(query, context, extra, seed); - }; - - for ( var prop in oldSizzle ) { - Sizzle[ prop ] = oldSizzle[ prop ]; - } - - // release memory in IE - div = null; - })(); -} - -(function(){ - var html = document.documentElement, - matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector; - - if ( matches ) { - // Check to see if it's possible to do matchesSelector - // on a disconnected node (IE 9 fails this) - var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ), - pseudoWorks = false; - - try { - // This should fail with an exception - // Gecko does not error, returns false instead - matches.call( document.documentElement, "[test!='']:sizzle" ); - - } catch( pseudoError ) { - pseudoWorks = true; - } - - Sizzle.matchesSelector = function( node, expr ) { - // Make sure that attribute selectors are quoted - expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); - - if ( !Sizzle.isXML( node ) ) { - try { - if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { - var ret = matches.call( node, expr ); - - // IE 9's matchesSelector returns false on disconnected nodes - if ( ret || !disconnectedMatch || - // As well, disconnected nodes are said to be in a document - // fragment in IE 9, so check for that - node.document && node.document.nodeType !== 11 ) { - return ret; - } - } - } catch(e) {} - } - - return Sizzle(expr, null, null, [node]).length > 0; - }; - } -})(); - -(function(){ - var div = document.createElement("div"); - - div.innerHTML = "
"; - - // Opera can't find a second classname (in 9.6) - // Also, make sure that getElementsByClassName actually exists - if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { - return; - } - - // Safari caches class attributes, doesn't catch changes (in 3.2) - div.lastChild.className = "e"; - - if ( div.getElementsByClassName("e").length === 1 ) { - return; - } - - Expr.order.splice(1, 0, "CLASS"); - Expr.find.CLASS = function( match, context, isXML ) { - if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { - return context.getElementsByClassName(match[1]); - } - }; - - // release memory in IE - div = null; -})(); - -function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { - for ( var i = 0, l = checkSet.length; i < l; i++ ) { - var elem = checkSet[i]; - - if ( elem ) { - var match = false; - - elem = elem[dir]; - - while ( elem ) { - if ( elem[ expando ] === doneName ) { - match = checkSet[elem.sizset]; - break; - } - - if ( elem.nodeType === 1 && !isXML ){ - elem[ expando ] = doneName; - elem.sizset = i; - } - - if ( elem.nodeName.toLowerCase() === cur ) { - match = elem; - break; - } - - elem = elem[dir]; - } - - checkSet[i] = match; - } - } -} - -function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { - for ( var i = 0, l = checkSet.length; i < l; i++ ) { - var elem = checkSet[i]; - - if ( elem ) { - var match = false; - - elem = elem[dir]; - - while ( elem ) { - if ( elem[ expando ] === doneName ) { - match = checkSet[elem.sizset]; - break; - } - - if ( elem.nodeType === 1 ) { - if ( !isXML ) { - elem[ expando ] = doneName; - elem.sizset = i; - } - - if ( typeof cur !== "string" ) { - if ( elem === cur ) { - match = true; - break; - } - - } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { - match = elem; - break; - } - } - - elem = elem[dir]; - } - - checkSet[i] = match; - } - } -} - -if ( document.documentElement.contains ) { - Sizzle.contains = function( a, b ) { - return a !== b && (a.contains ? a.contains(b) : true); - }; - -} else if ( document.documentElement.compareDocumentPosition ) { - Sizzle.contains = function( a, b ) { - return !!(a.compareDocumentPosition(b) & 16); - }; - -} else { - Sizzle.contains = function() { - return false; - }; -} - -Sizzle.isXML = function( elem ) { - // documentElement is verified for cases where it doesn't yet exist - // (such as loading iframes in IE - #4833) - var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; - - return documentElement ? documentElement.nodeName !== "HTML" : false; -}; - -var posProcess = function( selector, context, seed ) { - var match, - tmpSet = [], - later = "", - root = context.nodeType ? [context] : context; - - // Position selectors must be done after the filter - // And so must :not(positional) so we move all PSEUDOs to the end - while ( (match = Expr.match.PSEUDO.exec( selector )) ) { - later += match[0]; - selector = selector.replace( Expr.match.PSEUDO, "" ); - } - - selector = Expr.relative[selector] ? selector + "*" : selector; - - for ( var i = 0, l = root.length; i < l; i++ ) { - Sizzle( selector, root[i], tmpSet, seed ); - } - - return Sizzle.filter( later, tmpSet ); -}; - -// EXPOSE -// Override sizzle attribute retrieval -Sizzle.attr = jQuery.attr; -Sizzle.selectors.attrMap = {}; -jQuery.find = Sizzle; -jQuery.expr = Sizzle.selectors; -jQuery.expr[":"] = jQuery.expr.filters; -jQuery.unique = Sizzle.uniqueSort; -jQuery.text = Sizzle.getText; -jQuery.isXMLDoc = Sizzle.isXML; -jQuery.contains = Sizzle.contains; - - -})(); - - -var runtil = /Until$/, - rparentsprev = /^(?:parents|prevUntil|prevAll)/, - // Note: This RegExp should be improved, or likely pulled from Sizzle - rmultiselector = /,/, - isSimple = /^.[^:#\[\.,]*$/, - slice = Array.prototype.slice, - POS = jQuery.expr.match.globalPOS, - // methods guaranteed to produce a unique set when starting from a unique set - guaranteedUnique = { - children: true, - contents: true, - next: true, - prev: true - }; - -jQuery.fn.extend({ - find: function( selector ) { - var self = this, - i, l; - - if ( typeof selector !== "string" ) { - return jQuery( selector ).filter(function() { - for ( i = 0, l = self.length; i < l; i++ ) { - if ( jQuery.contains( self[ i ], this ) ) { - return true; - } - } - }); - } - - var ret = this.pushStack( "", "find", selector ), - length, n, r; - - for ( i = 0, l = this.length; i < l; i++ ) { - length = ret.length; - jQuery.find( selector, this[i], ret ); - - if ( i > 0 ) { - // Make sure that the results are unique - for ( n = length; n < ret.length; n++ ) { - for ( r = 0; r < length; r++ ) { - if ( ret[r] === ret[n] ) { - ret.splice(n--, 1); - break; - } - } - } - } - } - - return ret; - }, - - has: function( target ) { - var targets = jQuery( target ); - return this.filter(function() { - for ( var i = 0, l = targets.length; i < l; i++ ) { - if ( jQuery.contains( this, targets[i] ) ) { - return true; - } - } - }); - }, - - not: function( selector ) { - return this.pushStack( winnow(this, selector, false), "not", selector); - }, - - filter: function( selector ) { - return this.pushStack( winnow(this, selector, true), "filter", selector ); - }, - - is: function( selector ) { - return !!selector && ( - typeof selector === "string" ? - // If this is a positional selector, check membership in the returned set - // so $("p:first").is("p:last") won't return true for a doc with two "p". - POS.test( selector ) ? - jQuery( selector, this.context ).index( this[0] ) >= 0 : - jQuery.filter( selector, this ).length > 0 : - this.filter( selector ).length > 0 ); - }, - - closest: function( selectors, context ) { - var ret = [], i, l, cur = this[0]; - - // Array (deprecated as of jQuery 1.7) - if ( jQuery.isArray( selectors ) ) { - var level = 1; - - while ( cur && cur.ownerDocument && cur !== context ) { - for ( i = 0; i < selectors.length; i++ ) { - - if ( jQuery( cur ).is( selectors[ i ] ) ) { - ret.push({ selector: selectors[ i ], elem: cur, level: level }); - } - } - - cur = cur.parentNode; - level++; - } - - return ret; - } - - // String - var pos = POS.test( selectors ) || typeof selectors !== "string" ? - jQuery( selectors, context || this.context ) : - 0; - - for ( i = 0, l = this.length; i < l; i++ ) { - cur = this[i]; - - while ( cur ) { - if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { - ret.push( cur ); - break; - - } else { - cur = cur.parentNode; - if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) { - break; - } - } - } - } - - ret = ret.length > 1 ? jQuery.unique( ret ) : ret; - - return this.pushStack( ret, "closest", selectors ); - }, - - // Determine the position of an element within - // the matched set of elements - index: function( elem ) { - - // No argument, return index in parent - if ( !elem ) { - return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1; - } - - // index in selector - if ( typeof elem === "string" ) { - return jQuery.inArray( this[0], jQuery( elem ) ); - } - - // Locate the position of the desired element - return jQuery.inArray( - // If it receives a jQuery object, the first element is used - elem.jquery ? elem[0] : elem, this ); - }, - - add: function( selector, context ) { - var set = typeof selector === "string" ? - jQuery( selector, context ) : - jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), - all = jQuery.merge( this.get(), set ); - - return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? - all : - jQuery.unique( all ) ); - }, - - andSelf: function() { - return this.add( this.prevObject ); - } -}); - -// A painfully simple check to see if an element is disconnected -// from a document (should be improved, where feasible). -function isDisconnected( node ) { - return !node || !node.parentNode || node.parentNode.nodeType === 11; -} - -jQuery.each({ - parent: function( elem ) { - var parent = elem.parentNode; - return parent && parent.nodeType !== 11 ? parent : null; - }, - parents: function( elem ) { - return jQuery.dir( elem, "parentNode" ); - }, - parentsUntil: function( elem, i, until ) { - return jQuery.dir( elem, "parentNode", until ); - }, - next: function( elem ) { - return jQuery.nth( elem, 2, "nextSibling" ); - }, - prev: function( elem ) { - return jQuery.nth( elem, 2, "previousSibling" ); - }, - nextAll: function( elem ) { - return jQuery.dir( elem, "nextSibling" ); - }, - prevAll: function( elem ) { - return jQuery.dir( elem, "previousSibling" ); - }, - nextUntil: function( elem, i, until ) { - return jQuery.dir( elem, "nextSibling", until ); - }, - prevUntil: function( elem, i, until ) { - return jQuery.dir( elem, "previousSibling", until ); - }, - siblings: function( elem ) { - return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); - }, - children: function( elem ) { - return jQuery.sibling( elem.firstChild ); - }, - contents: function( elem ) { - return jQuery.nodeName( elem, "iframe" ) ? - elem.contentDocument || elem.contentWindow.document : - jQuery.makeArray( elem.childNodes ); - } -}, function( name, fn ) { - jQuery.fn[ name ] = function( until, selector ) { - var ret = jQuery.map( this, fn, until ); - - if ( !runtil.test( name ) ) { - selector = until; - } - - if ( selector && typeof selector === "string" ) { - ret = jQuery.filter( selector, ret ); - } - - ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; - - if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { - ret = ret.reverse(); - } - - return this.pushStack( ret, name, slice.call( arguments ).join(",") ); - }; -}); - -jQuery.extend({ - filter: function( expr, elems, not ) { - if ( not ) { - expr = ":not(" + expr + ")"; - } - - return elems.length === 1 ? - jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : - jQuery.find.matches(expr, elems); - }, - - dir: function( elem, dir, until ) { - var matched = [], - cur = elem[ dir ]; - - while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { - if ( cur.nodeType === 1 ) { - matched.push( cur ); - } - cur = cur[dir]; - } - return matched; - }, - - nth: function( cur, result, dir, elem ) { - result = result || 1; - var num = 0; - - for ( ; cur; cur = cur[dir] ) { - if ( cur.nodeType === 1 && ++num === result ) { - break; - } - } - - return cur; - }, - - sibling: function( n, elem ) { - var r = []; - - for ( ; n; n = n.nextSibling ) { - if ( n.nodeType === 1 && n !== elem ) { - r.push( n ); - } - } - - return r; - } -}); - -// Implement the identical functionality for filter and not -function winnow( elements, qualifier, keep ) { - - // Can't pass null or undefined to indexOf in Firefox 4 - // Set to 0 to skip string check - qualifier = qualifier || 0; - - if ( jQuery.isFunction( qualifier ) ) { - return jQuery.grep(elements, function( elem, i ) { - var retVal = !!qualifier.call( elem, i, elem ); - return retVal === keep; - }); - - } else if ( qualifier.nodeType ) { - return jQuery.grep(elements, function( elem, i ) { - return ( elem === qualifier ) === keep; - }); - - } else if ( typeof qualifier === "string" ) { - var filtered = jQuery.grep(elements, function( elem ) { - return elem.nodeType === 1; - }); - - if ( isSimple.test( qualifier ) ) { - return jQuery.filter(qualifier, filtered, !keep); - } else { - qualifier = jQuery.filter( qualifier, filtered ); - } - } - - return jQuery.grep(elements, function( elem, i ) { - return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; - }); -} - - - - -function createSafeFragment( document ) { - var list = nodeNames.split( "|" ), - safeFrag = document.createDocumentFragment(); - - if ( safeFrag.createElement ) { - while ( list.length ) { - safeFrag.createElement( - list.pop() - ); - } - } - return safeFrag; -} - -var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + - "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", - rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, - rleadingWhitespace = /^\s+/, - rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, - rtagName = /<([\w:]+)/, - rtbody = /]", "i"), - // checked="checked" or checked - rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, - rscriptType = /\/(java|ecma)script/i, - rcleanScript = /^\s*", "" ], - legend: [ 1, "
", "
" ], - thead: [ 1, "", "
" ], - tr: [ 2, "", "
" ], - td: [ 3, "", "
" ], - col: [ 2, "", "
" ], - area: [ 1, "", "" ], - _default: [ 0, "", "" ] - }, - safeFragment = createSafeFragment( document ); - -wrapMap.optgroup = wrapMap.option; -wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; -wrapMap.th = wrapMap.td; - -// IE can't serialize and