File size: 2,304 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package gadb

import (
	"database/sql"
	"database/sql/driver"
	"fmt"
	"strings"
)

// ProviderMessageID is a provider-specific identifier for a message.
type ProviderMessageID struct {
	// ExternalID is the provider-specific identifier for the message.
	ExternalID   string
	ProviderName string
}

var (
	_ driver.Valuer = ProviderMessageID{}
	_ sql.Scanner   = &ProviderMessageID{}
)

// ParseProviderMessageID parses a provider-specific identifier for a message.
func ParseProviderMessageID(id string) (ProviderMessageID, error) {
	var p ProviderMessageID
	err := p.Scan(id)
	return p, err
}

// String returns a parseable string representation of the provider-specific identifier for a message.
func (p ProviderMessageID) String() string {
	if p.ProviderName == "" || p.ExternalID == "" {
		return ""
	}

	return fmt.Sprintf("%s:%s", p.ProviderName, p.ExternalID)
}

func (p ProviderMessageID) Value() (driver.Value, error) {
	// Older versions of GoAlert had a separate name for each provider from the destination type, so we need to map them for compatibility.
	//
	// Since the SMS and voice message types are the only ones that rely on async status updates, they are the only ones that require this mapping.
	switch p.ProviderName {
	case "builtin-twilio-sms":
		p.ProviderName = "Twilio-SMS"
	case "builtin-twilio-voice":
		p.ProviderName = "Twilio-Voice"
	}
	val := p.String()
	if val == "" {
		return nil, nil
	}

	return val, nil
}

func (p *ProviderMessageID) Scan(value interface{}) error {
	switch v := value.(type) {
	case string:
		var ok bool
		p.ProviderName, p.ExternalID, ok = strings.Cut(v, ":")
		if !ok {
			return fmt.Errorf("invalid provider id format: '%s'; expected 'providername:providerid'", v)
		}

		// Older versions of GoAlert had a separate name for each provider from the destination type, so we need to map them for compatibility.
		//
		// Since the SMS and voice message types are the only ones that rely on async status updates, they are the only ones that require this mapping.
		switch p.ProviderName {
		case "Twilio-SMS":
			p.ProviderName = "builtin-twilio-sms"
		case "Twilio-Voice":
			p.ProviderName = "builtin-twilio-voice"
		}
	case nil:
		p.ExternalID = ""
		p.ProviderName = ""
	default:
		return fmt.Errorf("unsupported type: %T", v)
	}

	return nil
}