github.com/CyCoreSystems/ari@v4.8.4+incompatible/rid/rid.go (about)

     1  // Package rid provides unique resource IDs
     2  package rid
     3  
     4  import (
     5  	"crypto/rand"
     6  	"strings"
     7  	"time"
     8  
     9  	"github.com/oklog/ulid"
    10  )
    11  
    12  const (
    13  	// Bridge indicates the resource ID is of a bridge
    14  	Bridge = "br"
    15  
    16  	// Channel indicates the resource ID is of a channel
    17  	Channel = "ch"
    18  
    19  	// Playback indicates the resource ID is of a playback
    20  	Playback = "pb"
    21  
    22  	// Recording indicates the resource ID is for a recording
    23  	Recording = "rc"
    24  
    25  	// Snoop indicates the resource ID is for a snoop session
    26  	Snoop = "sn"
    27  )
    28  
    29  // New returns a new generic resource ID
    30  func New(kind string) string {
    31  
    32  	id := strings.ToLower(ulid.MustNew(ulid.Now(), rand.Reader).String())
    33  
    34  	if kind != "" {
    35  		if len(kind) > 2 {
    36  			kind = kind[:2]
    37  		}
    38  		id += "-" + kind
    39  	}
    40  
    41  	return id
    42  }
    43  
    44  // Timestamp returns the timestamp stored within the resource ID
    45  func Timestamp(id string) (ts time.Time, err error) {
    46  	idx := strings.Index(id, "-")
    47  	if idx > 0 {
    48  		id = id[:idx]
    49  	}
    50  
    51  	uid, err := ulid.Parse(id)
    52  	if err != nil {
    53  		return
    54  	}
    55  
    56  	ms := int64(uid.Time())
    57  	ts = time.Unix(ms/1000, (ms%1000)*1000000)
    58  
    59  	return
    60  }