/
controllers.go
981 lines (901 loc) · 26 KB
/
controllers.go
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
package main
import (
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/randallsquared/go-tigertonic"
"github.com/randallsquared/gochute/profile"
)
type PhotoHandler struct {
}
type Photo struct {
Id int
Created time.Time
Href, Caption string
}
type PhotoChange struct {
Id int
Caption string
}
type Profile struct {
Id int
RateTypeId int
HourlyRate int
DailyRate int
RateUnits string
Created time.Time
Email *string
Phone *string
Name *string
Photos []Photo
Flags []profile.Flag
Utypes []profile.Utype
}
type Auth struct {
Id int
Profile int
Hash *string
Username *string
Name string
Token *string
Created *time.Time
Updated *time.Time
LastAuth *time.Time
Authorized bool
}
type AuthConnect struct {
Hash string
}
type AuthChange struct {
Id *int
Hash *string
Username *string
Name string
Authorized bool
}
type AuthCreate struct {
Username *string
Hash string
Name string
}
type Freetime struct {
Start time.Time
End time.Time
Location *profile.Location
Utypes []profile.Utype
Flags []profile.Flag
}
// NewMessage doesn't need Invite, since it's either part of one or that info is in the URL.
// It doesn't need Sender, since that's the context Profile. It doesn't need Id, since the
// client doesn't know it, yet. It doesn't need Sent, since that's automatically generated
// at creation time. It doesn't need much.
type NewMessage struct {
Photo *int
Body string
}
// NewInvite, like NewMessage, is tailored to avoid duplicating information we already have,
// or which doesn't exist yet, such as the Organizer (context Profile), the Id, which will be
// created automatically, or Active, which must be true on creation. We also don't want to
// pass the entire profiles of Attendees, since no changes can be made to them in any case,
// and that's a lot of extra network traffic which no one needs.
type NewInvite struct {
Attendees []int // Profiles
Start time.Time
End *time.Time
Place string
Message *NewMessage
}
type Message struct {
Id int
Sent time.Time
Sender Profile
Photo *Photo
Body string
}
type Attendee struct {
Profile
Status profile.Status
}
type Invite struct {
Attendees []Attendee
Id int
Organizer Profile
Active bool
Start time.Time
End *time.Time
Created time.Time
Place string
Messages []Message
}
func authenticate(r *http.Request) (http.Header, error) {
token := r.Header.Get(ChuteToken)
if token == "" {
return nil, tigertonic.Unauthorized{errors.New("please log in")}
}
auth := new(profile.Auth)
auth.Token = &token
err := auth.Get()
if err != nil {
return nil, tigertonic.Unauthorized{errors.New("please log in")}
}
c := tigertonic.Context(r).(*Context)
c.Auth = auth
c.Profile = new(profile.Profile)
err = c.Profile.Get(auth)
if err != nil {
return nil, tigertonic.Unauthorized{errors.New("please log in")}
}
return nil, nil
}
func param(u *url.URL, param string) string {
query := u.Query()
return query.Get("{" + param + "}")
}
func findProfile(u *url.URL, c *Context) (*profile.Profile, func(string, ...interface{}) (int, http.Header, Response, error), error) {
id := param(u, "id")
if id == "" {
return c.Profile, nil, nil
}
intId, err := strconv.Atoi(id)
if err != nil {
complaint := "'" + id + "' is not a valid Profile Id."
return nil, error400, errors.New(complaint)
}
ip, err := profile.GetProfile(intId)
if err != nil {
if err.Error() == profile.NotFoundError {
return nil, error404, errors.New("profile not found")
}
return nil, error500, err
}
return ip, nil, nil
}
func (m *Message) convert(im profile.Message) error {
m.Id = im.Id
m.Sent = im.Sent
m.Body = im.Body
ip, err := profile.GetProfile(im.Sender)
if err != nil {
return err
}
m.Sender = Profile{}
err = m.Sender.convert(*ip)
if im.Photo == nil {
// short circuit out o' here; we're done
return nil
}
ph, err := profile.GetPhoto(*im.Photo)
if err != nil {
return err
}
// dammit, we shouldn't have to keep running back to the database for this
ip, err = profile.GetProfile(ph.Profile)
if err != nil {
return err
}
href := ph.GetExpiringUrl(ip.Folder)
m.Photo = &Photo{ph.Id, ph.Created, href, ph.Caption}
return nil
}
func (p *Profile) convert(ip profile.Profile) error {
p.Id = ip.Id
p.RateTypeId = ip.RateTypeId
p.DailyRate = ip.DailyRate
p.HourlyRate = ip.HourlyRate
p.RateUnits = ip.RateUnits
p.Created = ip.Created
p.Email = ip.Email
p.Phone = ip.Phone
p.Name = ip.Name
p.Flags = ip.Flags
p.Utypes = ip.Utypes
dbPhotos, err := ip.Photos()
if err != nil {
return err
}
for _, photo := range dbPhotos {
href := photo.GetExpiringUrl(ip.Folder)
p.Photos = append(p.Photos, Photo{photo.Id, photo.Created, href, photo.Caption})
}
return nil
}
func (i *Invite) convert(ii profile.Invite) error {
i.Id = ii.Id
i.Active = ii.Active
i.Start = ii.Start
i.End = ii.End
i.Created = ii.Created
i.Place = ii.Place
// Organizer and Attendees are or contain Profiles, so there's some hoops to jump through
ip, err := profile.GetProfile(ii.Organizer)
if err != nil {
return err
}
i.Organizer = Profile{}
err = i.Organizer.convert(*ip)
if err != nil {
return err
}
for _, att := range ii.Attendees {
log.Println("got status", att.Status, "for attendee", att.Profile.Id)
p := Profile{}
err = p.convert(att.Profile)
if err != nil {
return err
}
i.Attendees = append(i.Attendees, Attendee{p, att.Status})
}
for _, im := range ii.Messages {
m := Message{}
err = m.convert(im)
if err != nil {
return err
}
i.Messages = append(i.Messages, m)
}
return nil
}
func getInvite(u *url.URL, h http.Header, _ interface{}, c *Context) (int, http.Header, Response, error) {
id := param(u, "id")
intId, err := strconv.Atoi(id)
if err != nil {
return error400("'"+id+"' is not a valid Invite Id.", "Bad invite id.")
}
ii, err := profile.GetInvite(intId)
if err != nil {
return error500("db failure: p208", err.Error())
}
i := Invite{}
err = i.convert(*ii)
if err != nil {
return error500("db failure: p204", err.Error())
}
return http.StatusOK, nil, i, nil
}
func cancelInvite(u *url.URL, h http.Header, _ interface{}, c *Context) (int, http.Header, Response, error) {
id := param(u, "id")
intId, err := strconv.Atoi(id)
if err != nil {
return error400("'"+id+"' is not a valid Invite Id.", "Bad invite id.")
}
ii, err := profile.GetInvite(intId)
if err != nil {
errString := err.Error()
if errString == profile.NotFoundError {
return error404("Invite not found.", errString)
}
return error500("db failure: p269", errString)
}
err = ii.Cancel()
if err != nil {
return error500("db failure: p273", err.Error())
}
ii.Active = false
i := Invite{}
err = i.convert(*ii)
if err != nil {
return error500("db failure: p279", err.Error())
}
return http.StatusOK, nil, i, nil
}
func addMessage(u *url.URL, h http.Header, m *NewMessage, c *Context) (int, http.Header, Response, error) {
id := param(u, "id")
intId, err := strconv.Atoi(id)
if err != nil {
return error400("'"+id+"' is not a valid Invite Id.", "Bad invite id.")
}
ii, err := profile.GetInvite(intId)
if err != nil {
errString := err.Error()
if errString == profile.NotFoundError {
return error404("Invite not found.", errString)
}
return error500("db failure: p268", errString)
}
// if there's a photo, check that it exists and is owned by us
if m.Photo != nil {
photoId := *m.Photo
_, err := c.Profile.GetPhoto(photoId)
if err != nil {
return error400("'"+strconv.Itoa(photoId)+"' is not a valid Photo Id.", "Bad photo id")
}
}
im := profile.Message{0, time.Now(), c.Profile.Id, ii.Id, m.Photo, m.Body}
err = im.Create()
if err != nil {
return error500("db failure: p273", err.Error())
}
ii.RefreshMessages(nil)
i := Invite{}
err = i.convert(*ii)
if err != nil {
return error500("db failure: p280", err.Error())
}
return http.StatusOK, nil, i, nil
}
func changeStatus(u *url.URL, h http.Header, s *profile.Status, c *Context) (int, http.Header, Response, error) {
status := *s
if s == nil || !profile.Statuses[status] {
complaint := "'" + string(status) + "' doesn't appear to be a valid status: "
complaint += strings.Join(profile.StatusStrings(), ", ")
return error400(complaint, "non-Status status update")
}
id := param(u, "id")
intId, err := strconv.Atoi(id)
if err != nil {
return error400("'"+id+"' is not a valid Invite Id.", "Bad invite id.")
}
ii, err := profile.GetInvite(intId)
if err != nil {
errString := err.Error()
if errString == profile.NotFoundError {
return error404("Invite not found.", errString)
}
return error500("db failure: p270", errString)
}
err = ii.ChangeStatus(*c.Profile, status)
if err != nil {
return error500("db failure: p278", err.Error())
}
// let's avoid going back for another dozen db queries...
for i := range ii.Attendees {
if ii.Attendees[i].Id == c.Profile.Id {
ii.Attendees[i].Status = status
}
}
i := Invite{}
err = i.convert(*ii)
if err != nil {
return error500("db failure: p289", err.Error())
}
return http.StatusOK, nil, i, nil
}
func addAttendees(u *url.URL, h http.Header, as []int, c *Context) (int, http.Header, Response, error) {
id := param(u, "id")
intId, err := strconv.Atoi(id)
if err != nil {
return error400("'"+id+"' is not a valid Invite Id.", "Bad invite id.")
}
ii, err := profile.GetInvite(intId)
if err != nil {
errString := err.Error()
if errString == profile.NotFoundError {
return error404("Invite not found.", errString)
}
return error500("db failure: p373", errString)
}
if ii.Organizer != c.Profile.Id {
return error403("You are not the Organizer for this Invite.", "Bad organizer!")
}
var atts []profile.Attendee
for _, a := range as {
p, err := profile.GetProfile(a)
if err != nil {
complaint := "'" + strconv.Itoa(a) + "' is not a valid Profile id."
return error400(complaint, "got a non-Profile Id for an attendee")
}
atts = append(atts, profile.Attendee{*p, profile.StatusPending})
}
err = ii.AddAttendees(atts)
if err != nil {
return error500("db failure: p392", err.Error())
}
err = ii.RefreshAttendees(nil)
if err != nil {
return error500("db failure: p397", err.Error())
}
i := Invite{}
err = i.convert(*ii)
if err != nil {
return error500("db failure: p289", err.Error())
}
return http.StatusOK, nil, i, nil
}
func invite(u *url.URL, h http.Header, i *NewInvite, c *Context) (int, http.Header, Response, error) {
if i.End != nil && !i.Start.Before(*i.End) {
complaint := i.End.String() + " is not after " + i.Start.String()
return error400(complaint, "got bad Invite representation")
}
if len(i.Attendees) < 1 {
complaint := "There must be at least one attendee for an invite."
return error400(complaint, "got Invite without any attendees")
}
var atts []profile.Attendee
for _, att := range i.Attendees {
p, err := profile.GetProfile(att)
if err != nil {
complaint := "'" + strconv.Itoa(att) + "' is not a valid Profile id."
return error400(complaint, "got a non-Profile Id for an attendee")
}
atts = append(atts, profile.Attendee{*p, profile.StatusPending})
}
ii := profile.Invite{}
ii.Attendees = atts
ii.Organizer = c.Profile.Id
ii.Active = true
ii.Start = i.Start
ii.End = i.End
ii.Created = time.Now()
ii.Place = i.Place
err := ii.Create()
if err != nil {
return error500("db failure: p175", err.Error())
}
if i.Message != nil {
m := profile.Message{0, time.Now(), c.Profile.Id, ii.Id, i.Message.Photo, i.Message.Body}
err := m.Create()
if err != nil {
return error500("db failure: p245", err.Error())
}
}
newI, err := profile.GetInvite(ii.Id)
if err != nil {
return error500("db failure: p250", err.Error())
}
out := Invite{}
err = out.convert(*newI)
if err != nil {
return error500("db failure: p227", err.Error())
}
return http.StatusOK, nil, out, nil
}
// createProfile receives a hash and an optional username.
// If there is a username, it must be unique.
func createProfile(u *url.URL, h http.Header, r *Auth) (int, http.Header, Response, error) {
var err error
p := new(profile.Profile)
a := profile.NewAuth(r.Hash, r.Username)
// if Getting an Auth succeeds, there was an existing row
err = a.Get()
if err == nil {
return error400("auth exists", "hash:", *r.Hash)
}
a.Name = r.Name
err = p.Create()
if err != nil {
return error500("db failure: p56", err.Error())
}
a.Profile = p.Id
err = a.Create()
if err != nil {
return error500("db failure: p62", err.Error())
}
// if all is well...
oh := http.Header{}
oh.Add(ChuteToken, *a.Token)
response := Profile{Id: p.Id, Created: p.Created}
return http.StatusCreated, oh, response, nil
}
func connectAuth(u *url.URL, h http.Header, r *AuthConnect, c *Context) (int, http.Header, Response, error) {
a := profile.NewAuth(&r.Hash, nil)
err := a.Get()
if err != nil {
return error400("couldn't find that auth", err.Error())
}
if a.Username != nil {
return error400("can't connect a username and password to another account")
}
// this is the only change we make at this endpoint
a.Profile = c.Profile.Id
err = a.Save()
if err != nil {
return error500("db failure: p520", err.Error())
}
return getAuths(u, h, nil, c)
}
func updateAuth(u *url.URL, h http.Header, r *AuthChange, c *Context) (int, http.Header, Response, error) {
a := new(profile.Auth)
if r.Id != nil {
a.Id = *r.Id
} else {
a.Hash = []byte(*r.Hash)
a.Username = r.Username
}
err := a.Get()
if err != nil {
return error400("couldn't find that auth", err.Error())
}
if a.Profile != c.Profile.Id {
return error400("unauthorized access")
}
if r.Hash != nil {
a.InHash = []byte(*r.Hash)
}
a.Username = r.Username
a.Name = r.Name
a.Authorized = r.Authorized
err = a.Save()
if err != nil {
return error500("db failure: p544", err.Error())
}
return getAuths(u, h, nil, c)
}
func createAuth(u *url.URL, h http.Header, r *AuthCreate, c *Context) (int, http.Header, Response, error) {
a := profile.NewAuth(&r.Hash, r.Username)
err := a.Get()
if err != nil {
// this auth doesn't already exist
a.Name = r.Name
a.Authorized = true
a.Profile = c.Profile.Id
a.InHash = []byte(r.Hash)
a.Username = r.Username
err = a.Create()
if err != nil {
return error500("db failure: p560", err.Error())
}
return getAuths(u, h, nil, c)
}
return error400("unauthorized access")
}
func login(u *url.URL, h http.Header, r *Auth) (int, http.Header, Response, error) {
if r == nil {
return error400("no authorization provided")
}
auth := profile.NewAuth(r.Hash, r.Username)
err := auth.Get()
log.Println("got auth:", auth)
if err != nil {
return error401("login failure", "no such auth!")
} else if !auth.Authenticated() {
return error401("login failure", "hash:", *r.Hash)
}
token, err := auth.Login()
if err != nil {
return error500("db failure: p137", err.Error())
}
oh := http.Header{}
oh.Add(ChuteToken, token)
return http.StatusOK, oh, struct{}{}, nil
}
func logout(u *url.URL, h http.Header, r *Auth, c *Context) (int, http.Header, Response, error) {
err := c.Auth.Logout()
if err != nil {
return error500("db failure: p110", err.Error())
}
return http.StatusOK, nil, struct{}{}, nil
}
func getAuths(u *url.URL, h http.Header, _ interface{}, c *Context) (int, http.Header, Response, error) {
var out []Auth
auths, err := c.Profile.GetAuths()
if err != nil {
return error500("db failure: p102", err.Error())
}
for _, auth := range auths {
out = append(out, Auth{auth.Id, auth.Profile, nil, auth.Username, auth.Name, auth.Token, auth.Created, auth.Updated, auth.LastAuth, auth.Authorized})
}
return http.StatusOK, nil, out, nil
}
/*
getMyInvitesBySearch pulls from the URL (and can only see invites to which this user is a party).
'status': one of the profile.Status constants.
'from': ISO-8601 timestamp to find invites which start on or after (only the date is used).
*/
func getMyInvitesBySearch(u *url.URL, h http.Header, _ interface{}, c *Context) (int, http.Header, Response, error) {
var (
is []Invite
i Invite
err error
statuses []profile.Status
from time.Time
to time.Time
active *bool
)
tmpTrue := true
tmpFalse := false
query := u.Query()
if a := query.Get("active"); len(a) > 0 {
if a == "false" {
active = &tmpFalse
} else if a == "true" {
active = &tmpTrue
} else {
return error400("didn't understand '"+a+"' as a value for 'active'", a)
}
}
s := query["status"]
for _, status := range s {
statuses = append(statuses, profile.Status(status))
}
if t := query.Get("from"); len(t) > 0 {
from, err = time.Parse(time.RFC3339Nano, t)
if err != nil {
return error400("didn't understand '"+t+"' as a search time", err.Error())
}
} else {
from = time.Now()
}
if t := query.Get("to"); len(t) > 0 {
to, err = time.Parse(time.RFC3339Nano, t)
if err != nil {
return error400("didn't understand '"+t+"' as a search time", err.Error())
}
} else {
to = time.Now().AddDate(0, 0, 90) // 90 days from now is the default
}
iis, err := c.Profile.GetInvites(statuses, from, to, active)
if err != nil {
return error500("db failure: p409", err.Error())
}
for _, ii := range iis {
i = Invite{}
err = i.convert(ii)
if err != nil {
return error500("db failure: p418", err.Error())
}
is = append(is, i)
}
return http.StatusOK, nil, is, nil
}
/*
getProfilesBySearch pulls from the URL
'from': ISO-8601 timestamp to find profiles with free time surrounding.
'type': the Profile type to search for (multiple specifications are ORed together)
'flag': the flags to search for (multiple specifications are ANDed together)
*/
func getProfilesBySearch(u *url.URL, h http.Header, _ interface{}, c *Context) (int, http.Header, Response, error) {
var (
p Profile
ps []Profile
from time.Time
lat float64
lon float64
err error
)
query := u.Query()
if la := query.Get("lat"); len(la) > 0 {
lat, err = strconv.ParseFloat(la, 32)
if err != nil {
return error400("didn't understand '"+la+"' as a latitude", err.Error())
}
}
if lo := query.Get("lon"); len(lo) > 0 {
lon, err = strconv.ParseFloat(lo, 32)
if err != nil {
return error400("didn't understand '"+lo+"' as a longitude", err.Error())
}
}
if f := query.Get("from"); len(f) > 0 {
from, err = time.Parse(time.RFC3339Nano, f)
if err != nil {
return error400("didn't understand '"+f+"' as a search time", err.Error())
}
} else {
from = time.Now()
}
flags := query["flag"]
for _, flag := range flags {
if _, err := strconv.ParseInt(flag, 10, 0); err != nil {
return error400("didn't understand '"+flag+"' as a flag", err.Error())
}
}
utypes := query["type"]
for _, t := range utypes {
if _, err := strconv.ParseInt(t, 10, 0); err != nil {
return error400("didn't understand '"+t+"' as a profile type", err.Error())
}
}
// get all profiles with freetimes surrounding this 'from'
// we start with the autenticated profile to get the lat and long without having to pass it
ips, err := c.Profile.Search(from, utypes, flags, float32(lat), float32(lon))
if err != nil {
return error500("db failure: p205", err.Error())
}
for _, ip := range ips {
p = Profile{}
err = p.convert(ip)
if err != nil {
return error500("db failure: p247", err.Error())
}
ps = append(ps, p)
}
return http.StatusOK, nil, ps, nil
}
func getProfile(u *url.URL, h http.Header, _ interface{}, c *Context) (int, http.Header, Response, error) {
var p Profile
var ip *profile.Profile
ip, errType, err := findProfile(u, c)
if err != nil {
return errType("profile not found", err.Error())
}
p = Profile{}
err = p.convert(*ip)
if err != nil {
return error500("db failure: p188", err.Error())
}
return http.StatusOK, nil, p, nil
}
func getFlags(u *url.URL, h http.Header, _ interface{}) (int, http.Header, Response, error) {
flags, err := profile.GetFlags()
if err != nil {
return error500("db failure: p220", err.Error())
}
return http.StatusOK, nil, flags, nil
}
func getRates(u *url.URL, h http.Header, _ interface{}) (int, http.Header, Response, error) {
rates, err := profile.GetRateTypes()
if err != nil {
return error500("db failure: p762", err.Error())
}
return http.StatusOK, nil, rates, nil
}
func getTypes(u *url.URL, h http.Header, _ interface{}) (int, http.Header, Response, error) {
types, err := profile.GetTypes()
if err != nil {
return error500("db failure: p228", err.Error())
}
return http.StatusOK, nil, types, nil
}
func getFreetime(u *url.URL, h http.Header, _ interface{}, c *Context) (int, http.Header, Response, error) {
var fs []Freetime
p, errType, err := findProfile(u, c)
if err != nil {
return errType("profile not found", err.Error())
}
profileFs, err := p.GetFreetimes()
if err != nil {
return error500("db failure: p212", err.Error())
}
for _, f := range profileFs {
fs = append(fs, Freetime{f.Start, f.End, f.Location, f.Utypes, f.Flags})
}
return http.StatusOK, nil, fs, nil
}
func removeAllFreetime(u *url.URL, h http.Header, _ interface{}, c *Context) (int, http.Header, Response, error) {
err := c.Profile.RemoveAllFreetime()
if err != nil {
return error500("db failure: p238", err.Error())
}
return http.StatusNoContent, nil, nil, nil
}
func removeFreetime(u *url.URL, h http.Header, _ interface{}, c *Context) (int, http.Header, Response, error) {
var err error
s := param(u, "start")
start, err := time.Parse(time.RFC3339Nano, s)
if err != nil {
return error500("didn't understand '"+s+"' as a start time", err.Error())
}
err = c.Profile.RemoveFreetime(start)
if err != nil {
return error500("db failure: p253", err.Error())
}
return getFreetime(u, h, nil, c)
}
func createFreetime(u *url.URL, h http.Header, fs []Freetime, c *Context) (int, http.Header, Response, error) {
// need to ensure that start is before end
for _, f := range fs {
if !f.Start.Before(f.End) {
complaint := f.End.String() + " is not after " + f.Start.String()
return error400(complaint, "got bad Freetime representation")
}
// I'm not doing the create/insert here because I don't want to insert a random number
// of these before having an error. So we have to loop over range fs twice, which is
// not very nice, but not sure how else to handle it.
}
var err error
for _, f := range fs {
err = c.Profile.NewFreetime(f.Start, f.End, f.Location, f.Utypes, f.Flags)
if err != nil {
if err.Error() == profile.DuplicateFreetimeError {
err = c.Profile.UpdateFreetime(f.Start, f.End, f.Location, f.Utypes, f.Flags)
if err != nil {
return error500("db failure: p261", err.Error())
}
continue
}
return error500("db failure: p223", err.Error())
}
}
return getFreetime(u, h, nil, c)
}
func updateProfile(u *url.URL, h http.Header, p *Profile, c *Context) (int, http.Header, Response, error) {
// we're already authed, so we just have to update and save, right?
c.Profile.RateTypeId = p.RateTypeId
c.Profile.HourlyRate = p.HourlyRate
c.Profile.DailyRate = p.DailyRate
c.Profile.RateUnits = p.RateUnits
c.Profile.Email = p.Email
c.Profile.Phone = p.Phone
c.Profile.Name = p.Name
c.Profile.Flags = p.Flags
c.Profile.Utypes = p.Utypes
err := c.Profile.Save()
if err != nil {
return error500("db failure: p308", err.Error())
}
out := Profile{}
err = out.convert(*c.Profile)
if err != nil {
return error500("db failure: p313", err.Error())
}
return http.StatusOK, nil, out, nil
}
func updatePhoto(u *url.URL, h http.Header, p *PhotoChange, c *Context) (int, http.Header, Response, error) {
photo, err := c.Profile.GetPhoto(p.Id)
if err != nil {
return error400("'"+string(p.Id)+"' is not a valid Photo id.", "Bad photo id.")
}
photo.Caption = p.Caption
err = photo.Save()
if err != nil {
return error500("db failure: p837", err.Error())
}
href := photo.GetExpiringUrl(c.Profile.Folder)
out := Photo{photo.Id, photo.Created, href, photo.Caption}
return http.StatusOK, nil, out, nil
}
func removePhoto(u *url.URL, h http.Header, _ interface{}, c *Context) (int, http.Header, Response, error) {
id := u.Query().Get("{id}")
intId, err := strconv.Atoi(id)
if err != nil {
return error400("'"+id+"' is not a valid Photo id.", "Bad photo id.")
}
photo, err := c.Profile.GetPhoto(intId)
if err != nil {
return error404("photo not found", err.Error())
}
err = photo.Remove()
if err != nil {
return error500("photo removal error: p220", err.Error())
}
return http.StatusNoContent, nil, nil, nil
}
// PhotoHandler.ServeHTTP currently handles only the first file uploaded.
func (ph PhotoHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var complaint string
file, meta, err := r.FormFile("photo")
if err != nil {
complaint = `{"error": "file upload issue: p200"}`
log.Println(complaint, err.Error())
w.WriteHeader(500)
w.Write([]byte(complaint + "\n"))
return
}
typeArray := meta.Header["Content-Type"]
if len(typeArray) < 1 || !allowedPhotoTypes[typeArray[0]] {
complaint = `{"error": "please upload only an image file in jpg, gif, or png"}`
log.Println(complaint)
w.WriteHeader(400)
w.Write([]byte(complaint + "\n"))
return
}
ctype := typeArray[0]
fmt.Println(r.FormValue("caption"))
c := tigertonic.Context(r).(*Context)
photo := c.Profile.NewPhoto(r.FormValue("caption"))
_, err = photo.Create(c.Profile.Folder, ctype, file)
if err != nil {
complaint = `{"error": "file upload issue: p244"}`
log.Println(complaint, err.Error())
w.WriteHeader(500)
w.Write([]byte(complaint + "\n"))
return
}
href := photo.GetExpiringUrl(c.Profile.Folder)
output, err := json.Marshal(Photo{photo.Id, photo.Created, href, photo.Caption})
if err != nil {
complaint = `{"error": "file upload issue: p874"}`
log.Println(complaint, err.Error())
w.WriteHeader(500)
w.Write([]byte(complaint + "\n"))
return
}
_, err = w.Write([]byte(output))
if err != nil {
log.Println("WTF? p226", err.Error())
}
}
/*
func blockProfile(u *url.URL, h http.Header, _ interface{}) (int, http.Header, interface{}, error) {
return http.StatusOK, nil, nil, nil
}
func unBlockProfile(u *url.URL, h http.Header, _ interface{}) (int, http.Header, interface{}, error) {
return http.StatusOK, nil, nil, nil
}
*/