Add check for already invited
2 files changed, 81 insertions(+), 0 deletions(-)

M db.go
M db_test.go
M db.go +39 -0
@@ 11,9 11,11 @@ import (
 	"time"
 )
 
+// TODO track invite changes; hash(summary, start, end, description)
 type Db interface {
 	Stats() DbStats
 	UpdateInvites(string, []string) error
+	Invited(string, string) (bool, error)
 	Error() error
 }
 

          
@@ 103,6 105,43 @@ func (d db) UpdateInvites(id string, as 
 	return nil
 }
 
+func (d db) Invited(id, email string) (bool, error) {
+	// Lock the database
+	ln := d.path + ".lock"
+	lock := flock.New(ln)
+	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+	defer cancel()
+	success, err := lock.TryLockContext(ctx, 100*time.Millisecond)
+	if !success {
+		msg := fmt.Sprintf("Database appears to be locked by another process. Try removing %s\n", ln)
+		return false, errors.New(msg)
+	}
+	if err != nil {
+		return false, err
+	}
+	defer lock.Unlock()
+	defer os.Remove(lock.Path())
+
+	rs, err := d.readDb()
+	if err != nil {
+		return false, err
+	}
+
+	temail := strings.ToLower(strings.TrimSpace(email))
+	for _, r := range rs {
+		if r[0] == id {
+			es := strings.Split(r[1], ",")
+			for _, e := range es {
+				te := strings.ToLower(strings.TrimSpace(e))
+				if temail == te {
+					return true, nil
+				}
+			}
+		}
+	}
+	return false, nil
+}
+
 func (d db) save(rs [][]string) error {
 	// Write the DB back out
 	foutn := d.path + ".tmp"

          
M db_test.go +42 -0
@@ 154,3 154,45 @@ func Test_db_UpdateInvites(t *testing.T)
 
 // TODO test locking
 // TODO test malformed DB
+
+func TestInvited(t *testing.T) {
+	type args struct {
+		id string
+		email string
+	}
+	tests := []struct {
+		name    string
+		args    args
+		want    bool
+		wantErr bool
+	}{
+		{"yes invited one", args{"2", "w@v.u"}, true, false},
+		{"not invited", args{"2", "a@b.c"}, false, false},
+		{"yes invited many", args{"3", "q@p.o"}, true, false},
+	}
+
+	// Set up the test DB
+	dbName := "testdb"
+	fout, err := os.Create(dbName)
+	if err != nil {
+		t.Errorf("error setting up db %s", err)
+	}
+	// Clean up test data
+	defer os.Remove(dbName)
+	fout.WriteString("1\tz@y.x\n2\tw@v.u\n3\tt@s.r,q@p.o\n4\tq@r.s,a@b.c,d@e.f\n")
+	fout.Close()
+
+	d := OpenDb(dbName)
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			got, err := d.Invited(tt.args.id, tt.args.email)
+			if (err != nil) != tt.wantErr {
+				t.Errorf("Invited() %s error = %v, wantErr %v", tt.name, err, tt.wantErr)
+				return
+			}
+			if got != tt.want {
+				t.Errorf("Invited() %s = %v, want %v", tt.name, got, tt.want)
+			}
+		})
+	}
+}