-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobservations_controller.rb
3124 lines (2870 loc) · 116 KB
/
observations_controller.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#encoding: utf-8
class ObservationsController < ApplicationController
caches_page :tile_points
OBS_LIMIT = 20000
WIDGET_CACHE_EXPIRATION = 15.minutes
caches_action :index, :by_login, :project,
:expires_in => WIDGET_CACHE_EXPIRATION,
:cache_path => Proc.new {|c| c.params.merge(:locale => I18n.locale)},
:if => Proc.new {|c|
c.session.blank? && # make sure they're logged out
c.request.format && # make sure format corresponds to a known mime type
(c.request.format.geojson? || c.request.format.widget? || c.request.format.kml?) &&
c.request.url.size < 250}
caches_action :of,
:expires_in => 1.day,
:cache_path => Proc.new {|c| c.params.merge(:locale => I18n.locale)},
:if => Proc.new {|c| c.request.format != :html }
cache_sweeper :observation_sweeper, :only => [:create, :update, :destroy]
rescue_from ::AbstractController::ActionNotFound do
unless @selected_user = User.find_by_login(params[:action])
return render_404
end
by_login
end
doorkeeper_for :create, :update, :destroy, :viewed_updates, :update_fields, :if => lambda { authenticate_with_oauth? }
before_filter :load_user_by_login, :only => [:by_login, :by_login_all]
before_filter :return_here, :only => [:index, :by_login, :show, :id_please,
:import, :export, :add_from_list, :new, :project]
before_filter :authenticate_user!,
:unless => lambda { authenticated_with_oauth? },
:except => [:explore,
:index,
:of,
:show,
:by_login,
:id_please,
:tile_points,
:nearby,
:widget,
:project,
:stats,
:taxa,
:taxon_stats,
:user_stats,
:community_taxon_summary,
:map, :add_identification, :identify]
load_only = [ :show, :edit, :edit_photos, :update_photos, :destroy,
:fields, :viewed_updates, :community_taxon_summary, :update_fields]
before_filter :load_observation, :only => load_only
blocks_spam :only => load_only, :instance => :observation
before_filter :require_owner, :only => [:edit, :edit_photos,
:update_photos, :destroy]
before_filter :curator_required, :only => [:curation, :accumulation, :phylogram]
before_filter :load_photo_identities, :only => [:new, :new_batch, :show,
:new_batch_csv,:edit, :update, :edit_batch, :create, :import,
:import_photos, :import_sounds, :new_from_list]
before_filter :load_sound_identities, :only => [:new, :new_batch, :show,
:new_batch_csv,:edit, :update, :edit_batch, :create, :import,
:import_photos, :import_sounds, :new_from_list]
before_filter :photo_identities_required, :only => [:import_photos]
after_filter :refresh_lists_for_batch, :only => [:create, :update]
MOBILIZED = [:add_from_list, :nearby, :add_nearby, :project, :by_login, :index, :show]
before_filter :unmobilized, :except => MOBILIZED
before_filter :mobilized, :only => MOBILIZED
before_filter :load_prefs, :only => [:index, :project, :by_login]
ORDER_BY_FIELDS = %w"created_at observed_on project species_guess"
REJECTED_FEED_PARAMS = %w"page view filters_open partial action id locale"
REJECTED_KML_FEED_PARAMS = REJECTED_FEED_PARAMS + %w"swlat swlng nelat nelng BBOX"
MAP_GRID_PARAMS_TO_CONSIDER = REJECTED_KML_FEED_PARAMS +
%w"order order_by taxon_id taxon_name project_id user_id utf8"
DISPLAY_ORDER_BY_FIELDS = {
'created_at' => 'date added',
'observations.id' => 'date added',
'id' => 'date added',
'observed_on' => 'date observed',
'species_guess' => 'species name',
'project' => "date added to project"
}
PARTIALS = %w(cached_component observation_component observation mini project_observation)
EDIT_PARTIALS = %w(add_photos)
PHOTO_SYNC_ATTRS = [:description, :species_guess, :taxon_id, :observed_on,
:observed_on_string, :latitude, :longitude, :place_guess]
# GET /observations
# GET /observations.xml
def index
search_params, find_options = get_search_params(params)
search_params = site_search_params(search_params)
obsLimit = @prefs["observations_limits"].to_i
if logged_in? && current_user.has_role?(:admin)
Rails.logger.info 'Admin power'
elsif logged_in? && current_user.has_role?(:exporter)
if find_options[:page] && find_options[:per_page]
nitems = obsLimit
if find_options[:page].to_i * find_options[:per_page].to_i > nitems
if request.format == :json
render json: {message: "You reach #{nitems} items limit"}, status: 403
return false
end
end
end
elsif find_options[:page] && find_options[:per_page]
if find_options[:page].to_i * find_options[:per_page].to_i > 20000
if !logged_in? && request.format == :html
authenticate_user!
return false
elsif request.format == :json
render json: {message: 'You reach 20,000 items limit'}, status: 403
return false
end
end
end
if search_params[:q].blank?
@observations = if perform_caching && (!logged_in? || find_options[:page] == 1)
cache_params = params.reject{|k,v| %w(controller action format partial).include?(k.to_s)}
cache_params[:page] ||= 1
cache_params[:per_page] ||= find_options[:per_page]
cache_params[:site_name] ||= SITE_NAME if CONFIG.site_only_observations
cache_params[:bounds] ||= CONFIG.bounds if CONFIG.bounds
cache_key = "obs_index_#{Digest::MD5.hexdigest(cache_params.to_s)}"
Rails.cache.fetch(cache_key, :expires_in => 5.minutes) do
get_paginated_observations(search_params, find_options).to_a
end
else
get_paginated_observations(search_params, find_options)
end
else
@observations = search_observations(search_params, find_options)
end
respond_to do |format|
Rails.logger.info '-'* 100
Rails.logger.info 'RESPOND_TO'
format.html do
@iconic_taxa ||= []
grid_affecting_params = request.query_parameters.reject{ |k,v|
MAP_GRID_PARAMS_TO_CONSIDER.include?(k.to_s) }
# there are no parameters at all, so we can show the grid for all taxa
@map_grid_params = { }
if grid_affecting_params.blank?
@display_map_grid = true
# we can only show grids when quality_grade = 'any',
# and all other parameters are empty
elsif grid_affecting_params.delete("quality_grade") == "any" &&
grid_affecting_params.detect{ |k,v| v != "" }.nil?
@display_map_grid = true
end
# if we are showing a grid
if @display_map_grid
@map_grid_params.merge!({
taxon_id: (search_params[:taxon] ? search_params[:taxon].id : nil),
user_id: search_params[:user_id],
project_id: search_params[:project_id],
place_id: search_params[:place_id]
}.delete_if{ |k,v| v.nil? })
if search_params[:taxon] && search_params[:taxon].iconic_taxon
@map_grid_params[:iconic_taxon] = search_params[:taxon].iconic_taxon.name
end
end
if (partial = params[:partial]) && PARTIALS.include?(partial)
pagination_headers_for(@observations)
return render_observations_partial(partial)
end
end
format.json do
render_observations_to_json
end
format.mobile
format.geojson do
render :json => @observations.to_geojson(:except => [
:geom, :latitude, :longitude, :map_scale,
:num_identification_agreements, :num_identification_disagreements,
:delta, :location_is_exact])
end
format.atom do
@updated_at = Observation.first(:order => 'updated_at DESC').updated_at
end
format.dwc
format.csv do
render_observations_to_csv
end
format.kml do
render_observations_to_kml(
:snippet => "#{CONFIG.site_name} Feed for Everyone",
:description => "#{CONFIG.site_name} Feed for Everyone",
:name => "#{CONFIG.site_name} Feed for Everyone"
)
end
format.widget do
if params[:markup_only] == 'true'
render :js => render_to_string(:partial => "widget.html.erb", :locals => {
:show_user => true, :target => params[:target], :default_image => params[:default_image], :silence => params[:silence]
})
else
render :js => render_to_string(:partial => "widget.js.erb", :locals => {
:show_user => true
})
end
end
end
end
def getUser(token)
# token = "f8cf54de29268054c858accee17e13194e1b8bfa"
urlInfo = "https://www.authenix.eu/oauth/tokeninfo"
clientId = "df4b4fd7-f57c-5c1c-10ce-84dfdbb495a3"
clientSecret = "0bd623bdcc5467595c70466c2d755b5821bd14d6b7aa9d8ea6fb0bff716ed0e7"
data = "token=#{token}&token_type_hint=access_token"
res = `curl -X POST #{urlInfo} -u #{clientId}:#{clientSecret} -H "accept: application/json" -H "Content-Type: application/x-www-form-urlencoded" -d "#{data}"`
aux = JSON.parse(res)
if (aux['active'])
return aux['username']
else
return nil
end
end
def add_identification
#observation_id: 279488,
#taxon_id: 942,
#user_id: 4032,
#type: nil,
#body: nil,
if params[:taxon]
i1 = Identification.new
i1.observation_id = params[:observation_id]
i1.taxon_id = (Taxon.search params[:taxon].split(/[ _-]/)[0..1]).first.id #params[:taxon_id]
i1.user_id = 1
i1.origin = getUser(params[:token]) #params[:type]
i1.body = params[:body] or "by Cos4Cloud"
i1.save
render :json => {i1: i1, errors: i1.errors.messages.to_s}
else
i1 = Comment.new
i1.parent_id = params[:observation_id]
i1.parent_type = 'Observation'
i1.user_id = 1
i1.origin = getUser(params[:token]) #params[:type]
i1.body = params[:body] or "by Cos4Cloud"
i1.save
render :json => {i1: i1, errors: i1.errors.messages.to_s}
end
end
def identify
@observation = Observation.find(params[:id], :include => [ :quality_metrics,
:photos,
:identifications,
{ :taxon => :taxon_names }
])
photo = @observation.observation_photos.first.photo.medium_url.sub 'http://', 'https://'
urlStr = 'https://my-api.plantnet.org/v2/identify/all?';
params = "images=#{URI.escape(photo)}&organs=flower&lang=en&api-key=2a10HwuT6PvsSXZFYhBwzlsXO"
url = URI(urlStr)
url.query = params
net = Net::HTTP.new(url.host, 443)
net.use_ssl = true
res = net.get(url.to_s)
json = JSON.parse res.body
taxon = json["results"][0]["species"]["scientificNameWithoutAuthor"]
score = json["results"][0]["score"] * 100
taxa = (Taxon.search taxon.split(/[ _-]/)[0..1])
if taxa.empty?
taxa = (Taxon.search taxon.split(/[ _-]/)[0])
end
if (not taxa.empty?)
i1 = Identification.new
i1.observation_id = @observation.id
i1.taxon_id = taxa.first.id
i1.user_id = 2
score = score.round(1)
i1.body = "#{taxon} #{score}\% by PlantNet"
i1.save
return render :json => {ok: true, i1: i1, errors: i1.errors.messages.to_s}
end
render :json => {ok: false}
end
def of
if request.format == :html
redirect_to observations_path(:taxon_id => params[:id])
return
end
unless @taxon = Taxon.find_by_id(params[:id].to_i)
render_404 && return
end
@observations = Observation.of(@taxon).all(
:include => [ :user,
:iconic_taxon,
{ :taxon => :taxon_descriptions },
{ :observation_photos => :photo } ],
:order => "observations.id desc",
:limit => 500).sort_by{|o| [o.quality_grade == "research" ? 1 : 0, o.id]}
respond_to do |format|
format.json do
render :json => @observations.to_json(
:methods => [ :user_login, :iconic_taxon_name, :obs_image_url],
:include => [ { :user => { :only => :login } },
:taxon, :iconic_taxon ] )
end
format.geojson do
render :json => @observations.to_geojson(:except => [
:geom, :latitude, :longitude, :map_scale,
:num_identification_agreements, :num_identification_disagreements,
:delta, :location_is_exact])
end
end
end
# GET /observations/1
# GET /observations/1.xml
def show
if request.format == :html &&
params[:partial] == "cached_component" &&
fragment_exist?(@observation.component_cache_key(:for_owner => @observation.user_id == current_user.try(:id)))
return render(:partial => params[:partial], :object => @observation,
:layout => false)
end
@previous = @observation.user.observations.first(:conditions => ["id < ?", @observation.id], :order => "id DESC")
@prev = @previous
@next = @observation.user.observations.first(:conditions => ["id > ?", @observation.id], :order => "id ASC")
@quality_metrics = @observation.quality_metrics.all(:include => :user)
if logged_in?
@user_quality_metrics = @observation.quality_metrics.select{|qm| qm.user_id == current_user.id}
@project_invitations = @observation.project_invitations.limit(100).to_a
@project_invitations_by_project_id = @project_invitations.index_by(&:project_id)
end
@coordinates_viewable = @observation.coordinates_viewable_by?(current_user)
respond_to do |format|
format.html do
# always display the time in the zone in which is was observed
Time.zone = @observation.user.time_zone
@identifications = @observation.identifications.includes(:user, :taxon => :photos)
@current_identifications = @identifications.select{|o| o.current?}
@owners_identification = @current_identifications.detect do |ident|
ident.user_id == @observation.user_id
end
@community_identification = if @observation.community_taxon
Identification.new(:taxon => @observation.community_taxon, :observation => @observation)
end
if logged_in?
@viewers_identification = @current_identifications.detect do |ident|
ident.user_id == current_user.id
end
end
@current_identifications_by_taxon = @current_identifications.select do |ident|
ident.user_id != ident.observation.user_id
end.group_by{|i| i.taxon}
@sorted_current_identifications_by_taxon = @current_identifications_by_taxon.sort_by do |row|
row.last.size
end.reverse
if logged_in?
@projects = Project.all(
:joins => [:project_users],
:limit => 1000,
:conditions => ["project_users.user_id = ?", current_user]
).sort_by{|p| p.title.downcase}
end
@places = @observation.places
@project_observations = @observation.project_observations.limit(100).to_a
@project_observations_by_project_id = @project_observations.index_by(&:project_id)
@comments_and_identifications = (@observation.comments.all +
@identifications).sort_by{|r| r.created_at}
@photos = @observation.observation_photos.includes(:photo => [:flags]).sort_by do |op|
op.position || @observation.observation_photos.size + op.id.to_i
end.map{|op| op.photo}.compact
@flagged_photos = @photos.select{|p| p.flagged?}
@sounds = @observation.sounds.all
if @observation.observed_on
@day_observations = Observation.by(@observation.user).on(@observation.observed_on)
.includes([ :photos, :user ])
.paginate(:page => 1, :per_page => 14)
end
if logged_in?
@subscription = @observation.update_subscriptions.first(:conditions => {:user_id => current_user})
end
@observation_links = @observation.observation_links.sort_by{|ol| ol.href}
@posts = @observation.posts.published.limit(50)
if @observation.taxon
unless @places.blank?
@listed_taxon = ListedTaxon.
includes(:place).
where("taxon_id = ? AND place_id IN (?) AND establishment_means IS NOT NULL", @observation.taxon_id, @places).
order("establishment_means IN ('endemic', 'introduced') DESC, places.bbox_area ASC").first
@conservation_status = ConservationStatus.
where(:taxon_id => @observation.taxon).where("place_id IN (?)", @places).
where("iucn >= ?", Taxon::IUCN_NEAR_THREATENED).
includes(:place).first
end
@conservation_status ||= ConservationStatus.where(:taxon_id => @observation.taxon).where("place_id IS NULL").
where("iucn >= ?", Taxon::IUCN_NEAR_THREATENED).first
end
@observer_provider_authorizations = @observation.user.provider_authorizations
@shareable_image_url = if !@photos.blank? && photo = @photos.detect{|p| p.medium_url =~ /^http/}
FakeView.image_url(photo.best_url(:original))
else
FakeView.iconic_taxon_image_url(@observation.taxon, :size => 200)
end
@shareable_description = @observation.to_plain_s(:no_place_guess => !@coordinates_viewable)
@shareable_description += ".\n\n#{@observation.description}" unless @observation.description.blank?
if logged_in?
user_viewed_updates
end
if params[:partial]
return render(:partial => params[:partial], :object => @observation,
:layout => false)
end
end
format.mobile
format.xml { render :xml => @observation }
format.json do
taxon_options = Taxon.default_json_options
taxon_options[:methods] += [:iconic_taxon_name, :image_url, :common_name, :default_name]
render :json => @observation.to_json(
:viewer => current_user,
:methods => [:user_login, :iconic_taxon_name],
:include => {
:observation_field_values => {:include => {:observation_field => {:only => [:name]}}},
:project_observations => {
:include => {
:project => {
:only => [:id, :title],
:methods => [:icon_url]
}
}
},
:observation_photos => {
:include => {
:photo => {
:methods => [:license_code, :attribution],
:except => [:original_url, :file_processing, :file_file_size,
:file_content_type, :file_file_name, :mobile, :metadata, :user_id,
:native_realname, :native_photo_id]
}
}
},
:comments => {
:include => {
:user => {
:only => [:name, :login, :id],
:methods => [:user_icon_url]
}
}
},
:taxon => taxon_options,
:identifications => {
:include => {
:user => {
:only => [:name, :login, :id],
:methods => [:user_icon_url]
},
:taxon => taxon_options
}
}
})
end
format.atom do
cache
end
end
end
# GET /observations/new
# GET /observations/new.xml
# An attempt at creating a simple new page for batch add
def new
@observation = Observation.new(:user => current_user)
@observation.id_please = params[:id_please]
@observation.time_zone = current_user.time_zone
if params[:copy] && (copy_obs = Observation.find_by_id(params[:copy])) && copy_obs.user_id == current_user.id
%w(observed_on_string time_zone place_guess geoprivacy map_scale positional_accuracy).each do |a|
@observation.send("#{a}=", copy_obs.send(a))
end
@observation.latitude = copy_obs.private_latitude || copy_obs.latitude
@observation.longitude = copy_obs.private_longitude || copy_obs.longitude
copy_obs.observation_photos.each do |op|
@observation.observation_photos.build(:photo => op.photo)
end
copy_obs.observation_field_values.each do |ofv|
@observation.observation_field_values.build(:observation_field => ofv.observation_field, :value => ofv.value)
end
end
@taxon = Taxon.find_by_id(params[:taxon_id].to_i) unless params[:taxon_id].blank?
unless params[:taxon_name].blank?
@taxon ||= TaxonName.first(:conditions => [
"lower(name) = ?", params[:taxon_name].to_s.strip.gsub(/[\s_]+/, ' ').downcase]
).try(:taxon)
end
if !params[:project_id].blank?
@project = if params[:project_id].to_i == 0
Project.includes(:project_observation_fields => :observation_field).find(params[:project_id])
else
Project.includes(:project_observation_fields => :observation_field).find_by_id(params[:project_id].to_i)
end
if @project
@place = @project.place
@project_curators = @project.project_users.where("role IN (?)", [ProjectUser::MANAGER, ProjectUser::CURATOR])
@tracking_code = params[:tracking_code] if @project.tracking_code_allowed?(params[:tracking_code])
@kml_assets = @project.project_assets.select{|pa| pa.asset_file_name =~ /\.km[lz]$/}
end
end
@place ||= Place.find(params[:place_id]) unless params[:place_id].blank? rescue nil
if @place
@place_geometry = PlaceGeometry.without_geom.first(:conditions => {:place_id => @place})
end
if params[:facebook_photo_id]
begin
sync_facebook_photo
rescue Koala::Facebook::APIError => e
raise e unless e.message =~ /OAuthException/
redirect_to ProviderAuthorization::AUTH_URLS['facebook']
return
end
end
sync_flickr_photo if params[:flickr_photo_id] && current_user.flickr_identity
sync_picasa_photo if params[:picasa_photo_id] && current_user.picasa_identity
sync_local_photo if params[:local_photo_id]
@welcome = params[:welcome]
# this should happen AFTER photo syncing so params can override attrs
# from the photo
[:latitude, :longitude, :place_guess, :location_is_exact, :map_scale,
:positional_accuracy, :positioning_device, :positioning_method,
:observed_on_string].each do |obs_attr|
next if params[obs_attr].blank?
# sync_photo indicates that the user clicked sync photo, so presumably they'd
# like the photo attrs to override the URL
# invite links are the other case, in which URL params *should* override the
# photo attrs b/c the person who made the invite link chose a taxon or something
if params[:sync_photo]
@observation.send("#{obs_attr}=", params[obs_attr]) if @observation.send(obs_attr).blank?
else
@observation.send("#{obs_attr}=", params[obs_attr])
end
end
if @taxon
@observation.taxon = @taxon
@observation.species_guess = if @taxon.common_name
@taxon.common_name.name
else
@taxon.name
end
elsif !params[:taxon_name].blank?
@observation.species_guess = params[:taxon_name]
end
@observation_fields = ObservationField.recently_used_by(current_user).limit(10)
respond_to do |format|
format.html do
@observations = [@observation]
@sharing_authorizations = current_user.provider_authorizations.select do |pa|
pa.provider_name == "facebook" || (pa.provider_name == "twitter" && !pa.secret.blank?)
end
end
format.json { render :json => @observation }
end
end
# def quickadd
# if params[:txt]
# pieces = txt.split(/\sat\s|\son\s|\sin\s/)
# @observation = Observation.new(:species_guess => pieces.first)
# @observation.place_guess = pieces.last if pieces.size > 1
# if pieces.size > 2
# @observation.observed_on_string = pieces[1..-2].join(' ')
# end
# @observation.user = self.current_user
# end
# respond_to do |format|
# if @observation.save
# flash[:notice] = "Your observation was saved."
# format.html { redirect_to :action => @user.login }
# format.xml { render :xml => @observation, :status => :created,
# :location => @observation }
# format.js { render }
# else
# format.html { render :action => "new" }
# format.xml { render :xml => @observation.errors,
# :status => :unprocessable_entity }
# format.js { render :json => @observation.errors,
# :status => :unprocessable_entity }
# end
# end
# end
# GET /observations/1/edit
def edit
# Only the owner should be able to see this.
unless current_user.id == @observation.user_id or current_user.is_admin?
redirect_to observation_path(@observation)
return
end
# Make sure user is editing the REAL coordinates
if @observation.coordinates_obscured?
@observation.latitude = @observation.private_latitude
@observation.longitude = @observation.private_longitude
end
if params[:facebook_photo_id]
begin
sync_facebook_photo
rescue Koala::Facebook::APIError => e
raise e unless e.message =~ /OAuthException/
redirect_to ProviderAuthorization::AUTH_URLS['facebook']
return
end
end
sync_flickr_photo if params[:flickr_photo_id]
sync_picasa_photo if params[:picasa_photo_id]
sync_local_photo if params[:local_photo_id]
@observation_fields = ObservationField.recently_used_by(current_user).limit(10)
if @observation.quality_metrics.detect{|qm| qm.user_id == @observation.user_id && qm.metric == QualityMetric::WILD && !qm.agree?}
@observation.captive_flag = true
end
respond_to do |format|
format.html do
if params[:partial] && EDIT_PARTIALS.include?(params[:partial])
return render(:partial => params[:partial], :object => @observation,
:layout => false)
end
end
end
end
# POST /observations
# POST /observations.xml
def create
# Handle the case of a single obs
params[:observations] = [['0', params[:observation]]] if params[:observation]
if params[:observations].blank? && params[:observation].blank?
respond_to do |format|
format.html do
flash[:error] = t(:no_observations_submitted)
redirect_to new_observation_path
end
format.json { render :status => :unprocessable_entity, :json => "No observations submitted!" }
end
return
end
@observations = params[:observations].map do |fieldset_index, observation|
next if observation.blank?
observation.delete('fieldset_index') if observation[:fieldset_index]
o = unless observation[:uuid].blank?
current_user.observations.where(:uuid => observation[:uuid]).first
end
o ||= Observation.new
o.assign_attributes(observation)
o.user = current_user
o.user_agent = request.user_agent
o.site = @site || current_user.site
if doorkeeper_token && (a = doorkeeper_token.application)
o.oauth_application = a.becomes(OauthApplication)
end
# Get photos
puts '@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@'
Rails.logger.error "[PHOTOS #{o.inspect}]"
puts '@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@'
Photo.descendent_classes.each do |klass|
klass_key = klass.to_s.underscore.pluralize.to_sym
if params[klass_key] && params[klass_key][fieldset_index]
o.photos << retrieve_photos(params[klass_key][fieldset_index],
:user => current_user, :photo_class => klass)
end
if params["#{klass_key}_to_sync"] && params["#{klass_key}_to_sync"][fieldset_index]
if photo = o.photos.compact.last
photo_o = photo.to_observation
PHOTO_SYNC_ATTRS.each do |a|
o.send("#{a}=", photo_o.send(a)) if o.send(a).blank?
end
end
end
end
o.sounds << Sound.from_observation_params(params, fieldset_index, current_user)
o
end
current_user.observations << @observations.compact
if request.format != :json && !params[:accept_terms] && params[:project_id] && !current_user.project_users.find_by_project_id(params[:project_id])
flash[:error] = t(:but_we_didnt_add_this_observation_to_the_x_project, :project => Project.find_by_id(params[:project_id]).title)
else
create_project_observations
end
update_user_account
# check for errors
errors = false
@observations.compact.each { |obs| errors = true unless obs.valid? }
respond_to do |format|
format.html do
unless errors
flash[:notice] = params[:success_msg] || t(:observations_saved)
if params[:commit] == t(:save_and_add_another)
o = @observations.first
redirect_to :action => 'new',
:latitude => o.coordinates_obscured? ? o.private_latitude : o.latitude,
:longitude => o.coordinates_obscured? ? o.private_longitude : o.longitude,
:place_guess => o.place_guess,
:observed_on_string => o.observed_on_string,
:location_is_exact => o.location_is_exact,
:map_scale => o.map_scale,
:positional_accuracy => o.positional_accuracy,
:positioning_method => o.positioning_method,
:positioning_device => o.positioning_device,
:project_id => params[:project_id]
elsif @observations.size == 1
redirect_to observation_path(@observations.first)
else
redirect_to :action => self.current_user.login
end
else
if @observations.size == 1
render :action => 'new'
else
render :action => 'edit_batch'
end
end
end
format.json do
if errors
json = if @observations.size == 1 && is_iphone_app_2?
{:error => @observations.map{|o| o.errors.full_messages}.flatten.uniq.compact.to_sentence}
else
{:errors => @observations.map{|o| o.errors.full_messages}}
end
render :json => json, :status => :unprocessable_entity
else
if @observations.size == 1 && is_iphone_app_2?
render :json => @observations[0].to_json(
:viewer => current_user,
:methods => [:user_login, :iconic_taxon_name],
:include => {
:taxon => Taxon.default_json_options,
:observation_field_values => {}
}
)
else
render :json => @observations.to_json(:viewer => current_user, :methods => [:user_login, :iconic_taxon_name])
end
end
end
end
end
# PUT /observations/1
# PUT /observations/1.xml
def update
observation_user = current_user
unless params[:admin_action].nil? || !current_user.is_admin?
observation_user = Observation.find(params[:id]).user
end
# Handle the case of a single obs
if params[:observation]
params[:observations] = [[params[:id], params[:observation]]]
elsif params[:id] && params[:observations]
params[:observations] = [[params[:id], params[:observations][0]]]
end
if params[:observations].blank? && params[:observation].blank?
respond_to do |format|
format.html do
flash[:error] = t(:no_observations_submitted)
redirect_to new_observation_path
end
format.json { render :status => :unprocessable_entity, :json => "No observations submitted!" }
end
return
end
@observations = Observation.all(
:conditions => [
"id IN (?) AND user_id = ?",
params[:observations].map{|k,v| k},
observation_user
]
)
# Make sure there's no evil going on
unique_user_ids = @observations.map(&:user_id).uniq
more_than_one_observer = unique_user_ids.size > 1
admin_action = unique_user_ids.first != observation_user.id && current_user.has_role?(:admin)
if !@observations.blank? && more_than_one_observer && !admin_action
msg = t(:you_dont_have_permission_to_edit_that_observation)
respond_to do |format|
format.html do
flash[:error] = msg
redirect_to(@observation || observations_path)
end
format.json do
render :status => :unprocessable_entity, :json => {:error => msg}
end
end
return
end
# Convert the params to a hash keyed by ID. Yes, it's weird
hashed_params = Hash[*params[:observations].to_a.flatten]
errors = false
extra_msg = nil
@observations.each_with_index do |observation,i|
fieldset_index = observation.id.to_s
# Update the flickr photos
# Note: this ignore photos thing is a total hack and should only be
# included if you are updating observations but aren't including flickr
# fields, e.g. when removing something from ID please
if !params[:ignore_photos] && !is_mobile_app?
# Get photos
updated_photos = []
old_photo_ids = observation.photo_ids
Photo.descendent_classes.each do |klass|
klass_key = klass.to_s.underscore.pluralize.to_sym
if params[klass_key] && params[klass_key][fieldset_index]
updated_photos += retrieve_photos(params[klass_key][fieldset_index],
:user => current_user, :photo_class => klass, :sync => true)
end
end
if updated_photos.empty?
observation.photos.clear
else
observation.photos = updated_photos
end
# Destroy old photos. ObservationPhotos seem to get removed by magic
doomed_photo_ids = (old_photo_ids - observation.photo_ids).compact
unless doomed_photo_ids.blank?
Photo.delay(:priority => INTEGRITY_PRIORITY).destroy_orphans(doomed_photo_ids)
end
Photo.descendent_classes.each do |klass|
klass_key = klass.to_s.underscore.pluralize.to_sym
next unless params["#{klass_key}_to_sync"] && params["#{klass_key}_to_sync"][fieldset_index]
next unless photo = observation.photos.compact.last
photo_o = photo.to_observation
PHOTO_SYNC_ATTRS.each do |a|
hashed_params[observation.id.to_s] ||= {}
if hashed_params[observation.id.to_s][a].blank? && observation.send(a).blank?
hashed_params[observation.id.to_s][a] = photo_o.send(a)
end
end
end
end
# Kind of like :ignore_photos, but :editing_sounds makes it opt-in rather than opt-out
# If editing sounds and no sound parameters are present, assign to an empty array
# This way, sounds will be removed
if params[:editing_sounds]
params[:soundcloud_sounds] ||= {fieldset_index => []}
params[:soundcloud_sounds][fieldset_index] ||= []
observation.sounds = Sound.from_observation_params(params, fieldset_index, current_user)
end
unless observation.update_attributes(hashed_params[observation.id.to_s])
errors = true
end
if !errors && params[:project_id] && !observation.project_observations.where(:project_id => params[:project_id]).exists?
if @project ||= Project.find(params[:project_id])
project_observation = ProjectObservation.create(:project => @project, :observation => observation)
extra_msg = if project_observation.valid?
"Successfully added to #{@project.title}"
else
"Failed to add to #{@project.title}: #{project_observation.errors.full_messages.to_sentence}"
end
end
end
end
respond_to do |format|
if errors
format.html do
if @observations.size == 1
@observation = @observations.first
render :action => 'edit'
else
render :action => 'edit_batch'
end
end
format.xml { render :xml => @observations.collect(&:errors), :status => :unprocessable_entity }
format.json do
render :status => :unprocessable_entity, :json => {
:error => @observations.map{|o| o.errors.full_messages.to_sentence}.to_sentence,
:errors => @observations.collect(&:errors)
}
end
elsif @observations.empty?
msg = if params[:id]
t(:that_observation_no_longer_exists)
else
t(:those_observations_no_longer_exist)
end
format.html do
flash[:error] = msg
redirect_back_or_default(observations_by_login_path(current_user.login))
end
format.json { render :json => {:error => msg}, :status => :gone }
else
format.html do
flash[:notice] = "#{t(:observations_was_successfully_updated)} #{extra_msg}"
if @observations.size == 1
redirect_to observation_path(@observations.first)
else
redirect_to observations_by_login_path(observation_user.login)
end
end
format.xml { head :ok }
format.js { render :json => @observations }
format.json do
if @observations.size == 1 && is_iphone_app_2?
render :json => @observations[0].to_json(
:methods => [:user_login, :iconic_taxon_name],
:include => {
:taxon => Taxon.default_json_options,
:observation_field_values => {},
:project_observations => {
:include => {
:project => {
:only => [:id, :title, :description],
:methods => [:icon_url]
}
}
},
:observation_photos => {
:include => {
:photo => {
:methods => [:license_code, :attribution],
:except => [:original_url, :file_processing, :file_file_size,
:file_content_type, :file_file_name, :mobile, :metadata, :user_id,
:native_realname, :native_photo_id]
}
}
},
})
else
render :json => @observations.to_json(:methods => [:user_login, :iconic_taxon_name])