repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
list | docstring
stringlengths 6
2.61k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 85
252
| partition
stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
docker/swarmkit
|
manager/state/store/memory.go
|
Wedged
|
func (s *MemoryStore) Wedged() bool {
lockedAt := s.updateLock.LockedAt()
if lockedAt.IsZero() {
return false
}
return time.Since(lockedAt) > WedgeTimeout
}
|
go
|
func (s *MemoryStore) Wedged() bool {
lockedAt := s.updateLock.LockedAt()
if lockedAt.IsZero() {
return false
}
return time.Since(lockedAt) > WedgeTimeout
}
|
[
"func",
"(",
"s",
"*",
"MemoryStore",
")",
"Wedged",
"(",
")",
"bool",
"{",
"lockedAt",
":=",
"s",
".",
"updateLock",
".",
"LockedAt",
"(",
")",
"\n",
"if",
"lockedAt",
".",
"IsZero",
"(",
")",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"return",
"time",
".",
"Since",
"(",
"lockedAt",
")",
">",
"WedgeTimeout",
"\n",
"}"
] |
// Wedged returns true if the store lock has been held for a long time,
// possibly indicating a deadlock.
|
[
"Wedged",
"returns",
"true",
"if",
"the",
"store",
"lock",
"has",
"been",
"held",
"for",
"a",
"long",
"time",
"possibly",
"indicating",
"a",
"deadlock",
"."
] |
59163bf75df38489d4a10392265d27156dc473c5
|
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/store/memory.go#L972-L979
|
train
|
docker/swarmkit
|
template/getter.go
|
NewTemplatedSecretGetter
|
func NewTemplatedSecretGetter(dependencies exec.DependencyGetter, t *api.Task, node *api.NodeDescription) exec.SecretGetter {
return templatedSecretGetter{dependencies: dependencies, t: t, node: node}
}
|
go
|
func NewTemplatedSecretGetter(dependencies exec.DependencyGetter, t *api.Task, node *api.NodeDescription) exec.SecretGetter {
return templatedSecretGetter{dependencies: dependencies, t: t, node: node}
}
|
[
"func",
"NewTemplatedSecretGetter",
"(",
"dependencies",
"exec",
".",
"DependencyGetter",
",",
"t",
"*",
"api",
".",
"Task",
",",
"node",
"*",
"api",
".",
"NodeDescription",
")",
"exec",
".",
"SecretGetter",
"{",
"return",
"templatedSecretGetter",
"{",
"dependencies",
":",
"dependencies",
",",
"t",
":",
"t",
",",
"node",
":",
"node",
"}",
"\n",
"}"
] |
// NewTemplatedSecretGetter returns a SecretGetter that evaluates templates.
|
[
"NewTemplatedSecretGetter",
"returns",
"a",
"SecretGetter",
"that",
"evaluates",
"templates",
"."
] |
59163bf75df38489d4a10392265d27156dc473c5
|
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/template/getter.go#L16-L18
|
train
|
docker/swarmkit
|
template/getter.go
|
NewTemplatedConfigGetter
|
func NewTemplatedConfigGetter(dependencies exec.DependencyGetter, t *api.Task, node *api.NodeDescription) TemplatedConfigGetter {
return templatedConfigGetter{dependencies: dependencies, t: t, node: node}
}
|
go
|
func NewTemplatedConfigGetter(dependencies exec.DependencyGetter, t *api.Task, node *api.NodeDescription) TemplatedConfigGetter {
return templatedConfigGetter{dependencies: dependencies, t: t, node: node}
}
|
[
"func",
"NewTemplatedConfigGetter",
"(",
"dependencies",
"exec",
".",
"DependencyGetter",
",",
"t",
"*",
"api",
".",
"Task",
",",
"node",
"*",
"api",
".",
"NodeDescription",
")",
"TemplatedConfigGetter",
"{",
"return",
"templatedConfigGetter",
"{",
"dependencies",
":",
"dependencies",
",",
"t",
":",
"t",
",",
"node",
":",
"node",
"}",
"\n",
"}"
] |
// NewTemplatedConfigGetter returns a ConfigGetter that evaluates templates.
|
[
"NewTemplatedConfigGetter",
"returns",
"a",
"ConfigGetter",
"that",
"evaluates",
"templates",
"."
] |
59163bf75df38489d4a10392265d27156dc473c5
|
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/template/getter.go#L64-L66
|
train
|
docker/swarmkit
|
template/getter.go
|
NewTemplatedDependencyGetter
|
func NewTemplatedDependencyGetter(dependencies exec.DependencyGetter, t *api.Task, node *api.NodeDescription) exec.DependencyGetter {
return templatedDependencyGetter{
secrets: NewTemplatedSecretGetter(dependencies, t, node),
configs: NewTemplatedConfigGetter(dependencies, t, node),
}
}
|
go
|
func NewTemplatedDependencyGetter(dependencies exec.DependencyGetter, t *api.Task, node *api.NodeDescription) exec.DependencyGetter {
return templatedDependencyGetter{
secrets: NewTemplatedSecretGetter(dependencies, t, node),
configs: NewTemplatedConfigGetter(dependencies, t, node),
}
}
|
[
"func",
"NewTemplatedDependencyGetter",
"(",
"dependencies",
"exec",
".",
"DependencyGetter",
",",
"t",
"*",
"api",
".",
"Task",
",",
"node",
"*",
"api",
".",
"NodeDescription",
")",
"exec",
".",
"DependencyGetter",
"{",
"return",
"templatedDependencyGetter",
"{",
"secrets",
":",
"NewTemplatedSecretGetter",
"(",
"dependencies",
",",
"t",
",",
"node",
")",
",",
"configs",
":",
"NewTemplatedConfigGetter",
"(",
"dependencies",
",",
"t",
",",
"node",
")",
",",
"}",
"\n",
"}"
] |
// NewTemplatedDependencyGetter returns a DependencyGetter that evaluates templates.
|
[
"NewTemplatedDependencyGetter",
"returns",
"a",
"DependencyGetter",
"that",
"evaluates",
"templates",
"."
] |
59163bf75df38489d4a10392265d27156dc473c5
|
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/template/getter.go#L104-L109
|
train
|
docker/swarmkit
|
manager/state/raft/storage/storage.go
|
BootstrapNew
|
func (e *EncryptedRaftLogger) BootstrapNew(metadata []byte) error {
e.encoderMu.Lock()
defer e.encoderMu.Unlock()
encrypter, decrypter := encryption.Defaults(e.EncryptionKey, e.FIPS)
walFactory := NewWALFactory(encrypter, decrypter)
for _, dirpath := range []string{filepath.Dir(e.walDir()), e.snapDir()} {
if err := os.MkdirAll(dirpath, 0700); err != nil {
return errors.Wrapf(err, "failed to create %s", dirpath)
}
}
var err error
// the wal directory must not already exist upon creation
e.wal, err = walFactory.Create(e.walDir(), metadata)
if err != nil {
return errors.Wrap(err, "failed to create WAL")
}
e.snapshotter = NewSnapFactory(encrypter, decrypter).New(e.snapDir())
return nil
}
|
go
|
func (e *EncryptedRaftLogger) BootstrapNew(metadata []byte) error {
e.encoderMu.Lock()
defer e.encoderMu.Unlock()
encrypter, decrypter := encryption.Defaults(e.EncryptionKey, e.FIPS)
walFactory := NewWALFactory(encrypter, decrypter)
for _, dirpath := range []string{filepath.Dir(e.walDir()), e.snapDir()} {
if err := os.MkdirAll(dirpath, 0700); err != nil {
return errors.Wrapf(err, "failed to create %s", dirpath)
}
}
var err error
// the wal directory must not already exist upon creation
e.wal, err = walFactory.Create(e.walDir(), metadata)
if err != nil {
return errors.Wrap(err, "failed to create WAL")
}
e.snapshotter = NewSnapFactory(encrypter, decrypter).New(e.snapDir())
return nil
}
|
[
"func",
"(",
"e",
"*",
"EncryptedRaftLogger",
")",
"BootstrapNew",
"(",
"metadata",
"[",
"]",
"byte",
")",
"error",
"{",
"e",
".",
"encoderMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"e",
".",
"encoderMu",
".",
"Unlock",
"(",
")",
"\n",
"encrypter",
",",
"decrypter",
":=",
"encryption",
".",
"Defaults",
"(",
"e",
".",
"EncryptionKey",
",",
"e",
".",
"FIPS",
")",
"\n",
"walFactory",
":=",
"NewWALFactory",
"(",
"encrypter",
",",
"decrypter",
")",
"\n\n",
"for",
"_",
",",
"dirpath",
":=",
"range",
"[",
"]",
"string",
"{",
"filepath",
".",
"Dir",
"(",
"e",
".",
"walDir",
"(",
")",
")",
",",
"e",
".",
"snapDir",
"(",
")",
"}",
"{",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"dirpath",
",",
"0700",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"dirpath",
")",
"\n",
"}",
"\n",
"}",
"\n",
"var",
"err",
"error",
"\n",
"// the wal directory must not already exist upon creation",
"e",
".",
"wal",
",",
"err",
"=",
"walFactory",
".",
"Create",
"(",
"e",
".",
"walDir",
"(",
")",
",",
"metadata",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"e",
".",
"snapshotter",
"=",
"NewSnapFactory",
"(",
"encrypter",
",",
"decrypter",
")",
".",
"New",
"(",
"e",
".",
"snapDir",
"(",
")",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// BootstrapNew creates a new snapshotter and WAL writer, expecting that there is nothing on disk
|
[
"BootstrapNew",
"creates",
"a",
"new",
"snapshotter",
"and",
"WAL",
"writer",
"expecting",
"that",
"there",
"is",
"nothing",
"on",
"disk"
] |
59163bf75df38489d4a10392265d27156dc473c5
|
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/raft/storage/storage.go#L143-L163
|
train
|
docker/swarmkit
|
manager/state/raft/storage/storage.go
|
RotateEncryptionKey
|
func (e *EncryptedRaftLogger) RotateEncryptionKey(newKey []byte) {
e.encoderMu.Lock()
defer e.encoderMu.Unlock()
if e.wal != nil { // if the wal exists, the snapshotter exists
// We don't want to have to close the WAL, because we can't open a new one.
// We need to know the previous snapshot, because when you open a WAL you
// have to read out all the entries from a particular snapshot, or you can't
// write. So just rotate the encoders out from under it. We already
// have a lock on writing to snapshots and WALs.
wrapped, ok := e.wal.(*wrappedWAL)
if !ok {
panic(fmt.Errorf("EncryptedRaftLogger's WAL is not a wrappedWAL"))
}
wrapped.encrypter, wrapped.decrypter = encryption.Defaults(newKey, e.FIPS)
e.snapshotter = NewSnapFactory(wrapped.encrypter, wrapped.decrypter).New(e.snapDir())
}
e.EncryptionKey = newKey
}
|
go
|
func (e *EncryptedRaftLogger) RotateEncryptionKey(newKey []byte) {
e.encoderMu.Lock()
defer e.encoderMu.Unlock()
if e.wal != nil { // if the wal exists, the snapshotter exists
// We don't want to have to close the WAL, because we can't open a new one.
// We need to know the previous snapshot, because when you open a WAL you
// have to read out all the entries from a particular snapshot, or you can't
// write. So just rotate the encoders out from under it. We already
// have a lock on writing to snapshots and WALs.
wrapped, ok := e.wal.(*wrappedWAL)
if !ok {
panic(fmt.Errorf("EncryptedRaftLogger's WAL is not a wrappedWAL"))
}
wrapped.encrypter, wrapped.decrypter = encryption.Defaults(newKey, e.FIPS)
e.snapshotter = NewSnapFactory(wrapped.encrypter, wrapped.decrypter).New(e.snapDir())
}
e.EncryptionKey = newKey
}
|
[
"func",
"(",
"e",
"*",
"EncryptedRaftLogger",
")",
"RotateEncryptionKey",
"(",
"newKey",
"[",
"]",
"byte",
")",
"{",
"e",
".",
"encoderMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"e",
".",
"encoderMu",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"e",
".",
"wal",
"!=",
"nil",
"{",
"// if the wal exists, the snapshotter exists",
"// We don't want to have to close the WAL, because we can't open a new one.",
"// We need to know the previous snapshot, because when you open a WAL you",
"// have to read out all the entries from a particular snapshot, or you can't",
"// write. So just rotate the encoders out from under it. We already",
"// have a lock on writing to snapshots and WALs.",
"wrapped",
",",
"ok",
":=",
"e",
".",
"wal",
".",
"(",
"*",
"wrappedWAL",
")",
"\n",
"if",
"!",
"ok",
"{",
"panic",
"(",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n\n",
"wrapped",
".",
"encrypter",
",",
"wrapped",
".",
"decrypter",
"=",
"encryption",
".",
"Defaults",
"(",
"newKey",
",",
"e",
".",
"FIPS",
")",
"\n\n",
"e",
".",
"snapshotter",
"=",
"NewSnapFactory",
"(",
"wrapped",
".",
"encrypter",
",",
"wrapped",
".",
"decrypter",
")",
".",
"New",
"(",
"e",
".",
"snapDir",
"(",
")",
")",
"\n",
"}",
"\n",
"e",
".",
"EncryptionKey",
"=",
"newKey",
"\n",
"}"
] |
// RotateEncryptionKey swaps out the encoders and decoders used by the wal and snapshotter
|
[
"RotateEncryptionKey",
"swaps",
"out",
"the",
"encoders",
"and",
"decoders",
"used",
"by",
"the",
"wal",
"and",
"snapshotter"
] |
59163bf75df38489d4a10392265d27156dc473c5
|
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/raft/storage/storage.go#L174-L194
|
train
|
docker/swarmkit
|
manager/state/raft/storage/storage.go
|
SaveSnapshot
|
func (e *EncryptedRaftLogger) SaveSnapshot(snapshot raftpb.Snapshot) error {
walsnap := walpb.Snapshot{
Index: snapshot.Metadata.Index,
Term: snapshot.Metadata.Term,
}
e.encoderMu.RLock()
if err := e.wal.SaveSnapshot(walsnap); err != nil {
e.encoderMu.RUnlock()
return err
}
snapshotter := e.snapshotter
e.encoderMu.RUnlock()
if err := snapshotter.SaveSnap(snapshot); err != nil {
return err
}
return e.wal.ReleaseLockTo(snapshot.Metadata.Index)
}
|
go
|
func (e *EncryptedRaftLogger) SaveSnapshot(snapshot raftpb.Snapshot) error {
walsnap := walpb.Snapshot{
Index: snapshot.Metadata.Index,
Term: snapshot.Metadata.Term,
}
e.encoderMu.RLock()
if err := e.wal.SaveSnapshot(walsnap); err != nil {
e.encoderMu.RUnlock()
return err
}
snapshotter := e.snapshotter
e.encoderMu.RUnlock()
if err := snapshotter.SaveSnap(snapshot); err != nil {
return err
}
return e.wal.ReleaseLockTo(snapshot.Metadata.Index)
}
|
[
"func",
"(",
"e",
"*",
"EncryptedRaftLogger",
")",
"SaveSnapshot",
"(",
"snapshot",
"raftpb",
".",
"Snapshot",
")",
"error",
"{",
"walsnap",
":=",
"walpb",
".",
"Snapshot",
"{",
"Index",
":",
"snapshot",
".",
"Metadata",
".",
"Index",
",",
"Term",
":",
"snapshot",
".",
"Metadata",
".",
"Term",
",",
"}",
"\n\n",
"e",
".",
"encoderMu",
".",
"RLock",
"(",
")",
"\n",
"if",
"err",
":=",
"e",
".",
"wal",
".",
"SaveSnapshot",
"(",
"walsnap",
")",
";",
"err",
"!=",
"nil",
"{",
"e",
".",
"encoderMu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"snapshotter",
":=",
"e",
".",
"snapshotter",
"\n",
"e",
".",
"encoderMu",
".",
"RUnlock",
"(",
")",
"\n\n",
"if",
"err",
":=",
"snapshotter",
".",
"SaveSnap",
"(",
"snapshot",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"e",
".",
"wal",
".",
"ReleaseLockTo",
"(",
"snapshot",
".",
"Metadata",
".",
"Index",
")",
"\n",
"}"
] |
// SaveSnapshot actually saves a given snapshot to both the WAL and the snapshot.
|
[
"SaveSnapshot",
"actually",
"saves",
"a",
"given",
"snapshot",
"to",
"both",
"the",
"WAL",
"and",
"the",
"snapshot",
"."
] |
59163bf75df38489d4a10392265d27156dc473c5
|
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/raft/storage/storage.go#L197-L217
|
train
|
docker/swarmkit
|
manager/state/raft/storage/storage.go
|
GC
|
func (e *EncryptedRaftLogger) GC(index uint64, term uint64, keepOldSnapshots uint64) error {
// Delete any older snapshots
curSnapshot := fmt.Sprintf("%016x-%016x%s", term, index, ".snap")
snapshots, err := ListSnapshots(e.snapDir())
if err != nil {
return err
}
// Ignore any snapshots that are older than the current snapshot.
// Delete the others. Rather than doing lexical comparisons, we look
// at what exists before/after the current snapshot in the slice.
// This means that if the current snapshot doesn't appear in the
// directory for some strange reason, we won't delete anything, which
// is the safe behavior.
curSnapshotIdx := -1
var (
removeErr error
oldestSnapshot string
)
for i, snapFile := range snapshots {
if curSnapshotIdx >= 0 && i > curSnapshotIdx {
if uint64(i-curSnapshotIdx) > keepOldSnapshots {
err := os.Remove(filepath.Join(e.snapDir(), snapFile))
if err != nil && removeErr == nil {
removeErr = err
}
continue
}
} else if snapFile == curSnapshot {
curSnapshotIdx = i
}
oldestSnapshot = snapFile
}
if removeErr != nil {
return removeErr
}
// Remove any WAL files that only contain data from before the oldest
// remaining snapshot.
if oldestSnapshot == "" {
return nil
}
// Parse index out of oldest snapshot's filename
var snapTerm, snapIndex uint64
_, err = fmt.Sscanf(oldestSnapshot, "%016x-%016x.snap", &snapTerm, &snapIndex)
if err != nil {
return errors.Wrapf(err, "malformed snapshot filename %s", oldestSnapshot)
}
wals, err := ListWALs(e.walDir())
if err != nil {
return err
}
found := false
deleteUntil := -1
for i, walName := range wals {
var walSeq, walIndex uint64
_, err = fmt.Sscanf(walName, "%016x-%016x.wal", &walSeq, &walIndex)
if err != nil {
return errors.Wrapf(err, "could not parse WAL name %s", walName)
}
if walIndex >= snapIndex {
deleteUntil = i - 1
found = true
break
}
}
// If all WAL files started with indices below the oldest snapshot's
// index, we can delete all but the newest WAL file.
if !found && len(wals) != 0 {
deleteUntil = len(wals) - 1
}
for i := 0; i < deleteUntil; i++ {
walPath := filepath.Join(e.walDir(), wals[i])
l, err := fileutil.TryLockFile(walPath, os.O_WRONLY, fileutil.PrivateFileMode)
if err != nil {
return errors.Wrapf(err, "could not lock old WAL file %s for removal", wals[i])
}
err = os.Remove(walPath)
l.Close()
if err != nil {
return errors.Wrapf(err, "error removing old WAL file %s", wals[i])
}
}
return nil
}
|
go
|
func (e *EncryptedRaftLogger) GC(index uint64, term uint64, keepOldSnapshots uint64) error {
// Delete any older snapshots
curSnapshot := fmt.Sprintf("%016x-%016x%s", term, index, ".snap")
snapshots, err := ListSnapshots(e.snapDir())
if err != nil {
return err
}
// Ignore any snapshots that are older than the current snapshot.
// Delete the others. Rather than doing lexical comparisons, we look
// at what exists before/after the current snapshot in the slice.
// This means that if the current snapshot doesn't appear in the
// directory for some strange reason, we won't delete anything, which
// is the safe behavior.
curSnapshotIdx := -1
var (
removeErr error
oldestSnapshot string
)
for i, snapFile := range snapshots {
if curSnapshotIdx >= 0 && i > curSnapshotIdx {
if uint64(i-curSnapshotIdx) > keepOldSnapshots {
err := os.Remove(filepath.Join(e.snapDir(), snapFile))
if err != nil && removeErr == nil {
removeErr = err
}
continue
}
} else if snapFile == curSnapshot {
curSnapshotIdx = i
}
oldestSnapshot = snapFile
}
if removeErr != nil {
return removeErr
}
// Remove any WAL files that only contain data from before the oldest
// remaining snapshot.
if oldestSnapshot == "" {
return nil
}
// Parse index out of oldest snapshot's filename
var snapTerm, snapIndex uint64
_, err = fmt.Sscanf(oldestSnapshot, "%016x-%016x.snap", &snapTerm, &snapIndex)
if err != nil {
return errors.Wrapf(err, "malformed snapshot filename %s", oldestSnapshot)
}
wals, err := ListWALs(e.walDir())
if err != nil {
return err
}
found := false
deleteUntil := -1
for i, walName := range wals {
var walSeq, walIndex uint64
_, err = fmt.Sscanf(walName, "%016x-%016x.wal", &walSeq, &walIndex)
if err != nil {
return errors.Wrapf(err, "could not parse WAL name %s", walName)
}
if walIndex >= snapIndex {
deleteUntil = i - 1
found = true
break
}
}
// If all WAL files started with indices below the oldest snapshot's
// index, we can delete all but the newest WAL file.
if !found && len(wals) != 0 {
deleteUntil = len(wals) - 1
}
for i := 0; i < deleteUntil; i++ {
walPath := filepath.Join(e.walDir(), wals[i])
l, err := fileutil.TryLockFile(walPath, os.O_WRONLY, fileutil.PrivateFileMode)
if err != nil {
return errors.Wrapf(err, "could not lock old WAL file %s for removal", wals[i])
}
err = os.Remove(walPath)
l.Close()
if err != nil {
return errors.Wrapf(err, "error removing old WAL file %s", wals[i])
}
}
return nil
}
|
[
"func",
"(",
"e",
"*",
"EncryptedRaftLogger",
")",
"GC",
"(",
"index",
"uint64",
",",
"term",
"uint64",
",",
"keepOldSnapshots",
"uint64",
")",
"error",
"{",
"// Delete any older snapshots",
"curSnapshot",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"term",
",",
"index",
",",
"\"",
"\"",
")",
"\n\n",
"snapshots",
",",
"err",
":=",
"ListSnapshots",
"(",
"e",
".",
"snapDir",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Ignore any snapshots that are older than the current snapshot.",
"// Delete the others. Rather than doing lexical comparisons, we look",
"// at what exists before/after the current snapshot in the slice.",
"// This means that if the current snapshot doesn't appear in the",
"// directory for some strange reason, we won't delete anything, which",
"// is the safe behavior.",
"curSnapshotIdx",
":=",
"-",
"1",
"\n",
"var",
"(",
"removeErr",
"error",
"\n",
"oldestSnapshot",
"string",
"\n",
")",
"\n\n",
"for",
"i",
",",
"snapFile",
":=",
"range",
"snapshots",
"{",
"if",
"curSnapshotIdx",
">=",
"0",
"&&",
"i",
">",
"curSnapshotIdx",
"{",
"if",
"uint64",
"(",
"i",
"-",
"curSnapshotIdx",
")",
">",
"keepOldSnapshots",
"{",
"err",
":=",
"os",
".",
"Remove",
"(",
"filepath",
".",
"Join",
"(",
"e",
".",
"snapDir",
"(",
")",
",",
"snapFile",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"removeErr",
"==",
"nil",
"{",
"removeErr",
"=",
"err",
"\n",
"}",
"\n",
"continue",
"\n",
"}",
"\n",
"}",
"else",
"if",
"snapFile",
"==",
"curSnapshot",
"{",
"curSnapshotIdx",
"=",
"i",
"\n",
"}",
"\n",
"oldestSnapshot",
"=",
"snapFile",
"\n",
"}",
"\n\n",
"if",
"removeErr",
"!=",
"nil",
"{",
"return",
"removeErr",
"\n",
"}",
"\n\n",
"// Remove any WAL files that only contain data from before the oldest",
"// remaining snapshot.",
"if",
"oldestSnapshot",
"==",
"\"",
"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Parse index out of oldest snapshot's filename",
"var",
"snapTerm",
",",
"snapIndex",
"uint64",
"\n",
"_",
",",
"err",
"=",
"fmt",
".",
"Sscanf",
"(",
"oldestSnapshot",
",",
"\"",
"\"",
",",
"&",
"snapTerm",
",",
"&",
"snapIndex",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"oldestSnapshot",
")",
"\n",
"}",
"\n\n",
"wals",
",",
"err",
":=",
"ListWALs",
"(",
"e",
".",
"walDir",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"found",
":=",
"false",
"\n",
"deleteUntil",
":=",
"-",
"1",
"\n\n",
"for",
"i",
",",
"walName",
":=",
"range",
"wals",
"{",
"var",
"walSeq",
",",
"walIndex",
"uint64",
"\n",
"_",
",",
"err",
"=",
"fmt",
".",
"Sscanf",
"(",
"walName",
",",
"\"",
"\"",
",",
"&",
"walSeq",
",",
"&",
"walIndex",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"walName",
")",
"\n",
"}",
"\n\n",
"if",
"walIndex",
">=",
"snapIndex",
"{",
"deleteUntil",
"=",
"i",
"-",
"1",
"\n",
"found",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"// If all WAL files started with indices below the oldest snapshot's",
"// index, we can delete all but the newest WAL file.",
"if",
"!",
"found",
"&&",
"len",
"(",
"wals",
")",
"!=",
"0",
"{",
"deleteUntil",
"=",
"len",
"(",
"wals",
")",
"-",
"1",
"\n",
"}",
"\n\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"deleteUntil",
";",
"i",
"++",
"{",
"walPath",
":=",
"filepath",
".",
"Join",
"(",
"e",
".",
"walDir",
"(",
")",
",",
"wals",
"[",
"i",
"]",
")",
"\n",
"l",
",",
"err",
":=",
"fileutil",
".",
"TryLockFile",
"(",
"walPath",
",",
"os",
".",
"O_WRONLY",
",",
"fileutil",
".",
"PrivateFileMode",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"wals",
"[",
"i",
"]",
")",
"\n",
"}",
"\n",
"err",
"=",
"os",
".",
"Remove",
"(",
"walPath",
")",
"\n",
"l",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"wals",
"[",
"i",
"]",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// GC garbage collects snapshots and wals older than the provided index and term
|
[
"GC",
"garbage",
"collects",
"snapshots",
"and",
"wals",
"older",
"than",
"the",
"provided",
"index",
"and",
"term"
] |
59163bf75df38489d4a10392265d27156dc473c5
|
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/raft/storage/storage.go#L220-L316
|
train
|
docker/swarmkit
|
manager/state/raft/storage/storage.go
|
SaveEntries
|
func (e *EncryptedRaftLogger) SaveEntries(st raftpb.HardState, entries []raftpb.Entry) error {
e.encoderMu.RLock()
defer e.encoderMu.RUnlock()
if e.wal == nil {
return fmt.Errorf("raft WAL has either been closed or has never been created")
}
return e.wal.Save(st, entries)
}
|
go
|
func (e *EncryptedRaftLogger) SaveEntries(st raftpb.HardState, entries []raftpb.Entry) error {
e.encoderMu.RLock()
defer e.encoderMu.RUnlock()
if e.wal == nil {
return fmt.Errorf("raft WAL has either been closed or has never been created")
}
return e.wal.Save(st, entries)
}
|
[
"func",
"(",
"e",
"*",
"EncryptedRaftLogger",
")",
"SaveEntries",
"(",
"st",
"raftpb",
".",
"HardState",
",",
"entries",
"[",
"]",
"raftpb",
".",
"Entry",
")",
"error",
"{",
"e",
".",
"encoderMu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"e",
".",
"encoderMu",
".",
"RUnlock",
"(",
")",
"\n\n",
"if",
"e",
".",
"wal",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"e",
".",
"wal",
".",
"Save",
"(",
"st",
",",
"entries",
")",
"\n",
"}"
] |
// SaveEntries saves only entries to disk
|
[
"SaveEntries",
"saves",
"only",
"entries",
"to",
"disk"
] |
59163bf75df38489d4a10392265d27156dc473c5
|
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/raft/storage/storage.go#L319-L327
|
train
|
docker/swarmkit
|
manager/state/raft/storage/storage.go
|
Close
|
func (e *EncryptedRaftLogger) Close(ctx context.Context) {
e.encoderMu.Lock()
defer e.encoderMu.Unlock()
if e.wal != nil {
if err := e.wal.Close(); err != nil {
log.G(ctx).WithError(err).Error("error closing raft WAL")
}
}
e.wal = nil
e.snapshotter = nil
}
|
go
|
func (e *EncryptedRaftLogger) Close(ctx context.Context) {
e.encoderMu.Lock()
defer e.encoderMu.Unlock()
if e.wal != nil {
if err := e.wal.Close(); err != nil {
log.G(ctx).WithError(err).Error("error closing raft WAL")
}
}
e.wal = nil
e.snapshotter = nil
}
|
[
"func",
"(",
"e",
"*",
"EncryptedRaftLogger",
")",
"Close",
"(",
"ctx",
"context",
".",
"Context",
")",
"{",
"e",
".",
"encoderMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"e",
".",
"encoderMu",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"e",
".",
"wal",
"!=",
"nil",
"{",
"if",
"err",
":=",
"e",
".",
"wal",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"G",
"(",
"ctx",
")",
".",
"WithError",
"(",
"err",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"e",
".",
"wal",
"=",
"nil",
"\n",
"e",
".",
"snapshotter",
"=",
"nil",
"\n",
"}"
] |
// Close closes the logger - it will have to be bootstrapped again to start writing
|
[
"Close",
"closes",
"the",
"logger",
"-",
"it",
"will",
"have",
"to",
"be",
"bootstrapped",
"again",
"to",
"start",
"writing"
] |
59163bf75df38489d4a10392265d27156dc473c5
|
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/raft/storage/storage.go#L330-L342
|
train
|
docker/swarmkit
|
manager/state/raft/storage/storage.go
|
Clear
|
func (e *EncryptedRaftLogger) Clear(ctx context.Context) error {
e.encoderMu.Lock()
defer e.encoderMu.Unlock()
if e.wal != nil {
if err := e.wal.Close(); err != nil {
log.G(ctx).WithError(err).Error("error closing raft WAL")
}
}
e.snapshotter = nil
os.RemoveAll(e.walDir())
os.RemoveAll(e.snapDir())
return nil
}
|
go
|
func (e *EncryptedRaftLogger) Clear(ctx context.Context) error {
e.encoderMu.Lock()
defer e.encoderMu.Unlock()
if e.wal != nil {
if err := e.wal.Close(); err != nil {
log.G(ctx).WithError(err).Error("error closing raft WAL")
}
}
e.snapshotter = nil
os.RemoveAll(e.walDir())
os.RemoveAll(e.snapDir())
return nil
}
|
[
"func",
"(",
"e",
"*",
"EncryptedRaftLogger",
")",
"Clear",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"e",
".",
"encoderMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"e",
".",
"encoderMu",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"e",
".",
"wal",
"!=",
"nil",
"{",
"if",
"err",
":=",
"e",
".",
"wal",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"G",
"(",
"ctx",
")",
".",
"WithError",
"(",
"err",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"e",
".",
"snapshotter",
"=",
"nil",
"\n\n",
"os",
".",
"RemoveAll",
"(",
"e",
".",
"walDir",
"(",
")",
")",
"\n",
"os",
".",
"RemoveAll",
"(",
"e",
".",
"snapDir",
"(",
")",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Clear closes the existing WAL and removes the WAL and snapshot.
|
[
"Clear",
"closes",
"the",
"existing",
"WAL",
"and",
"removes",
"the",
"WAL",
"and",
"snapshot",
"."
] |
59163bf75df38489d4a10392265d27156dc473c5
|
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/manager/state/raft/storage/storage.go#L345-L359
|
train
|
docker/swarmkit
|
agent/worker.go
|
Init
|
func (w *worker) Init(ctx context.Context) error {
w.mu.Lock()
defer w.mu.Unlock()
ctx = log.WithModule(ctx, "worker")
// TODO(stevvooe): Start task cleanup process.
// read the tasks from the database and start any task managers that may be needed.
return w.db.Update(func(tx *bolt.Tx) error {
return WalkTasks(tx, func(task *api.Task) error {
if !TaskAssigned(tx, task.ID) {
// NOTE(stevvooe): If tasks can survive worker restart, we need
// to startup the controller and ensure they are removed. For
// now, we can simply remove them from the database.
if err := DeleteTask(tx, task.ID); err != nil {
log.G(ctx).WithError(err).Errorf("error removing task %v", task.ID)
}
return nil
}
status, err := GetTaskStatus(tx, task.ID)
if err != nil {
log.G(ctx).WithError(err).Error("unable to read tasks status")
return nil
}
task.Status = *status // merges the status into the task, ensuring we start at the right point.
return w.startTask(ctx, tx, task)
})
})
}
|
go
|
func (w *worker) Init(ctx context.Context) error {
w.mu.Lock()
defer w.mu.Unlock()
ctx = log.WithModule(ctx, "worker")
// TODO(stevvooe): Start task cleanup process.
// read the tasks from the database and start any task managers that may be needed.
return w.db.Update(func(tx *bolt.Tx) error {
return WalkTasks(tx, func(task *api.Task) error {
if !TaskAssigned(tx, task.ID) {
// NOTE(stevvooe): If tasks can survive worker restart, we need
// to startup the controller and ensure they are removed. For
// now, we can simply remove them from the database.
if err := DeleteTask(tx, task.ID); err != nil {
log.G(ctx).WithError(err).Errorf("error removing task %v", task.ID)
}
return nil
}
status, err := GetTaskStatus(tx, task.ID)
if err != nil {
log.G(ctx).WithError(err).Error("unable to read tasks status")
return nil
}
task.Status = *status // merges the status into the task, ensuring we start at the right point.
return w.startTask(ctx, tx, task)
})
})
}
|
[
"func",
"(",
"w",
"*",
"worker",
")",
"Init",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"w",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"w",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"ctx",
"=",
"log",
".",
"WithModule",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n\n",
"// TODO(stevvooe): Start task cleanup process.",
"// read the tasks from the database and start any task managers that may be needed.",
"return",
"w",
".",
"db",
".",
"Update",
"(",
"func",
"(",
"tx",
"*",
"bolt",
".",
"Tx",
")",
"error",
"{",
"return",
"WalkTasks",
"(",
"tx",
",",
"func",
"(",
"task",
"*",
"api",
".",
"Task",
")",
"error",
"{",
"if",
"!",
"TaskAssigned",
"(",
"tx",
",",
"task",
".",
"ID",
")",
"{",
"// NOTE(stevvooe): If tasks can survive worker restart, we need",
"// to startup the controller and ensure they are removed. For",
"// now, we can simply remove them from the database.",
"if",
"err",
":=",
"DeleteTask",
"(",
"tx",
",",
"task",
".",
"ID",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"G",
"(",
"ctx",
")",
".",
"WithError",
"(",
"err",
")",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"task",
".",
"ID",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"status",
",",
"err",
":=",
"GetTaskStatus",
"(",
"tx",
",",
"task",
".",
"ID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"G",
"(",
"ctx",
")",
".",
"WithError",
"(",
"err",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"task",
".",
"Status",
"=",
"*",
"status",
"// merges the status into the task, ensuring we start at the right point.",
"\n",
"return",
"w",
".",
"startTask",
"(",
"ctx",
",",
"tx",
",",
"task",
")",
"\n",
"}",
")",
"\n",
"}",
")",
"\n",
"}"
] |
// Init prepares the worker for assignments.
|
[
"Init",
"prepares",
"the",
"worker",
"for",
"assignments",
"."
] |
59163bf75df38489d4a10392265d27156dc473c5
|
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/agent/worker.go#L84-L115
|
train
|
docker/swarmkit
|
agent/worker.go
|
Close
|
func (w *worker) Close() {
w.mu.Lock()
w.closed = true
w.mu.Unlock()
w.taskevents.Close()
}
|
go
|
func (w *worker) Close() {
w.mu.Lock()
w.closed = true
w.mu.Unlock()
w.taskevents.Close()
}
|
[
"func",
"(",
"w",
"*",
"worker",
")",
"Close",
"(",
")",
"{",
"w",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"w",
".",
"closed",
"=",
"true",
"\n",
"w",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"w",
".",
"taskevents",
".",
"Close",
"(",
")",
"\n",
"}"
] |
// Close performs worker cleanup when no longer needed.
|
[
"Close",
"performs",
"worker",
"cleanup",
"when",
"no",
"longer",
"needed",
"."
] |
59163bf75df38489d4a10392265d27156dc473c5
|
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/agent/worker.go#L118-L124
|
train
|
docker/swarmkit
|
agent/worker.go
|
Assign
|
func (w *worker) Assign(ctx context.Context, assignments []*api.AssignmentChange) error {
w.mu.Lock()
defer w.mu.Unlock()
if w.closed {
return ErrClosed
}
log.G(ctx).WithFields(logrus.Fields{
"len(assignments)": len(assignments),
}).Debug("(*worker).Assign")
// Need to update dependencies before tasks
err := reconcileSecrets(ctx, w, assignments, true)
if err != nil {
return err
}
err = reconcileConfigs(ctx, w, assignments, true)
if err != nil {
return err
}
return reconcileTaskState(ctx, w, assignments, true)
}
|
go
|
func (w *worker) Assign(ctx context.Context, assignments []*api.AssignmentChange) error {
w.mu.Lock()
defer w.mu.Unlock()
if w.closed {
return ErrClosed
}
log.G(ctx).WithFields(logrus.Fields{
"len(assignments)": len(assignments),
}).Debug("(*worker).Assign")
// Need to update dependencies before tasks
err := reconcileSecrets(ctx, w, assignments, true)
if err != nil {
return err
}
err = reconcileConfigs(ctx, w, assignments, true)
if err != nil {
return err
}
return reconcileTaskState(ctx, w, assignments, true)
}
|
[
"func",
"(",
"w",
"*",
"worker",
")",
"Assign",
"(",
"ctx",
"context",
".",
"Context",
",",
"assignments",
"[",
"]",
"*",
"api",
".",
"AssignmentChange",
")",
"error",
"{",
"w",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"w",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"w",
".",
"closed",
"{",
"return",
"ErrClosed",
"\n",
"}",
"\n\n",
"log",
".",
"G",
"(",
"ctx",
")",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"len",
"(",
"assignments",
")",
",",
"}",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n\n",
"// Need to update dependencies before tasks",
"err",
":=",
"reconcileSecrets",
"(",
"ctx",
",",
"w",
",",
"assignments",
",",
"true",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"err",
"=",
"reconcileConfigs",
"(",
"ctx",
",",
"w",
",",
"assignments",
",",
"true",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"reconcileTaskState",
"(",
"ctx",
",",
"w",
",",
"assignments",
",",
"true",
")",
"\n",
"}"
] |
// Assign assigns a full set of tasks, configs, and secrets to the worker.
// Any tasks not previously known will be started. Any tasks that are in the task set
// and already running will be updated, if possible. Any tasks currently running on
// the worker outside the task set will be terminated.
// Anything not in the set of assignments will be removed.
|
[
"Assign",
"assigns",
"a",
"full",
"set",
"of",
"tasks",
"configs",
"and",
"secrets",
"to",
"the",
"worker",
".",
"Any",
"tasks",
"not",
"previously",
"known",
"will",
"be",
"started",
".",
"Any",
"tasks",
"that",
"are",
"in",
"the",
"task",
"set",
"and",
"already",
"running",
"will",
"be",
"updated",
"if",
"possible",
".",
"Any",
"tasks",
"currently",
"running",
"on",
"the",
"worker",
"outside",
"the",
"task",
"set",
"will",
"be",
"terminated",
".",
"Anything",
"not",
"in",
"the",
"set",
"of",
"assignments",
"will",
"be",
"removed",
"."
] |
59163bf75df38489d4a10392265d27156dc473c5
|
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/agent/worker.go#L131-L156
|
train
|
docker/swarmkit
|
agent/worker.go
|
updateTaskStatus
|
func (w *worker) updateTaskStatus(ctx context.Context, tx *bolt.Tx, taskID string, status *api.TaskStatus) error {
if err := PutTaskStatus(tx, taskID, status); err != nil {
log.G(ctx).WithError(err).Error("failed writing status to disk")
return err
}
// broadcast the task status out.
for key := range w.listeners {
if err := key.StatusReporter.UpdateTaskStatus(ctx, taskID, status); err != nil {
log.G(ctx).WithError(err).Errorf("failed updating status for reporter %v", key.StatusReporter)
}
}
return nil
}
|
go
|
func (w *worker) updateTaskStatus(ctx context.Context, tx *bolt.Tx, taskID string, status *api.TaskStatus) error {
if err := PutTaskStatus(tx, taskID, status); err != nil {
log.G(ctx).WithError(err).Error("failed writing status to disk")
return err
}
// broadcast the task status out.
for key := range w.listeners {
if err := key.StatusReporter.UpdateTaskStatus(ctx, taskID, status); err != nil {
log.G(ctx).WithError(err).Errorf("failed updating status for reporter %v", key.StatusReporter)
}
}
return nil
}
|
[
"func",
"(",
"w",
"*",
"worker",
")",
"updateTaskStatus",
"(",
"ctx",
"context",
".",
"Context",
",",
"tx",
"*",
"bolt",
".",
"Tx",
",",
"taskID",
"string",
",",
"status",
"*",
"api",
".",
"TaskStatus",
")",
"error",
"{",
"if",
"err",
":=",
"PutTaskStatus",
"(",
"tx",
",",
"taskID",
",",
"status",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"G",
"(",
"ctx",
")",
".",
"WithError",
"(",
"err",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"// broadcast the task status out.",
"for",
"key",
":=",
"range",
"w",
".",
"listeners",
"{",
"if",
"err",
":=",
"key",
".",
"StatusReporter",
".",
"UpdateTaskStatus",
"(",
"ctx",
",",
"taskID",
",",
"status",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"G",
"(",
"ctx",
")",
".",
"WithError",
"(",
"err",
")",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"key",
".",
"StatusReporter",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// updateTaskStatus reports statuses to listeners, read lock must be held.
|
[
"updateTaskStatus",
"reports",
"statuses",
"to",
"listeners",
"read",
"lock",
"must",
"be",
"held",
"."
] |
59163bf75df38489d4a10392265d27156dc473c5
|
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/agent/worker.go#L501-L515
|
train
|
docker/swarmkit
|
agent/worker.go
|
Subscribe
|
func (w *worker) Subscribe(ctx context.Context, subscription *api.SubscriptionMessage) error {
log.G(ctx).Debugf("Received subscription %s (selector: %v)", subscription.ID, subscription.Selector)
publisher, cancel, err := w.publisherProvider.Publisher(ctx, subscription.ID)
if err != nil {
return err
}
// Send a close once we're done
defer cancel()
match := func(t *api.Task) bool {
// TODO(aluzzardi): Consider using maps to limit the iterations.
for _, tid := range subscription.Selector.TaskIDs {
if t.ID == tid {
return true
}
}
for _, sid := range subscription.Selector.ServiceIDs {
if t.ServiceID == sid {
return true
}
}
for _, nid := range subscription.Selector.NodeIDs {
if t.NodeID == nid {
return true
}
}
return false
}
wg := sync.WaitGroup{}
w.mu.Lock()
for _, tm := range w.taskManagers {
if match(tm.task) {
wg.Add(1)
go func(tm *taskManager) {
defer wg.Done()
tm.Logs(ctx, *subscription.Options, publisher)
}(tm)
}
}
w.mu.Unlock()
// If follow mode is disabled, wait for the current set of matched tasks
// to finish publishing logs, then close the subscription by returning.
if subscription.Options == nil || !subscription.Options.Follow {
waitCh := make(chan struct{})
go func() {
defer close(waitCh)
wg.Wait()
}()
select {
case <-ctx.Done():
return ctx.Err()
case <-waitCh:
return nil
}
}
// In follow mode, watch for new tasks. Don't close the subscription
// until it's cancelled.
ch, cancel := w.taskevents.Watch()
defer cancel()
for {
select {
case v := <-ch:
task := v.(*api.Task)
if match(task) {
w.mu.RLock()
tm, ok := w.taskManagers[task.ID]
w.mu.RUnlock()
if !ok {
continue
}
go tm.Logs(ctx, *subscription.Options, publisher)
}
case <-ctx.Done():
return ctx.Err()
}
}
}
|
go
|
func (w *worker) Subscribe(ctx context.Context, subscription *api.SubscriptionMessage) error {
log.G(ctx).Debugf("Received subscription %s (selector: %v)", subscription.ID, subscription.Selector)
publisher, cancel, err := w.publisherProvider.Publisher(ctx, subscription.ID)
if err != nil {
return err
}
// Send a close once we're done
defer cancel()
match := func(t *api.Task) bool {
// TODO(aluzzardi): Consider using maps to limit the iterations.
for _, tid := range subscription.Selector.TaskIDs {
if t.ID == tid {
return true
}
}
for _, sid := range subscription.Selector.ServiceIDs {
if t.ServiceID == sid {
return true
}
}
for _, nid := range subscription.Selector.NodeIDs {
if t.NodeID == nid {
return true
}
}
return false
}
wg := sync.WaitGroup{}
w.mu.Lock()
for _, tm := range w.taskManagers {
if match(tm.task) {
wg.Add(1)
go func(tm *taskManager) {
defer wg.Done()
tm.Logs(ctx, *subscription.Options, publisher)
}(tm)
}
}
w.mu.Unlock()
// If follow mode is disabled, wait for the current set of matched tasks
// to finish publishing logs, then close the subscription by returning.
if subscription.Options == nil || !subscription.Options.Follow {
waitCh := make(chan struct{})
go func() {
defer close(waitCh)
wg.Wait()
}()
select {
case <-ctx.Done():
return ctx.Err()
case <-waitCh:
return nil
}
}
// In follow mode, watch for new tasks. Don't close the subscription
// until it's cancelled.
ch, cancel := w.taskevents.Watch()
defer cancel()
for {
select {
case v := <-ch:
task := v.(*api.Task)
if match(task) {
w.mu.RLock()
tm, ok := w.taskManagers[task.ID]
w.mu.RUnlock()
if !ok {
continue
}
go tm.Logs(ctx, *subscription.Options, publisher)
}
case <-ctx.Done():
return ctx.Err()
}
}
}
|
[
"func",
"(",
"w",
"*",
"worker",
")",
"Subscribe",
"(",
"ctx",
"context",
".",
"Context",
",",
"subscription",
"*",
"api",
".",
"SubscriptionMessage",
")",
"error",
"{",
"log",
".",
"G",
"(",
"ctx",
")",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"subscription",
".",
"ID",
",",
"subscription",
".",
"Selector",
")",
"\n\n",
"publisher",
",",
"cancel",
",",
"err",
":=",
"w",
".",
"publisherProvider",
".",
"Publisher",
"(",
"ctx",
",",
"subscription",
".",
"ID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"// Send a close once we're done",
"defer",
"cancel",
"(",
")",
"\n\n",
"match",
":=",
"func",
"(",
"t",
"*",
"api",
".",
"Task",
")",
"bool",
"{",
"// TODO(aluzzardi): Consider using maps to limit the iterations.",
"for",
"_",
",",
"tid",
":=",
"range",
"subscription",
".",
"Selector",
".",
"TaskIDs",
"{",
"if",
"t",
".",
"ID",
"==",
"tid",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"sid",
":=",
"range",
"subscription",
".",
"Selector",
".",
"ServiceIDs",
"{",
"if",
"t",
".",
"ServiceID",
"==",
"sid",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"nid",
":=",
"range",
"subscription",
".",
"Selector",
".",
"NodeIDs",
"{",
"if",
"t",
".",
"NodeID",
"==",
"nid",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"false",
"\n",
"}",
"\n\n",
"wg",
":=",
"sync",
".",
"WaitGroup",
"{",
"}",
"\n",
"w",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"for",
"_",
",",
"tm",
":=",
"range",
"w",
".",
"taskManagers",
"{",
"if",
"match",
"(",
"tm",
".",
"task",
")",
"{",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
"tm",
"*",
"taskManager",
")",
"{",
"defer",
"wg",
".",
"Done",
"(",
")",
"\n",
"tm",
".",
"Logs",
"(",
"ctx",
",",
"*",
"subscription",
".",
"Options",
",",
"publisher",
")",
"\n",
"}",
"(",
"tm",
")",
"\n",
"}",
"\n",
"}",
"\n",
"w",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"// If follow mode is disabled, wait for the current set of matched tasks",
"// to finish publishing logs, then close the subscription by returning.",
"if",
"subscription",
".",
"Options",
"==",
"nil",
"||",
"!",
"subscription",
".",
"Options",
".",
"Follow",
"{",
"waitCh",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"defer",
"close",
"(",
"waitCh",
")",
"\n",
"wg",
".",
"Wait",
"(",
")",
"\n",
"}",
"(",
")",
"\n\n",
"select",
"{",
"case",
"<-",
"ctx",
".",
"Done",
"(",
")",
":",
"return",
"ctx",
".",
"Err",
"(",
")",
"\n",
"case",
"<-",
"waitCh",
":",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"// In follow mode, watch for new tasks. Don't close the subscription",
"// until it's cancelled.",
"ch",
",",
"cancel",
":=",
"w",
".",
"taskevents",
".",
"Watch",
"(",
")",
"\n",
"defer",
"cancel",
"(",
")",
"\n",
"for",
"{",
"select",
"{",
"case",
"v",
":=",
"<-",
"ch",
":",
"task",
":=",
"v",
".",
"(",
"*",
"api",
".",
"Task",
")",
"\n",
"if",
"match",
"(",
"task",
")",
"{",
"w",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"tm",
",",
"ok",
":=",
"w",
".",
"taskManagers",
"[",
"task",
".",
"ID",
"]",
"\n",
"w",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"!",
"ok",
"{",
"continue",
"\n",
"}",
"\n\n",
"go",
"tm",
".",
"Logs",
"(",
"ctx",
",",
"*",
"subscription",
".",
"Options",
",",
"publisher",
")",
"\n",
"}",
"\n",
"case",
"<-",
"ctx",
".",
"Done",
"(",
")",
":",
"return",
"ctx",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// Subscribe to log messages matching the subscription.
|
[
"Subscribe",
"to",
"log",
"messages",
"matching",
"the",
"subscription",
"."
] |
59163bf75df38489d4a10392265d27156dc473c5
|
https://github.com/docker/swarmkit/blob/59163bf75df38489d4a10392265d27156dc473c5/agent/worker.go#L518-L603
|
train
|
spf13/afero
|
ioutil.go
|
ReadDir
|
func (a Afero) ReadDir(dirname string) ([]os.FileInfo, error) {
return ReadDir(a.Fs, dirname)
}
|
go
|
func (a Afero) ReadDir(dirname string) ([]os.FileInfo, error) {
return ReadDir(a.Fs, dirname)
}
|
[
"func",
"(",
"a",
"Afero",
")",
"ReadDir",
"(",
"dirname",
"string",
")",
"(",
"[",
"]",
"os",
".",
"FileInfo",
",",
"error",
")",
"{",
"return",
"ReadDir",
"(",
"a",
".",
"Fs",
",",
"dirname",
")",
"\n",
"}"
] |
// ReadDir reads the directory named by dirname and returns
// a list of sorted directory entries.
|
[
"ReadDir",
"reads",
"the",
"directory",
"named",
"by",
"dirname",
"and",
"returns",
"a",
"list",
"of",
"sorted",
"directory",
"entries",
"."
] |
588a75ec4f32903aa5e39a2619ba6a4631e28424
|
https://github.com/spf13/afero/blob/588a75ec4f32903aa5e39a2619ba6a4631e28424/ioutil.go#L38-L40
|
train
|
spf13/afero
|
ioutil.go
|
ReadFile
|
func (a Afero) ReadFile(filename string) ([]byte, error) {
return ReadFile(a.Fs, filename)
}
|
go
|
func (a Afero) ReadFile(filename string) ([]byte, error) {
return ReadFile(a.Fs, filename)
}
|
[
"func",
"(",
"a",
"Afero",
")",
"ReadFile",
"(",
"filename",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"ReadFile",
"(",
"a",
".",
"Fs",
",",
"filename",
")",
"\n",
"}"
] |
// ReadFile reads the file named by filename and returns the contents.
// A successful call returns err == nil, not err == EOF. Because ReadFile
// reads the whole file, it does not treat an EOF from Read as an error
// to be reported.
|
[
"ReadFile",
"reads",
"the",
"file",
"named",
"by",
"filename",
"and",
"returns",
"the",
"contents",
".",
"A",
"successful",
"call",
"returns",
"err",
"==",
"nil",
"not",
"err",
"==",
"EOF",
".",
"Because",
"ReadFile",
"reads",
"the",
"whole",
"file",
"it",
"does",
"not",
"treat",
"an",
"EOF",
"from",
"Read",
"as",
"an",
"error",
"to",
"be",
"reported",
"."
] |
588a75ec4f32903aa5e39a2619ba6a4631e28424
|
https://github.com/spf13/afero/blob/588a75ec4f32903aa5e39a2619ba6a4631e28424/ioutil.go#L60-L62
|
train
|
spf13/afero
|
ioutil.go
|
readAll
|
func readAll(r io.Reader, capacity int64) (b []byte, err error) {
buf := bytes.NewBuffer(make([]byte, 0, capacity))
// If the buffer overflows, we will get bytes.ErrTooLarge.
// Return that as an error. Any other panic remains.
defer func() {
e := recover()
if e == nil {
return
}
if panicErr, ok := e.(error); ok && panicErr == bytes.ErrTooLarge {
err = panicErr
} else {
panic(e)
}
}()
_, err = buf.ReadFrom(r)
return buf.Bytes(), err
}
|
go
|
func readAll(r io.Reader, capacity int64) (b []byte, err error) {
buf := bytes.NewBuffer(make([]byte, 0, capacity))
// If the buffer overflows, we will get bytes.ErrTooLarge.
// Return that as an error. Any other panic remains.
defer func() {
e := recover()
if e == nil {
return
}
if panicErr, ok := e.(error); ok && panicErr == bytes.ErrTooLarge {
err = panicErr
} else {
panic(e)
}
}()
_, err = buf.ReadFrom(r)
return buf.Bytes(), err
}
|
[
"func",
"readAll",
"(",
"r",
"io",
".",
"Reader",
",",
"capacity",
"int64",
")",
"(",
"b",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"buf",
":=",
"bytes",
".",
"NewBuffer",
"(",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
",",
"capacity",
")",
")",
"\n",
"// If the buffer overflows, we will get bytes.ErrTooLarge.",
"// Return that as an error. Any other panic remains.",
"defer",
"func",
"(",
")",
"{",
"e",
":=",
"recover",
"(",
")",
"\n",
"if",
"e",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"if",
"panicErr",
",",
"ok",
":=",
"e",
".",
"(",
"error",
")",
";",
"ok",
"&&",
"panicErr",
"==",
"bytes",
".",
"ErrTooLarge",
"{",
"err",
"=",
"panicErr",
"\n",
"}",
"else",
"{",
"panic",
"(",
"e",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"_",
",",
"err",
"=",
"buf",
".",
"ReadFrom",
"(",
"r",
")",
"\n",
"return",
"buf",
".",
"Bytes",
"(",
")",
",",
"err",
"\n",
"}"
] |
// readAll reads from r until an error or EOF and returns the data it read
// from the internal buffer allocated with a specified capacity.
|
[
"readAll",
"reads",
"from",
"r",
"until",
"an",
"error",
"or",
"EOF",
"and",
"returns",
"the",
"data",
"it",
"read",
"from",
"the",
"internal",
"buffer",
"allocated",
"with",
"a",
"specified",
"capacity",
"."
] |
588a75ec4f32903aa5e39a2619ba6a4631e28424
|
https://github.com/spf13/afero/blob/588a75ec4f32903aa5e39a2619ba6a4631e28424/ioutil.go#L90-L107
|
train
|
spf13/afero
|
ioutil.go
|
WriteFile
|
func (a Afero) WriteFile(filename string, data []byte, perm os.FileMode) error {
return WriteFile(a.Fs, filename, data, perm)
}
|
go
|
func (a Afero) WriteFile(filename string, data []byte, perm os.FileMode) error {
return WriteFile(a.Fs, filename, data, perm)
}
|
[
"func",
"(",
"a",
"Afero",
")",
"WriteFile",
"(",
"filename",
"string",
",",
"data",
"[",
"]",
"byte",
",",
"perm",
"os",
".",
"FileMode",
")",
"error",
"{",
"return",
"WriteFile",
"(",
"a",
".",
"Fs",
",",
"filename",
",",
"data",
",",
"perm",
")",
"\n",
"}"
] |
// WriteFile writes data to a file named by filename.
// If the file does not exist, WriteFile creates it with permissions perm;
// otherwise WriteFile truncates it before writing.
|
[
"WriteFile",
"writes",
"data",
"to",
"a",
"file",
"named",
"by",
"filename",
".",
"If",
"the",
"file",
"does",
"not",
"exist",
"WriteFile",
"creates",
"it",
"with",
"permissions",
"perm",
";",
"otherwise",
"WriteFile",
"truncates",
"it",
"before",
"writing",
"."
] |
588a75ec4f32903aa5e39a2619ba6a4631e28424
|
https://github.com/spf13/afero/blob/588a75ec4f32903aa5e39a2619ba6a4631e28424/ioutil.go#L120-L122
|
train
|
spf13/afero
|
util.go
|
WriteReader
|
func (a Afero) WriteReader(path string, r io.Reader) (err error) {
return WriteReader(a.Fs, path, r)
}
|
go
|
func (a Afero) WriteReader(path string, r io.Reader) (err error) {
return WriteReader(a.Fs, path, r)
}
|
[
"func",
"(",
"a",
"Afero",
")",
"WriteReader",
"(",
"path",
"string",
",",
"r",
"io",
".",
"Reader",
")",
"(",
"err",
"error",
")",
"{",
"return",
"WriteReader",
"(",
"a",
".",
"Fs",
",",
"path",
",",
"r",
")",
"\n",
"}"
] |
// Takes a reader and a path and writes the content
|
[
"Takes",
"a",
"reader",
"and",
"a",
"path",
"and",
"writes",
"the",
"content"
] |
588a75ec4f32903aa5e39a2619ba6a4631e28424
|
https://github.com/spf13/afero/blob/588a75ec4f32903aa5e39a2619ba6a4631e28424/util.go#L36-L38
|
train
|
spf13/afero
|
util.go
|
GetTempDir
|
func GetTempDir(fs Fs, subPath string) string {
addSlash := func(p string) string {
if FilePathSeparator != p[len(p)-1:] {
p = p + FilePathSeparator
}
return p
}
dir := addSlash(os.TempDir())
if subPath != "" {
// preserve windows backslash :-(
if FilePathSeparator == "\\" {
subPath = strings.Replace(subPath, "\\", "____", -1)
}
dir = dir + UnicodeSanitize((subPath))
if FilePathSeparator == "\\" {
dir = strings.Replace(dir, "____", "\\", -1)
}
if exists, _ := Exists(fs, dir); exists {
return addSlash(dir)
}
err := fs.MkdirAll(dir, 0777)
if err != nil {
panic(err)
}
dir = addSlash(dir)
}
return dir
}
|
go
|
func GetTempDir(fs Fs, subPath string) string {
addSlash := func(p string) string {
if FilePathSeparator != p[len(p)-1:] {
p = p + FilePathSeparator
}
return p
}
dir := addSlash(os.TempDir())
if subPath != "" {
// preserve windows backslash :-(
if FilePathSeparator == "\\" {
subPath = strings.Replace(subPath, "\\", "____", -1)
}
dir = dir + UnicodeSanitize((subPath))
if FilePathSeparator == "\\" {
dir = strings.Replace(dir, "____", "\\", -1)
}
if exists, _ := Exists(fs, dir); exists {
return addSlash(dir)
}
err := fs.MkdirAll(dir, 0777)
if err != nil {
panic(err)
}
dir = addSlash(dir)
}
return dir
}
|
[
"func",
"GetTempDir",
"(",
"fs",
"Fs",
",",
"subPath",
"string",
")",
"string",
"{",
"addSlash",
":=",
"func",
"(",
"p",
"string",
")",
"string",
"{",
"if",
"FilePathSeparator",
"!=",
"p",
"[",
"len",
"(",
"p",
")",
"-",
"1",
":",
"]",
"{",
"p",
"=",
"p",
"+",
"FilePathSeparator",
"\n",
"}",
"\n",
"return",
"p",
"\n",
"}",
"\n",
"dir",
":=",
"addSlash",
"(",
"os",
".",
"TempDir",
"(",
")",
")",
"\n\n",
"if",
"subPath",
"!=",
"\"",
"\"",
"{",
"// preserve windows backslash :-(",
"if",
"FilePathSeparator",
"==",
"\"",
"\\\\",
"\"",
"{",
"subPath",
"=",
"strings",
".",
"Replace",
"(",
"subPath",
",",
"\"",
"\\\\",
"\"",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n",
"}",
"\n",
"dir",
"=",
"dir",
"+",
"UnicodeSanitize",
"(",
"(",
"subPath",
")",
")",
"\n",
"if",
"FilePathSeparator",
"==",
"\"",
"\\\\",
"\"",
"{",
"dir",
"=",
"strings",
".",
"Replace",
"(",
"dir",
",",
"\"",
"\"",
",",
"\"",
"\\\\",
"\"",
",",
"-",
"1",
")",
"\n",
"}",
"\n\n",
"if",
"exists",
",",
"_",
":=",
"Exists",
"(",
"fs",
",",
"dir",
")",
";",
"exists",
"{",
"return",
"addSlash",
"(",
"dir",
")",
"\n",
"}",
"\n\n",
"err",
":=",
"fs",
".",
"MkdirAll",
"(",
"dir",
",",
"0777",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"dir",
"=",
"addSlash",
"(",
"dir",
")",
"\n",
"}",
"\n",
"return",
"dir",
"\n",
"}"
] |
// GetTempDir returns the default temp directory with trailing slash
// if subPath is not empty then it will be created recursively with mode 777 rwx rwx rwx
|
[
"GetTempDir",
"returns",
"the",
"default",
"temp",
"directory",
"with",
"trailing",
"slash",
"if",
"subPath",
"is",
"not",
"empty",
"then",
"it",
"will",
"be",
"created",
"recursively",
"with",
"mode",
"777",
"rwx",
"rwx",
"rwx"
] |
588a75ec4f32903aa5e39a2619ba6a4631e28424
|
https://github.com/spf13/afero/blob/588a75ec4f32903aa5e39a2619ba6a4631e28424/util.go#L103-L133
|
train
|
spf13/afero
|
util.go
|
UnicodeSanitize
|
func UnicodeSanitize(s string) string {
source := []rune(s)
target := make([]rune, 0, len(source))
for _, r := range source {
if unicode.IsLetter(r) ||
unicode.IsDigit(r) ||
unicode.IsMark(r) ||
r == '.' ||
r == '/' ||
r == '\\' ||
r == '_' ||
r == '-' ||
r == '%' ||
r == ' ' ||
r == '#' {
target = append(target, r)
}
}
return string(target)
}
|
go
|
func UnicodeSanitize(s string) string {
source := []rune(s)
target := make([]rune, 0, len(source))
for _, r := range source {
if unicode.IsLetter(r) ||
unicode.IsDigit(r) ||
unicode.IsMark(r) ||
r == '.' ||
r == '/' ||
r == '\\' ||
r == '_' ||
r == '-' ||
r == '%' ||
r == ' ' ||
r == '#' {
target = append(target, r)
}
}
return string(target)
}
|
[
"func",
"UnicodeSanitize",
"(",
"s",
"string",
")",
"string",
"{",
"source",
":=",
"[",
"]",
"rune",
"(",
"s",
")",
"\n",
"target",
":=",
"make",
"(",
"[",
"]",
"rune",
",",
"0",
",",
"len",
"(",
"source",
")",
")",
"\n\n",
"for",
"_",
",",
"r",
":=",
"range",
"source",
"{",
"if",
"unicode",
".",
"IsLetter",
"(",
"r",
")",
"||",
"unicode",
".",
"IsDigit",
"(",
"r",
")",
"||",
"unicode",
".",
"IsMark",
"(",
"r",
")",
"||",
"r",
"==",
"'.'",
"||",
"r",
"==",
"'/'",
"||",
"r",
"==",
"'\\\\'",
"||",
"r",
"==",
"'_'",
"||",
"r",
"==",
"'-'",
"||",
"r",
"==",
"'%'",
"||",
"r",
"==",
"' '",
"||",
"r",
"==",
"'#'",
"{",
"target",
"=",
"append",
"(",
"target",
",",
"r",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"string",
"(",
"target",
")",
"\n",
"}"
] |
// Rewrite string to remove non-standard path characters
|
[
"Rewrite",
"string",
"to",
"remove",
"non",
"-",
"standard",
"path",
"characters"
] |
588a75ec4f32903aa5e39a2619ba6a4631e28424
|
https://github.com/spf13/afero/blob/588a75ec4f32903aa5e39a2619ba6a4631e28424/util.go#L136-L157
|
train
|
spf13/afero
|
util.go
|
NeuterAccents
|
func NeuterAccents(s string) string {
t := transform.Chain(norm.NFD, transform.RemoveFunc(isMn), norm.NFC)
result, _, _ := transform.String(t, string(s))
return result
}
|
go
|
func NeuterAccents(s string) string {
t := transform.Chain(norm.NFD, transform.RemoveFunc(isMn), norm.NFC)
result, _, _ := transform.String(t, string(s))
return result
}
|
[
"func",
"NeuterAccents",
"(",
"s",
"string",
")",
"string",
"{",
"t",
":=",
"transform",
".",
"Chain",
"(",
"norm",
".",
"NFD",
",",
"transform",
".",
"RemoveFunc",
"(",
"isMn",
")",
",",
"norm",
".",
"NFC",
")",
"\n",
"result",
",",
"_",
",",
"_",
":=",
"transform",
".",
"String",
"(",
"t",
",",
"string",
"(",
"s",
")",
")",
"\n\n",
"return",
"result",
"\n",
"}"
] |
// Transform characters with accents into plain forms.
|
[
"Transform",
"characters",
"with",
"accents",
"into",
"plain",
"forms",
"."
] |
588a75ec4f32903aa5e39a2619ba6a4631e28424
|
https://github.com/spf13/afero/blob/588a75ec4f32903aa5e39a2619ba6a4631e28424/util.go#L160-L165
|
train
|
spf13/afero
|
util.go
|
FileContainsBytes
|
func FileContainsBytes(fs Fs, filename string, subslice []byte) (bool, error) {
f, err := fs.Open(filename)
if err != nil {
return false, err
}
defer f.Close()
return readerContainsAny(f, subslice), nil
}
|
go
|
func FileContainsBytes(fs Fs, filename string, subslice []byte) (bool, error) {
f, err := fs.Open(filename)
if err != nil {
return false, err
}
defer f.Close()
return readerContainsAny(f, subslice), nil
}
|
[
"func",
"FileContainsBytes",
"(",
"fs",
"Fs",
",",
"filename",
"string",
",",
"subslice",
"[",
"]",
"byte",
")",
"(",
"bool",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"fs",
".",
"Open",
"(",
"filename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n\n",
"return",
"readerContainsAny",
"(",
"f",
",",
"subslice",
")",
",",
"nil",
"\n",
"}"
] |
// Check if a file contains a specified byte slice.
|
[
"Check",
"if",
"a",
"file",
"contains",
"a",
"specified",
"byte",
"slice",
"."
] |
588a75ec4f32903aa5e39a2619ba6a4631e28424
|
https://github.com/spf13/afero/blob/588a75ec4f32903aa5e39a2619ba6a4631e28424/util.go#L176-L184
|
train
|
spf13/afero
|
util.go
|
FileContainsAnyBytes
|
func FileContainsAnyBytes(fs Fs, filename string, subslices [][]byte) (bool, error) {
f, err := fs.Open(filename)
if err != nil {
return false, err
}
defer f.Close()
return readerContainsAny(f, subslices...), nil
}
|
go
|
func FileContainsAnyBytes(fs Fs, filename string, subslices [][]byte) (bool, error) {
f, err := fs.Open(filename)
if err != nil {
return false, err
}
defer f.Close()
return readerContainsAny(f, subslices...), nil
}
|
[
"func",
"FileContainsAnyBytes",
"(",
"fs",
"Fs",
",",
"filename",
"string",
",",
"subslices",
"[",
"]",
"[",
"]",
"byte",
")",
"(",
"bool",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"fs",
".",
"Open",
"(",
"filename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n\n",
"return",
"readerContainsAny",
"(",
"f",
",",
"subslices",
"...",
")",
",",
"nil",
"\n",
"}"
] |
// Check if a file contains any of the specified byte slices.
|
[
"Check",
"if",
"a",
"file",
"contains",
"any",
"of",
"the",
"specified",
"byte",
"slices",
"."
] |
588a75ec4f32903aa5e39a2619ba6a4631e28424
|
https://github.com/spf13/afero/blob/588a75ec4f32903aa5e39a2619ba6a4631e28424/util.go#L191-L199
|
train
|
spf13/afero
|
util.go
|
readerContainsAny
|
func readerContainsAny(r io.Reader, subslices ...[]byte) bool {
if r == nil || len(subslices) == 0 {
return false
}
largestSlice := 0
for _, sl := range subslices {
if len(sl) > largestSlice {
largestSlice = len(sl)
}
}
if largestSlice == 0 {
return false
}
bufflen := largestSlice * 4
halflen := bufflen / 2
buff := make([]byte, bufflen)
var err error
var n, i int
for {
i++
if i == 1 {
n, err = io.ReadAtLeast(r, buff[:halflen], halflen)
} else {
if i != 2 {
// shift left to catch overlapping matches
copy(buff[:], buff[halflen:])
}
n, err = io.ReadAtLeast(r, buff[halflen:], halflen)
}
if n > 0 {
for _, sl := range subslices {
if bytes.Contains(buff, sl) {
return true
}
}
}
if err != nil {
break
}
}
return false
}
|
go
|
func readerContainsAny(r io.Reader, subslices ...[]byte) bool {
if r == nil || len(subslices) == 0 {
return false
}
largestSlice := 0
for _, sl := range subslices {
if len(sl) > largestSlice {
largestSlice = len(sl)
}
}
if largestSlice == 0 {
return false
}
bufflen := largestSlice * 4
halflen := bufflen / 2
buff := make([]byte, bufflen)
var err error
var n, i int
for {
i++
if i == 1 {
n, err = io.ReadAtLeast(r, buff[:halflen], halflen)
} else {
if i != 2 {
// shift left to catch overlapping matches
copy(buff[:], buff[halflen:])
}
n, err = io.ReadAtLeast(r, buff[halflen:], halflen)
}
if n > 0 {
for _, sl := range subslices {
if bytes.Contains(buff, sl) {
return true
}
}
}
if err != nil {
break
}
}
return false
}
|
[
"func",
"readerContainsAny",
"(",
"r",
"io",
".",
"Reader",
",",
"subslices",
"...",
"[",
"]",
"byte",
")",
"bool",
"{",
"if",
"r",
"==",
"nil",
"||",
"len",
"(",
"subslices",
")",
"==",
"0",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"largestSlice",
":=",
"0",
"\n\n",
"for",
"_",
",",
"sl",
":=",
"range",
"subslices",
"{",
"if",
"len",
"(",
"sl",
")",
">",
"largestSlice",
"{",
"largestSlice",
"=",
"len",
"(",
"sl",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"largestSlice",
"==",
"0",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"bufflen",
":=",
"largestSlice",
"*",
"4",
"\n",
"halflen",
":=",
"bufflen",
"/",
"2",
"\n",
"buff",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"bufflen",
")",
"\n",
"var",
"err",
"error",
"\n",
"var",
"n",
",",
"i",
"int",
"\n\n",
"for",
"{",
"i",
"++",
"\n",
"if",
"i",
"==",
"1",
"{",
"n",
",",
"err",
"=",
"io",
".",
"ReadAtLeast",
"(",
"r",
",",
"buff",
"[",
":",
"halflen",
"]",
",",
"halflen",
")",
"\n",
"}",
"else",
"{",
"if",
"i",
"!=",
"2",
"{",
"// shift left to catch overlapping matches",
"copy",
"(",
"buff",
"[",
":",
"]",
",",
"buff",
"[",
"halflen",
":",
"]",
")",
"\n",
"}",
"\n",
"n",
",",
"err",
"=",
"io",
".",
"ReadAtLeast",
"(",
"r",
",",
"buff",
"[",
"halflen",
":",
"]",
",",
"halflen",
")",
"\n",
"}",
"\n\n",
"if",
"n",
">",
"0",
"{",
"for",
"_",
",",
"sl",
":=",
"range",
"subslices",
"{",
"if",
"bytes",
".",
"Contains",
"(",
"buff",
",",
"sl",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// readerContains reports whether any of the subslices is within r.
|
[
"readerContains",
"reports",
"whether",
"any",
"of",
"the",
"subslices",
"is",
"within",
"r",
"."
] |
588a75ec4f32903aa5e39a2619ba6a4631e28424
|
https://github.com/spf13/afero/blob/588a75ec4f32903aa5e39a2619ba6a4631e28424/util.go#L202-L251
|
train
|
spf13/afero
|
util.go
|
IsEmpty
|
func IsEmpty(fs Fs, path string) (bool, error) {
if b, _ := Exists(fs, path); !b {
return false, fmt.Errorf("%q path does not exist", path)
}
fi, err := fs.Stat(path)
if err != nil {
return false, err
}
if fi.IsDir() {
f, err := fs.Open(path)
if err != nil {
return false, err
}
defer f.Close()
list, err := f.Readdir(-1)
return len(list) == 0, nil
}
return fi.Size() == 0, nil
}
|
go
|
func IsEmpty(fs Fs, path string) (bool, error) {
if b, _ := Exists(fs, path); !b {
return false, fmt.Errorf("%q path does not exist", path)
}
fi, err := fs.Stat(path)
if err != nil {
return false, err
}
if fi.IsDir() {
f, err := fs.Open(path)
if err != nil {
return false, err
}
defer f.Close()
list, err := f.Readdir(-1)
return len(list) == 0, nil
}
return fi.Size() == 0, nil
}
|
[
"func",
"IsEmpty",
"(",
"fs",
"Fs",
",",
"path",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"if",
"b",
",",
"_",
":=",
"Exists",
"(",
"fs",
",",
"path",
")",
";",
"!",
"b",
"{",
"return",
"false",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"path",
")",
"\n",
"}",
"\n",
"fi",
",",
"err",
":=",
"fs",
".",
"Stat",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"if",
"fi",
".",
"IsDir",
"(",
")",
"{",
"f",
",",
"err",
":=",
"fs",
".",
"Open",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n",
"list",
",",
"err",
":=",
"f",
".",
"Readdir",
"(",
"-",
"1",
")",
"\n",
"return",
"len",
"(",
"list",
")",
"==",
"0",
",",
"nil",
"\n",
"}",
"\n",
"return",
"fi",
".",
"Size",
"(",
")",
"==",
"0",
",",
"nil",
"\n",
"}"
] |
// IsEmpty checks if a given file or directory is empty.
|
[
"IsEmpty",
"checks",
"if",
"a",
"given",
"file",
"or",
"directory",
"is",
"empty",
"."
] |
588a75ec4f32903aa5e39a2619ba6a4631e28424
|
https://github.com/spf13/afero/blob/588a75ec4f32903aa5e39a2619ba6a4631e28424/util.go#L287-L305
|
train
|
spf13/afero
|
mem/file.go
|
Name
|
func (s *FileInfo) Name() string {
s.Lock()
_, name := filepath.Split(s.name)
s.Unlock()
return name
}
|
go
|
func (s *FileInfo) Name() string {
s.Lock()
_, name := filepath.Split(s.name)
s.Unlock()
return name
}
|
[
"func",
"(",
"s",
"*",
"FileInfo",
")",
"Name",
"(",
")",
"string",
"{",
"s",
".",
"Lock",
"(",
")",
"\n",
"_",
",",
"name",
":=",
"filepath",
".",
"Split",
"(",
"s",
".",
"name",
")",
"\n",
"s",
".",
"Unlock",
"(",
")",
"\n",
"return",
"name",
"\n",
"}"
] |
// Implements os.FileInfo
|
[
"Implements",
"os",
".",
"FileInfo"
] |
588a75ec4f32903aa5e39a2619ba6a4631e28424
|
https://github.com/spf13/afero/blob/588a75ec4f32903aa5e39a2619ba6a4631e28424/mem/file.go#L279-L284
|
train
|
spf13/afero
|
memmap.go
|
normalizePath
|
func normalizePath(path string) string {
path = filepath.Clean(path)
switch path {
case ".":
return FilePathSeparator
case "..":
return FilePathSeparator
default:
return path
}
}
|
go
|
func normalizePath(path string) string {
path = filepath.Clean(path)
switch path {
case ".":
return FilePathSeparator
case "..":
return FilePathSeparator
default:
return path
}
}
|
[
"func",
"normalizePath",
"(",
"path",
"string",
")",
"string",
"{",
"path",
"=",
"filepath",
".",
"Clean",
"(",
"path",
")",
"\n\n",
"switch",
"path",
"{",
"case",
"\"",
"\"",
":",
"return",
"FilePathSeparator",
"\n",
"case",
"\"",
"\"",
":",
"return",
"FilePathSeparator",
"\n",
"default",
":",
"return",
"path",
"\n",
"}",
"\n",
"}"
] |
// Handle some relative paths
|
[
"Handle",
"some",
"relative",
"paths"
] |
588a75ec4f32903aa5e39a2619ba6a4631e28424
|
https://github.com/spf13/afero/blob/588a75ec4f32903aa5e39a2619ba6a4631e28424/memmap.go#L161-L172
|
train
|
spf13/afero
|
basepath.go
|
RealPath
|
func (b *BasePathFs) RealPath(name string) (path string, err error) {
if err := validateBasePathName(name); err != nil {
return name, err
}
bpath := filepath.Clean(b.path)
path = filepath.Clean(filepath.Join(bpath, name))
if !strings.HasPrefix(path, bpath) {
return name, os.ErrNotExist
}
return path, nil
}
|
go
|
func (b *BasePathFs) RealPath(name string) (path string, err error) {
if err := validateBasePathName(name); err != nil {
return name, err
}
bpath := filepath.Clean(b.path)
path = filepath.Clean(filepath.Join(bpath, name))
if !strings.HasPrefix(path, bpath) {
return name, os.ErrNotExist
}
return path, nil
}
|
[
"func",
"(",
"b",
"*",
"BasePathFs",
")",
"RealPath",
"(",
"name",
"string",
")",
"(",
"path",
"string",
",",
"err",
"error",
")",
"{",
"if",
"err",
":=",
"validateBasePathName",
"(",
"name",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"name",
",",
"err",
"\n",
"}",
"\n\n",
"bpath",
":=",
"filepath",
".",
"Clean",
"(",
"b",
".",
"path",
")",
"\n",
"path",
"=",
"filepath",
".",
"Clean",
"(",
"filepath",
".",
"Join",
"(",
"bpath",
",",
"name",
")",
")",
"\n",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"path",
",",
"bpath",
")",
"{",
"return",
"name",
",",
"os",
".",
"ErrNotExist",
"\n",
"}",
"\n\n",
"return",
"path",
",",
"nil",
"\n",
"}"
] |
// on a file outside the base path it returns the given file name and an error,
// else the given file with the base path prepended
|
[
"on",
"a",
"file",
"outside",
"the",
"base",
"path",
"it",
"returns",
"the",
"given",
"file",
"name",
"and",
"an",
"error",
"else",
"the",
"given",
"file",
"with",
"the",
"base",
"path",
"prepended"
] |
588a75ec4f32903aa5e39a2619ba6a4631e28424
|
https://github.com/spf13/afero/blob/588a75ec4f32903aa5e39a2619ba6a4631e28424/basepath.go#L42-L54
|
train
|
spf13/afero
|
unionFile.go
|
Readdir
|
func (f *UnionFile) Readdir(c int) (ofi []os.FileInfo, err error) {
var merge DirsMerger = f.Merger
if merge == nil {
merge = defaultUnionMergeDirsFn
}
if f.off == 0 {
var lfi []os.FileInfo
if f.Layer != nil {
lfi, err = f.Layer.Readdir(-1)
if err != nil {
return nil, err
}
}
var bfi []os.FileInfo
if f.Base != nil {
bfi, err = f.Base.Readdir(-1)
if err != nil {
return nil, err
}
}
merged, err := merge(lfi, bfi)
if err != nil {
return nil, err
}
f.files = append(f.files, merged...)
}
if c <= 0 && len(f.files) == 0 {
return f.files, nil
}
if f.off >= len(f.files) {
return nil, io.EOF
}
if c <= 0 {
return f.files[f.off:], nil
}
if c > len(f.files) {
c = len(f.files)
}
defer func() { f.off += c }()
return f.files[f.off:c], nil
}
|
go
|
func (f *UnionFile) Readdir(c int) (ofi []os.FileInfo, err error) {
var merge DirsMerger = f.Merger
if merge == nil {
merge = defaultUnionMergeDirsFn
}
if f.off == 0 {
var lfi []os.FileInfo
if f.Layer != nil {
lfi, err = f.Layer.Readdir(-1)
if err != nil {
return nil, err
}
}
var bfi []os.FileInfo
if f.Base != nil {
bfi, err = f.Base.Readdir(-1)
if err != nil {
return nil, err
}
}
merged, err := merge(lfi, bfi)
if err != nil {
return nil, err
}
f.files = append(f.files, merged...)
}
if c <= 0 && len(f.files) == 0 {
return f.files, nil
}
if f.off >= len(f.files) {
return nil, io.EOF
}
if c <= 0 {
return f.files[f.off:], nil
}
if c > len(f.files) {
c = len(f.files)
}
defer func() { f.off += c }()
return f.files[f.off:c], nil
}
|
[
"func",
"(",
"f",
"*",
"UnionFile",
")",
"Readdir",
"(",
"c",
"int",
")",
"(",
"ofi",
"[",
"]",
"os",
".",
"FileInfo",
",",
"err",
"error",
")",
"{",
"var",
"merge",
"DirsMerger",
"=",
"f",
".",
"Merger",
"\n",
"if",
"merge",
"==",
"nil",
"{",
"merge",
"=",
"defaultUnionMergeDirsFn",
"\n",
"}",
"\n\n",
"if",
"f",
".",
"off",
"==",
"0",
"{",
"var",
"lfi",
"[",
"]",
"os",
".",
"FileInfo",
"\n",
"if",
"f",
".",
"Layer",
"!=",
"nil",
"{",
"lfi",
",",
"err",
"=",
"f",
".",
"Layer",
".",
"Readdir",
"(",
"-",
"1",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"var",
"bfi",
"[",
"]",
"os",
".",
"FileInfo",
"\n",
"if",
"f",
".",
"Base",
"!=",
"nil",
"{",
"bfi",
",",
"err",
"=",
"f",
".",
"Base",
".",
"Readdir",
"(",
"-",
"1",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"}",
"\n",
"merged",
",",
"err",
":=",
"merge",
"(",
"lfi",
",",
"bfi",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"f",
".",
"files",
"=",
"append",
"(",
"f",
".",
"files",
",",
"merged",
"...",
")",
"\n",
"}",
"\n\n",
"if",
"c",
"<=",
"0",
"&&",
"len",
"(",
"f",
".",
"files",
")",
"==",
"0",
"{",
"return",
"f",
".",
"files",
",",
"nil",
"\n",
"}",
"\n\n",
"if",
"f",
".",
"off",
">=",
"len",
"(",
"f",
".",
"files",
")",
"{",
"return",
"nil",
",",
"io",
".",
"EOF",
"\n",
"}",
"\n\n",
"if",
"c",
"<=",
"0",
"{",
"return",
"f",
".",
"files",
"[",
"f",
".",
"off",
":",
"]",
",",
"nil",
"\n",
"}",
"\n\n",
"if",
"c",
">",
"len",
"(",
"f",
".",
"files",
")",
"{",
"c",
"=",
"len",
"(",
"f",
".",
"files",
")",
"\n",
"}",
"\n\n",
"defer",
"func",
"(",
")",
"{",
"f",
".",
"off",
"+=",
"c",
"}",
"(",
")",
"\n",
"return",
"f",
".",
"files",
"[",
"f",
".",
"off",
":",
"c",
"]",
",",
"nil",
"\n",
"}"
] |
// Readdir will weave the two directories together and
// return a single view of the overlayed directories.
// At the end of the directory view, the error is io.EOF if c > 0.
|
[
"Readdir",
"will",
"weave",
"the",
"two",
"directories",
"together",
"and",
"return",
"a",
"single",
"view",
"of",
"the",
"overlayed",
"directories",
".",
"At",
"the",
"end",
"of",
"the",
"directory",
"view",
"the",
"error",
"is",
"io",
".",
"EOF",
"if",
"c",
">",
"0",
"."
] |
588a75ec4f32903aa5e39a2619ba6a4631e28424
|
https://github.com/spf13/afero/blob/588a75ec4f32903aa5e39a2619ba6a4631e28424/unionFile.go#L160-L208
|
train
|
spf13/afero
|
copyOnWriteFs.go
|
isBaseFile
|
func (u *CopyOnWriteFs) isBaseFile(name string) (bool, error) {
if _, err := u.layer.Stat(name); err == nil {
return false, nil
}
_, err := u.base.Stat(name)
if err != nil {
if oerr, ok := err.(*os.PathError); ok {
if oerr.Err == os.ErrNotExist || oerr.Err == syscall.ENOENT || oerr.Err == syscall.ENOTDIR {
return false, nil
}
}
if err == syscall.ENOENT {
return false, nil
}
}
return true, err
}
|
go
|
func (u *CopyOnWriteFs) isBaseFile(name string) (bool, error) {
if _, err := u.layer.Stat(name); err == nil {
return false, nil
}
_, err := u.base.Stat(name)
if err != nil {
if oerr, ok := err.(*os.PathError); ok {
if oerr.Err == os.ErrNotExist || oerr.Err == syscall.ENOENT || oerr.Err == syscall.ENOTDIR {
return false, nil
}
}
if err == syscall.ENOENT {
return false, nil
}
}
return true, err
}
|
[
"func",
"(",
"u",
"*",
"CopyOnWriteFs",
")",
"isBaseFile",
"(",
"name",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"if",
"_",
",",
"err",
":=",
"u",
".",
"layer",
".",
"Stat",
"(",
"name",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"u",
".",
"base",
".",
"Stat",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"oerr",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"os",
".",
"PathError",
")",
";",
"ok",
"{",
"if",
"oerr",
".",
"Err",
"==",
"os",
".",
"ErrNotExist",
"||",
"oerr",
".",
"Err",
"==",
"syscall",
".",
"ENOENT",
"||",
"oerr",
".",
"Err",
"==",
"syscall",
".",
"ENOTDIR",
"{",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"err",
"==",
"syscall",
".",
"ENOENT",
"{",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
",",
"err",
"\n",
"}"
] |
// Returns true if the file is not in the overlay
|
[
"Returns",
"true",
"if",
"the",
"file",
"is",
"not",
"in",
"the",
"overlay"
] |
588a75ec4f32903aa5e39a2619ba6a4631e28424
|
https://github.com/spf13/afero/blob/588a75ec4f32903aa5e39a2619ba6a4631e28424/copyOnWriteFs.go#L30-L46
|
train
|
spf13/afero
|
copyOnWriteFs.go
|
Rename
|
func (u *CopyOnWriteFs) Rename(oldname, newname string) error {
b, err := u.isBaseFile(oldname)
if err != nil {
return err
}
if b {
return syscall.EPERM
}
return u.layer.Rename(oldname, newname)
}
|
go
|
func (u *CopyOnWriteFs) Rename(oldname, newname string) error {
b, err := u.isBaseFile(oldname)
if err != nil {
return err
}
if b {
return syscall.EPERM
}
return u.layer.Rename(oldname, newname)
}
|
[
"func",
"(",
"u",
"*",
"CopyOnWriteFs",
")",
"Rename",
"(",
"oldname",
",",
"newname",
"string",
")",
"error",
"{",
"b",
",",
"err",
":=",
"u",
".",
"isBaseFile",
"(",
"oldname",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"b",
"{",
"return",
"syscall",
".",
"EPERM",
"\n",
"}",
"\n",
"return",
"u",
".",
"layer",
".",
"Rename",
"(",
"oldname",
",",
"newname",
")",
"\n",
"}"
] |
// Renaming files present only in the base layer is not permitted
|
[
"Renaming",
"files",
"present",
"only",
"in",
"the",
"base",
"layer",
"is",
"not",
"permitted"
] |
588a75ec4f32903aa5e39a2619ba6a4631e28424
|
https://github.com/spf13/afero/blob/588a75ec4f32903aa5e39a2619ba6a4631e28424/copyOnWriteFs.go#L131-L140
|
train
|
spf13/afero
|
copyOnWriteFs.go
|
Remove
|
func (u *CopyOnWriteFs) Remove(name string) error {
err := u.layer.Remove(name)
switch err {
case syscall.ENOENT:
_, err = u.base.Stat(name)
if err == nil {
return syscall.EPERM
}
return syscall.ENOENT
default:
return err
}
}
|
go
|
func (u *CopyOnWriteFs) Remove(name string) error {
err := u.layer.Remove(name)
switch err {
case syscall.ENOENT:
_, err = u.base.Stat(name)
if err == nil {
return syscall.EPERM
}
return syscall.ENOENT
default:
return err
}
}
|
[
"func",
"(",
"u",
"*",
"CopyOnWriteFs",
")",
"Remove",
"(",
"name",
"string",
")",
"error",
"{",
"err",
":=",
"u",
".",
"layer",
".",
"Remove",
"(",
"name",
")",
"\n",
"switch",
"err",
"{",
"case",
"syscall",
".",
"ENOENT",
":",
"_",
",",
"err",
"=",
"u",
".",
"base",
".",
"Stat",
"(",
"name",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"syscall",
".",
"EPERM",
"\n",
"}",
"\n",
"return",
"syscall",
".",
"ENOENT",
"\n",
"default",
":",
"return",
"err",
"\n",
"}",
"\n",
"}"
] |
// Removing files present only in the base layer is not permitted. If
// a file is present in the base layer and the overlay, only the overlay
// will be removed.
|
[
"Removing",
"files",
"present",
"only",
"in",
"the",
"base",
"layer",
"is",
"not",
"permitted",
".",
"If",
"a",
"file",
"is",
"present",
"in",
"the",
"base",
"layer",
"and",
"the",
"overlay",
"only",
"the",
"overlay",
"will",
"be",
"removed",
"."
] |
588a75ec4f32903aa5e39a2619ba6a4631e28424
|
https://github.com/spf13/afero/blob/588a75ec4f32903aa5e39a2619ba6a4631e28424/copyOnWriteFs.go#L145-L157
|
train
|
spf13/afero
|
path.go
|
lstatIfPossible
|
func lstatIfPossible(fs Fs, path string) (os.FileInfo, error) {
if lfs, ok := fs.(Lstater); ok {
fi, _, err := lfs.LstatIfPossible(path)
return fi, err
}
return fs.Stat(path)
}
|
go
|
func lstatIfPossible(fs Fs, path string) (os.FileInfo, error) {
if lfs, ok := fs.(Lstater); ok {
fi, _, err := lfs.LstatIfPossible(path)
return fi, err
}
return fs.Stat(path)
}
|
[
"func",
"lstatIfPossible",
"(",
"fs",
"Fs",
",",
"path",
"string",
")",
"(",
"os",
".",
"FileInfo",
",",
"error",
")",
"{",
"if",
"lfs",
",",
"ok",
":=",
"fs",
".",
"(",
"Lstater",
")",
";",
"ok",
"{",
"fi",
",",
"_",
",",
"err",
":=",
"lfs",
".",
"LstatIfPossible",
"(",
"path",
")",
"\n",
"return",
"fi",
",",
"err",
"\n",
"}",
"\n",
"return",
"fs",
".",
"Stat",
"(",
"path",
")",
"\n",
"}"
] |
// if the filesystem supports it, use Lstat, else use fs.Stat
|
[
"if",
"the",
"filesystem",
"supports",
"it",
"use",
"Lstat",
"else",
"use",
"fs",
".",
"Stat"
] |
588a75ec4f32903aa5e39a2619ba6a4631e28424
|
https://github.com/spf13/afero/blob/588a75ec4f32903aa5e39a2619ba6a4631e28424/path.go#L81-L87
|
train
|
requilence/integram
|
types.go
|
toBson
|
func (o *OAuthProvider) toBson() bson.M {
return bson.M{"baseurl": struct {
Scheme string
Host string
Path string
}{o.BaseURL.Scheme, o.BaseURL.Host, o.BaseURL.Path},
"id": o.ID,
"secret": o.Secret,
"service": o.Service}
}
|
go
|
func (o *OAuthProvider) toBson() bson.M {
return bson.M{"baseurl": struct {
Scheme string
Host string
Path string
}{o.BaseURL.Scheme, o.BaseURL.Host, o.BaseURL.Path},
"id": o.ID,
"secret": o.Secret,
"service": o.Service}
}
|
[
"func",
"(",
"o",
"*",
"OAuthProvider",
")",
"toBson",
"(",
")",
"bson",
".",
"M",
"{",
"return",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"struct",
"{",
"Scheme",
"string",
"\n",
"Host",
"string",
"\n",
"Path",
"string",
"\n",
"}",
"{",
"o",
".",
"BaseURL",
".",
"Scheme",
",",
"o",
".",
"BaseURL",
".",
"Host",
",",
"o",
".",
"BaseURL",
".",
"Path",
"}",
",",
"\"",
"\"",
":",
"o",
".",
"ID",
",",
"\"",
"\"",
":",
"o",
".",
"Secret",
",",
"\"",
"\"",
":",
"o",
".",
"Service",
"}",
"\n\n",
"}"
] |
// workaround to save urls as struct
|
[
"workaround",
"to",
"save",
"urls",
"as",
"struct"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/types.go#L50-L60
|
train
|
requilence/integram
|
helpers.go
|
URLMustParse
|
func URLMustParse(s string) *url.URL {
u, err := url.Parse(s)
if err != nil {
log.Errorf("Expected URL to parse: %q, got error: %v", s, err)
}
return u
}
|
go
|
func URLMustParse(s string) *url.URL {
u, err := url.Parse(s)
if err != nil {
log.Errorf("Expected URL to parse: %q, got error: %v", s, err)
}
return u
}
|
[
"func",
"URLMustParse",
"(",
"s",
"string",
")",
"*",
"url",
".",
"URL",
"{",
"u",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"s",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"s",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"u",
"\n",
"}"
] |
// URLMustParse returns url.URL from static string. Don't use it with a dynamic param
|
[
"URLMustParse",
"returns",
"url",
".",
"URL",
"from",
"static",
"string",
".",
"Don",
"t",
"use",
"it",
"with",
"a",
"dynamic",
"param"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/helpers.go#L165-L171
|
train
|
requilence/integram
|
helpers.go
|
GetVersion
|
func GetVersion() string {
if currentGitHead == "" {
b, err := ioutil.ReadFile(".git/HEAD")
if err != nil {
currentGitHead = "unknown"
return currentGitHead
}
p := refRE.FindStringSubmatch(string(b))
if len(p) < 2 {
currentGitHead = string(b)
return currentGitHead
}
b, err = ioutil.ReadFile(".git/" + p[1])
if err != nil {
currentGitHead = p[1]
return currentGitHead
}
currentGitHead = string(b)
}
return currentGitHead
}
|
go
|
func GetVersion() string {
if currentGitHead == "" {
b, err := ioutil.ReadFile(".git/HEAD")
if err != nil {
currentGitHead = "unknown"
return currentGitHead
}
p := refRE.FindStringSubmatch(string(b))
if len(p) < 2 {
currentGitHead = string(b)
return currentGitHead
}
b, err = ioutil.ReadFile(".git/" + p[1])
if err != nil {
currentGitHead = p[1]
return currentGitHead
}
currentGitHead = string(b)
}
return currentGitHead
}
|
[
"func",
"GetVersion",
"(",
")",
"string",
"{",
"if",
"currentGitHead",
"==",
"\"",
"\"",
"{",
"b",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"\"",
"\"",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"currentGitHead",
"=",
"\"",
"\"",
"\n",
"return",
"currentGitHead",
"\n",
"}",
"\n\n",
"p",
":=",
"refRE",
".",
"FindStringSubmatch",
"(",
"string",
"(",
"b",
")",
")",
"\n\n",
"if",
"len",
"(",
"p",
")",
"<",
"2",
"{",
"currentGitHead",
"=",
"string",
"(",
"b",
")",
"\n",
"return",
"currentGitHead",
"\n",
"}",
"\n\n",
"b",
",",
"err",
"=",
"ioutil",
".",
"ReadFile",
"(",
"\"",
"\"",
"+",
"p",
"[",
"1",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"currentGitHead",
"=",
"p",
"[",
"1",
"]",
"\n",
"return",
"currentGitHead",
"\n",
"}",
"\n\n",
"currentGitHead",
"=",
"string",
"(",
"b",
")",
"\n",
"}",
"\n",
"return",
"currentGitHead",
"\n",
"}"
] |
// GetVersion returns the current HEAD git commit if .git exists
|
[
"GetVersion",
"returns",
"the",
"current",
"HEAD",
"git",
"commit",
"if",
".",
"git",
"exists"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/helpers.go#L200-L225
|
train
|
requilence/integram
|
data.go
|
Cache
|
func (user *User) Cache(key string, res interface{}) (exists bool) {
return user.ctx.getCacheVal("user", key, res)
}
|
go
|
func (user *User) Cache(key string, res interface{}) (exists bool) {
return user.ctx.getCacheVal("user", key, res)
}
|
[
"func",
"(",
"user",
"*",
"User",
")",
"Cache",
"(",
"key",
"string",
",",
"res",
"interface",
"{",
"}",
")",
"(",
"exists",
"bool",
")",
"{",
"return",
"user",
".",
"ctx",
".",
"getCacheVal",
"(",
"\"",
"\"",
",",
"key",
",",
"res",
")",
"\n",
"}"
] |
// Cache returns if User's cache for specific key exists and try to bind it to res
|
[
"Cache",
"returns",
"if",
"User",
"s",
"cache",
"for",
"specific",
"key",
"exists",
"and",
"try",
"to",
"bind",
"it",
"to",
"res"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/data.go#L377-L379
|
train
|
requilence/integram
|
data.go
|
Cache
|
func (chat *Chat) Cache(key string, res interface{}) (exists bool) {
return chat.ctx.getCacheVal("chat", key, res)
}
|
go
|
func (chat *Chat) Cache(key string, res interface{}) (exists bool) {
return chat.ctx.getCacheVal("chat", key, res)
}
|
[
"func",
"(",
"chat",
"*",
"Chat",
")",
"Cache",
"(",
"key",
"string",
",",
"res",
"interface",
"{",
"}",
")",
"(",
"exists",
"bool",
")",
"{",
"return",
"chat",
".",
"ctx",
".",
"getCacheVal",
"(",
"\"",
"\"",
",",
"key",
",",
"res",
")",
"\n",
"}"
] |
// Cache returns if Chat's cache for specific key exists and try to bind it to res
|
[
"Cache",
"returns",
"if",
"Chat",
"s",
"cache",
"for",
"specific",
"key",
"exists",
"and",
"try",
"to",
"bind",
"it",
"to",
"res"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/data.go#L382-L384
|
train
|
requilence/integram
|
data.go
|
ServiceCache
|
func (c *Context) ServiceCache(key string, res interface{}) (exists bool) {
return c.getCacheVal("service", key, res)
}
|
go
|
func (c *Context) ServiceCache(key string, res interface{}) (exists bool) {
return c.getCacheVal("service", key, res)
}
|
[
"func",
"(",
"c",
"*",
"Context",
")",
"ServiceCache",
"(",
"key",
"string",
",",
"res",
"interface",
"{",
"}",
")",
"(",
"exists",
"bool",
")",
"{",
"return",
"c",
".",
"getCacheVal",
"(",
"\"",
"\"",
",",
"key",
",",
"res",
")",
"\n",
"}"
] |
// ServiceCache returns if Services's cache for specific key exists and try to bind it to res
|
[
"ServiceCache",
"returns",
"if",
"Services",
"s",
"cache",
"for",
"specific",
"key",
"exists",
"and",
"try",
"to",
"bind",
"it",
"to",
"res"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/data.go#L387-L389
|
train
|
requilence/integram
|
data.go
|
SetCache
|
func (user *User) SetCache(key string, val interface{}, ttl time.Duration) error {
expiresAt := time.Now().Add(ttl)
serviceID := user.ctx.getServiceID()
key = strings.ToLower(key)
if val == nil {
err := user.ctx.db.C("users_cache").Remove(bson.M{"userid": user.ID, "service": serviceID, "key": key})
return err
}
_, err := user.ctx.db.C("users_cache").Upsert(bson.M{"userid": user.ID, "service": serviceID, "key": key}, bson.M{"$set": bson.M{"val": val, "expiresat": expiresAt}})
if err != nil {
// workaround for WiredTiger bug: https://jira.mongodb.org/browse/SERVER-14322
if mgo.IsDup(err) {
return user.ctx.db.C("users_cache").Update(bson.M{"userid": user.ID, "service": serviceID, "key": key}, bson.M{"$set": bson.M{"val": val, "expiresat": expiresAt}})
}
log.WithError(err).WithField("key", key).Error("Can't set user cache value")
}
return err
}
|
go
|
func (user *User) SetCache(key string, val interface{}, ttl time.Duration) error {
expiresAt := time.Now().Add(ttl)
serviceID := user.ctx.getServiceID()
key = strings.ToLower(key)
if val == nil {
err := user.ctx.db.C("users_cache").Remove(bson.M{"userid": user.ID, "service": serviceID, "key": key})
return err
}
_, err := user.ctx.db.C("users_cache").Upsert(bson.M{"userid": user.ID, "service": serviceID, "key": key}, bson.M{"$set": bson.M{"val": val, "expiresat": expiresAt}})
if err != nil {
// workaround for WiredTiger bug: https://jira.mongodb.org/browse/SERVER-14322
if mgo.IsDup(err) {
return user.ctx.db.C("users_cache").Update(bson.M{"userid": user.ID, "service": serviceID, "key": key}, bson.M{"$set": bson.M{"val": val, "expiresat": expiresAt}})
}
log.WithError(err).WithField("key", key).Error("Can't set user cache value")
}
return err
}
|
[
"func",
"(",
"user",
"*",
"User",
")",
"SetCache",
"(",
"key",
"string",
",",
"val",
"interface",
"{",
"}",
",",
"ttl",
"time",
".",
"Duration",
")",
"error",
"{",
"expiresAt",
":=",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"ttl",
")",
"\n\n",
"serviceID",
":=",
"user",
".",
"ctx",
".",
"getServiceID",
"(",
")",
"\n",
"key",
"=",
"strings",
".",
"ToLower",
"(",
"key",
")",
"\n\n",
"if",
"val",
"==",
"nil",
"{",
"err",
":=",
"user",
".",
"ctx",
".",
"db",
".",
"C",
"(",
"\"",
"\"",
")",
".",
"Remove",
"(",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"user",
".",
"ID",
",",
"\"",
"\"",
":",
"serviceID",
",",
"\"",
"\"",
":",
"key",
"}",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"user",
".",
"ctx",
".",
"db",
".",
"C",
"(",
"\"",
"\"",
")",
".",
"Upsert",
"(",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"user",
".",
"ID",
",",
"\"",
"\"",
":",
"serviceID",
",",
"\"",
"\"",
":",
"key",
"}",
",",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"val",
",",
"\"",
"\"",
":",
"expiresAt",
"}",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// workaround for WiredTiger bug: https://jira.mongodb.org/browse/SERVER-14322",
"if",
"mgo",
".",
"IsDup",
"(",
"err",
")",
"{",
"return",
"user",
".",
"ctx",
".",
"db",
".",
"C",
"(",
"\"",
"\"",
")",
".",
"Update",
"(",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"user",
".",
"ID",
",",
"\"",
"\"",
":",
"serviceID",
",",
"\"",
"\"",
":",
"key",
"}",
",",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"val",
",",
"\"",
"\"",
":",
"expiresAt",
"}",
"}",
")",
"\n",
"}",
"\n",
"log",
".",
"WithError",
"(",
"err",
")",
".",
"WithField",
"(",
"\"",
"\"",
",",
"key",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] |
// SetCache set the User's cache with specific key and TTL
|
[
"SetCache",
"set",
"the",
"User",
"s",
"cache",
"with",
"specific",
"key",
"and",
"TTL"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/data.go#L405-L424
|
train
|
requilence/integram
|
data.go
|
UpdateCache
|
func (user *User) UpdateCache(key string, update interface{}, res interface{}) error {
exists := user.ctx.updateCacheVal("user", key, update, res)
if !exists {
log.WithField("key", key).Error("Can't update user cache value")
}
return nil
}
|
go
|
func (user *User) UpdateCache(key string, update interface{}, res interface{}) error {
exists := user.ctx.updateCacheVal("user", key, update, res)
if !exists {
log.WithField("key", key).Error("Can't update user cache value")
}
return nil
}
|
[
"func",
"(",
"user",
"*",
"User",
")",
"UpdateCache",
"(",
"key",
"string",
",",
"update",
"interface",
"{",
"}",
",",
"res",
"interface",
"{",
"}",
")",
"error",
"{",
"exists",
":=",
"user",
".",
"ctx",
".",
"updateCacheVal",
"(",
"\"",
"\"",
",",
"key",
",",
"update",
",",
"res",
")",
"\n\n",
"if",
"!",
"exists",
"{",
"log",
".",
"WithField",
"(",
"\"",
"\"",
",",
"key",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// UpdateCache updates the per User cache using MongoDB Update query
|
[
"UpdateCache",
"updates",
"the",
"per",
"User",
"cache",
"using",
"MongoDB",
"Update",
"query"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/data.go#L427-L435
|
train
|
requilence/integram
|
data.go
|
SetServiceCache
|
func (c *Context) SetServiceCache(key string, val interface{}, ttl time.Duration) error {
expiresAt := time.Now().Add(ttl)
serviceID := c.getServiceID()
key = strings.ToLower(key)
if val == nil {
err := c.db.C("services_cache").Remove(bson.M{"service": serviceID, "key": key})
return err
}
_, err := c.db.C("services_cache").Upsert(bson.M{"service": serviceID, "key": key}, bson.M{"$set": bson.M{"val": val, "expiresat": expiresAt}})
if err != nil {
// workaround for WiredTiger bug: https://jira.mongodb.org/browse/SERVER-14322
if mgo.IsDup(err) {
return c.db.C("services_cache").Update(bson.M{"service": serviceID, "key": key}, bson.M{"$set": bson.M{"val": val, "expiresat": expiresAt}})
}
log.WithError(err).WithField("key", key).Error("Can't set sevices cache value")
}
return err
}
|
go
|
func (c *Context) SetServiceCache(key string, val interface{}, ttl time.Duration) error {
expiresAt := time.Now().Add(ttl)
serviceID := c.getServiceID()
key = strings.ToLower(key)
if val == nil {
err := c.db.C("services_cache").Remove(bson.M{"service": serviceID, "key": key})
return err
}
_, err := c.db.C("services_cache").Upsert(bson.M{"service": serviceID, "key": key}, bson.M{"$set": bson.M{"val": val, "expiresat": expiresAt}})
if err != nil {
// workaround for WiredTiger bug: https://jira.mongodb.org/browse/SERVER-14322
if mgo.IsDup(err) {
return c.db.C("services_cache").Update(bson.M{"service": serviceID, "key": key}, bson.M{"$set": bson.M{"val": val, "expiresat": expiresAt}})
}
log.WithError(err).WithField("key", key).Error("Can't set sevices cache value")
}
return err
}
|
[
"func",
"(",
"c",
"*",
"Context",
")",
"SetServiceCache",
"(",
"key",
"string",
",",
"val",
"interface",
"{",
"}",
",",
"ttl",
"time",
".",
"Duration",
")",
"error",
"{",
"expiresAt",
":=",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"ttl",
")",
"\n",
"serviceID",
":=",
"c",
".",
"getServiceID",
"(",
")",
"\n",
"key",
"=",
"strings",
".",
"ToLower",
"(",
"key",
")",
"\n\n",
"if",
"val",
"==",
"nil",
"{",
"err",
":=",
"c",
".",
"db",
".",
"C",
"(",
"\"",
"\"",
")",
".",
"Remove",
"(",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"serviceID",
",",
"\"",
"\"",
":",
"key",
"}",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"_",
",",
"err",
":=",
"c",
".",
"db",
".",
"C",
"(",
"\"",
"\"",
")",
".",
"Upsert",
"(",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"serviceID",
",",
"\"",
"\"",
":",
"key",
"}",
",",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"val",
",",
"\"",
"\"",
":",
"expiresAt",
"}",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// workaround for WiredTiger bug: https://jira.mongodb.org/browse/SERVER-14322",
"if",
"mgo",
".",
"IsDup",
"(",
"err",
")",
"{",
"return",
"c",
".",
"db",
".",
"C",
"(",
"\"",
"\"",
")",
".",
"Update",
"(",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"serviceID",
",",
"\"",
"\"",
":",
"key",
"}",
",",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"val",
",",
"\"",
"\"",
":",
"expiresAt",
"}",
"}",
")",
"\n",
"}",
"\n",
"log",
".",
"WithError",
"(",
"err",
")",
".",
"WithField",
"(",
"\"",
"\"",
",",
"key",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] |
// SetServiceCache set the Services's cache with specific key and TTL
|
[
"SetServiceCache",
"set",
"the",
"Services",
"s",
"cache",
"with",
"specific",
"key",
"and",
"TTL"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/data.go#L470-L489
|
train
|
requilence/integram
|
data.go
|
Settings
|
func (user *User) Settings(out interface{}) error {
data, err := user.getData()
if err != nil {
return err
}
serviceID := user.ctx.getServiceID()
if _, ok := data.Settings[serviceID]; ok {
// TODO: workaround that creepy bindInterfaceToInterface
err = bindInterfaceToInterface(data.Settings[serviceID], out)
return err
}
// Not a error – just empty settings
return nil
}
|
go
|
func (user *User) Settings(out interface{}) error {
data, err := user.getData()
if err != nil {
return err
}
serviceID := user.ctx.getServiceID()
if _, ok := data.Settings[serviceID]; ok {
// TODO: workaround that creepy bindInterfaceToInterface
err = bindInterfaceToInterface(data.Settings[serviceID], out)
return err
}
// Not a error – just empty settings
return nil
}
|
[
"func",
"(",
"user",
"*",
"User",
")",
"Settings",
"(",
"out",
"interface",
"{",
"}",
")",
"error",
"{",
"data",
",",
"err",
":=",
"user",
".",
"getData",
"(",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"serviceID",
":=",
"user",
".",
"ctx",
".",
"getServiceID",
"(",
")",
"\n\n",
"if",
"_",
",",
"ok",
":=",
"data",
".",
"Settings",
"[",
"serviceID",
"]",
";",
"ok",
"{",
"// TODO: workaround that creepy bindInterfaceToInterface",
"err",
"=",
"bindInterfaceToInterface",
"(",
"data",
".",
"Settings",
"[",
"serviceID",
"]",
",",
"out",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"// Not a error – just empty settings",
"return",
"nil",
"\n",
"}"
] |
// Settings bind User's settings for service to the interface
|
[
"Settings",
"bind",
"User",
"s",
"settings",
"for",
"service",
"to",
"the",
"interface"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/data.go#L642-L658
|
train
|
requilence/integram
|
data.go
|
Settings
|
func (chat *Chat) Settings(out interface{}) error {
data, err := chat.getData()
if err != nil {
return err
}
serviceID := chat.ctx.getServiceID()
if _, ok := data.Settings[serviceID]; ok {
// TODO: workaround that creepy bindInterfaceToInterface
err = bindInterfaceToInterface(data.Settings[serviceID], out)
return err
}
// Not a error – just empty settings
return nil
}
|
go
|
func (chat *Chat) Settings(out interface{}) error {
data, err := chat.getData()
if err != nil {
return err
}
serviceID := chat.ctx.getServiceID()
if _, ok := data.Settings[serviceID]; ok {
// TODO: workaround that creepy bindInterfaceToInterface
err = bindInterfaceToInterface(data.Settings[serviceID], out)
return err
}
// Not a error – just empty settings
return nil
}
|
[
"func",
"(",
"chat",
"*",
"Chat",
")",
"Settings",
"(",
"out",
"interface",
"{",
"}",
")",
"error",
"{",
"data",
",",
"err",
":=",
"chat",
".",
"getData",
"(",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"serviceID",
":=",
"chat",
".",
"ctx",
".",
"getServiceID",
"(",
")",
"\n\n",
"if",
"_",
",",
"ok",
":=",
"data",
".",
"Settings",
"[",
"serviceID",
"]",
";",
"ok",
"{",
"// TODO: workaround that creepy bindInterfaceToInterface",
"err",
"=",
"bindInterfaceToInterface",
"(",
"data",
".",
"Settings",
"[",
"serviceID",
"]",
",",
"out",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"// Not a error – just empty settings",
"return",
"nil",
"\n",
"}"
] |
// Settings bind Chat's settings for service to the interface
|
[
"Settings",
"bind",
"Chat",
"s",
"settings",
"for",
"service",
"to",
"the",
"interface"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/data.go#L661-L678
|
train
|
requilence/integram
|
data.go
|
SaveSettings
|
func (chat *Chat) SaveSettings(allSettings interface{}) error {
serviceID := chat.ctx.getServiceID()
_, err := chat.ctx.db.C("chats").UpsertId(chat.ID, bson.M{"$set": bson.M{"settings." + serviceID: allSettings}, "$setOnInsert": bson.M{"createdat": time.Now()}})
if chat.data == nil {
chat.data = &chatData{}
}
if chat.data.Settings == nil {
chat.data.Settings = make(map[string]interface{})
}
chat.data.Settings[serviceID] = allSettings
return err
}
|
go
|
func (chat *Chat) SaveSettings(allSettings interface{}) error {
serviceID := chat.ctx.getServiceID()
_, err := chat.ctx.db.C("chats").UpsertId(chat.ID, bson.M{"$set": bson.M{"settings." + serviceID: allSettings}, "$setOnInsert": bson.M{"createdat": time.Now()}})
if chat.data == nil {
chat.data = &chatData{}
}
if chat.data.Settings == nil {
chat.data.Settings = make(map[string]interface{})
}
chat.data.Settings[serviceID] = allSettings
return err
}
|
[
"func",
"(",
"chat",
"*",
"Chat",
")",
"SaveSettings",
"(",
"allSettings",
"interface",
"{",
"}",
")",
"error",
"{",
"serviceID",
":=",
"chat",
".",
"ctx",
".",
"getServiceID",
"(",
")",
"\n\n",
"_",
",",
"err",
":=",
"chat",
".",
"ctx",
".",
"db",
".",
"C",
"(",
"\"",
"\"",
")",
".",
"UpsertId",
"(",
"chat",
".",
"ID",
",",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
"+",
"serviceID",
":",
"allSettings",
"}",
",",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"time",
".",
"Now",
"(",
")",
"}",
"}",
")",
"\n\n",
"if",
"chat",
".",
"data",
"==",
"nil",
"{",
"chat",
".",
"data",
"=",
"&",
"chatData",
"{",
"}",
"\n",
"}",
"\n\n",
"if",
"chat",
".",
"data",
".",
"Settings",
"==",
"nil",
"{",
"chat",
".",
"data",
".",
"Settings",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"}",
"\n\n",
"chat",
".",
"data",
".",
"Settings",
"[",
"serviceID",
"]",
"=",
"allSettings",
"\n\n",
"return",
"err",
"\n",
"}"
] |
// SaveSettings save Chat's setting for service
|
[
"SaveSettings",
"save",
"Chat",
"s",
"setting",
"for",
"service"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/data.go#L713-L730
|
train
|
requilence/integram
|
data.go
|
SaveSettings
|
func (user *User) SaveSettings(allSettings interface{}) error {
serviceID := user.ctx.getServiceID()
_, err := user.ctx.db.C("users").UpsertId(user.ID, bson.M{"$set": bson.M{"settings." + serviceID: allSettings}, "$setOnInsert": bson.M{"createdat": time.Now()}})
if user.data == nil {
user.data = &userData{}
}
if user.data.Settings == nil {
user.data.Settings = make(map[string]interface{})
}
user.data.Settings[serviceID] = allSettings
return err
}
|
go
|
func (user *User) SaveSettings(allSettings interface{}) error {
serviceID := user.ctx.getServiceID()
_, err := user.ctx.db.C("users").UpsertId(user.ID, bson.M{"$set": bson.M{"settings." + serviceID: allSettings}, "$setOnInsert": bson.M{"createdat": time.Now()}})
if user.data == nil {
user.data = &userData{}
}
if user.data.Settings == nil {
user.data.Settings = make(map[string]interface{})
}
user.data.Settings[serviceID] = allSettings
return err
}
|
[
"func",
"(",
"user",
"*",
"User",
")",
"SaveSettings",
"(",
"allSettings",
"interface",
"{",
"}",
")",
"error",
"{",
"serviceID",
":=",
"user",
".",
"ctx",
".",
"getServiceID",
"(",
")",
"\n\n",
"_",
",",
"err",
":=",
"user",
".",
"ctx",
".",
"db",
".",
"C",
"(",
"\"",
"\"",
")",
".",
"UpsertId",
"(",
"user",
".",
"ID",
",",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
"+",
"serviceID",
":",
"allSettings",
"}",
",",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"time",
".",
"Now",
"(",
")",
"}",
"}",
")",
"\n\n",
"if",
"user",
".",
"data",
"==",
"nil",
"{",
"user",
".",
"data",
"=",
"&",
"userData",
"{",
"}",
"\n",
"}",
"\n",
"if",
"user",
".",
"data",
".",
"Settings",
"==",
"nil",
"{",
"user",
".",
"data",
".",
"Settings",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"}",
"\n",
"user",
".",
"data",
".",
"Settings",
"[",
"serviceID",
"]",
"=",
"allSettings",
"\n\n",
"return",
"err",
"\n",
"}"
] |
// SaveSettings save User's setting for service
|
[
"SaveSettings",
"save",
"User",
"s",
"setting",
"for",
"service"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/data.go#L733-L748
|
train
|
requilence/integram
|
data.go
|
ServiceHookToken
|
func (chat *Chat) ServiceHookToken() string {
data, _ := chat.getData()
//TODO: test backward compatibility cases
for _, hook := range data.Hooks {
for _, service := range hook.Services {
if service == chat.ctx.ServiceName {
return hook.Token
}
}
}
token := "c" + rndStr.Get(10)
chat.addHook(serviceHook{
Token: token,
Services: []string{chat.ctx.ServiceName},
})
return token
}
|
go
|
func (chat *Chat) ServiceHookToken() string {
data, _ := chat.getData()
//TODO: test backward compatibility cases
for _, hook := range data.Hooks {
for _, service := range hook.Services {
if service == chat.ctx.ServiceName {
return hook.Token
}
}
}
token := "c" + rndStr.Get(10)
chat.addHook(serviceHook{
Token: token,
Services: []string{chat.ctx.ServiceName},
})
return token
}
|
[
"func",
"(",
"chat",
"*",
"Chat",
")",
"ServiceHookToken",
"(",
")",
"string",
"{",
"data",
",",
"_",
":=",
"chat",
".",
"getData",
"(",
")",
"\n",
"//TODO: test backward compatibility cases",
"for",
"_",
",",
"hook",
":=",
"range",
"data",
".",
"Hooks",
"{",
"for",
"_",
",",
"service",
":=",
"range",
"hook",
".",
"Services",
"{",
"if",
"service",
"==",
"chat",
".",
"ctx",
".",
"ServiceName",
"{",
"return",
"hook",
".",
"Token",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"token",
":=",
"\"",
"\"",
"+",
"rndStr",
".",
"Get",
"(",
"10",
")",
"\n",
"chat",
".",
"addHook",
"(",
"serviceHook",
"{",
"Token",
":",
"token",
",",
"Services",
":",
"[",
"]",
"string",
"{",
"chat",
".",
"ctx",
".",
"ServiceName",
"}",
",",
"}",
")",
"\n",
"return",
"token",
"\n",
"}"
] |
// ServiceHookToken returns Chats's hook token to use in webhook handling
|
[
"ServiceHookToken",
"returns",
"Chats",
"s",
"hook",
"token",
"to",
"use",
"in",
"webhook",
"handling"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/data.go#L784-L800
|
train
|
requilence/integram
|
data.go
|
ServiceHookURL
|
func (user *User) ServiceHookURL() string {
return Config.BaseURL + "/" + user.ctx.ServiceName + "/" + user.ServiceHookToken()
}
|
go
|
func (user *User) ServiceHookURL() string {
return Config.BaseURL + "/" + user.ctx.ServiceName + "/" + user.ServiceHookToken()
}
|
[
"func",
"(",
"user",
"*",
"User",
")",
"ServiceHookURL",
"(",
")",
"string",
"{",
"return",
"Config",
".",
"BaseURL",
"+",
"\"",
"\"",
"+",
"user",
".",
"ctx",
".",
"ServiceName",
"+",
"\"",
"\"",
"+",
"user",
".",
"ServiceHookToken",
"(",
")",
"\n",
"}"
] |
// ServiceHookURL returns User's webhook URL for service to use in webhook handling
// Used in case when incoming webhooks despatching on the user behalf to chats
|
[
"ServiceHookURL",
"returns",
"User",
"s",
"webhook",
"URL",
"for",
"service",
"to",
"use",
"in",
"webhook",
"handling",
"Used",
"in",
"case",
"when",
"incoming",
"webhooks",
"despatching",
"on",
"the",
"user",
"behalf",
"to",
"chats"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/data.go#L804-L806
|
train
|
requilence/integram
|
data.go
|
ServiceHookURL
|
func (chat *Chat) ServiceHookURL() string {
return Config.BaseURL + "/" + chat.ctx.ServiceName + "/" + chat.ServiceHookToken()
}
|
go
|
func (chat *Chat) ServiceHookURL() string {
return Config.BaseURL + "/" + chat.ctx.ServiceName + "/" + chat.ServiceHookToken()
}
|
[
"func",
"(",
"chat",
"*",
"Chat",
")",
"ServiceHookURL",
"(",
")",
"string",
"{",
"return",
"Config",
".",
"BaseURL",
"+",
"\"",
"\"",
"+",
"chat",
".",
"ctx",
".",
"ServiceName",
"+",
"\"",
"\"",
"+",
"chat",
".",
"ServiceHookToken",
"(",
")",
"\n",
"}"
] |
// ServiceHookURL returns Chats's webhook URL for service to use in webhook handling
// Used in case when user need to put webhook URL to receive notifications to chat
|
[
"ServiceHookURL",
"returns",
"Chats",
"s",
"webhook",
"URL",
"for",
"service",
"to",
"use",
"in",
"webhook",
"handling",
"Used",
"in",
"case",
"when",
"user",
"need",
"to",
"put",
"webhook",
"URL",
"to",
"receive",
"notifications",
"to",
"chat"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/data.go#L810-L812
|
train
|
requilence/integram
|
data.go
|
AddChatToHook
|
func (user *User) AddChatToHook(chatID int64) error {
data, _ := user.getData()
token := user.ServiceHookToken()
for i, hook := range data.Hooks {
if hook.Token == token {
for _, service := range hook.Services {
if service == user.ctx.ServiceName {
for _, existingChatID := range hook.Chats {
if existingChatID == chatID {
return nil
}
}
data.Hooks[i].Chats = append(data.Hooks[i].Chats, chatID)
err := user.ctx.db.C("users").Update(bson.M{"_id": user.ID, "hooks.services": service}, bson.M{"$addToSet": bson.M{"hooks.$.chats": chatID}})
return err
}
}
}
}
err := errors.New("Can't add chat to serviceHook. Can't find a hook.")
user.ctx.Log().Error(err)
return err
}
|
go
|
func (user *User) AddChatToHook(chatID int64) error {
data, _ := user.getData()
token := user.ServiceHookToken()
for i, hook := range data.Hooks {
if hook.Token == token {
for _, service := range hook.Services {
if service == user.ctx.ServiceName {
for _, existingChatID := range hook.Chats {
if existingChatID == chatID {
return nil
}
}
data.Hooks[i].Chats = append(data.Hooks[i].Chats, chatID)
err := user.ctx.db.C("users").Update(bson.M{"_id": user.ID, "hooks.services": service}, bson.M{"$addToSet": bson.M{"hooks.$.chats": chatID}})
return err
}
}
}
}
err := errors.New("Can't add chat to serviceHook. Can't find a hook.")
user.ctx.Log().Error(err)
return err
}
|
[
"func",
"(",
"user",
"*",
"User",
")",
"AddChatToHook",
"(",
"chatID",
"int64",
")",
"error",
"{",
"data",
",",
"_",
":=",
"user",
".",
"getData",
"(",
")",
"\n",
"token",
":=",
"user",
".",
"ServiceHookToken",
"(",
")",
"\n\n",
"for",
"i",
",",
"hook",
":=",
"range",
"data",
".",
"Hooks",
"{",
"if",
"hook",
".",
"Token",
"==",
"token",
"{",
"for",
"_",
",",
"service",
":=",
"range",
"hook",
".",
"Services",
"{",
"if",
"service",
"==",
"user",
".",
"ctx",
".",
"ServiceName",
"{",
"for",
"_",
",",
"existingChatID",
":=",
"range",
"hook",
".",
"Chats",
"{",
"if",
"existingChatID",
"==",
"chatID",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"data",
".",
"Hooks",
"[",
"i",
"]",
".",
"Chats",
"=",
"append",
"(",
"data",
".",
"Hooks",
"[",
"i",
"]",
".",
"Chats",
",",
"chatID",
")",
"\n",
"err",
":=",
"user",
".",
"ctx",
".",
"db",
".",
"C",
"(",
"\"",
"\"",
")",
".",
"Update",
"(",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"user",
".",
"ID",
",",
"\"",
"\"",
":",
"service",
"}",
",",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"chatID",
"}",
"}",
")",
"\n\n",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"err",
":=",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"user",
".",
"ctx",
".",
"Log",
"(",
")",
".",
"Error",
"(",
"err",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// AddChatToHook adds the target chat to user's existing hook
|
[
"AddChatToHook",
"adds",
"the",
"target",
"chat",
"to",
"user",
"s",
"existing",
"hook"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/data.go#L815-L839
|
train
|
requilence/integram
|
data.go
|
SaveSetting
|
func (chat *Chat) SaveSetting(key string, value interface{}) error {
key = strings.ToLower(key)
serviceID := chat.ctx.getServiceID()
var cd chatData
_, err := chat.ctx.db.C("chats").FindId(chat.ID).Select(bson.M{"settings." + serviceID: 1}).
Apply(
mgo.Change{
Update: bson.M{
"$set": bson.M{"settings." + serviceID + "." + key: value},
"$setOnInsert": bson.M{"createdat": time.Now()},
},
Upsert: true,
ReturnNew: true,
},
&cd)
if err == nil && chat.data != nil && chat.data.Settings != nil && cd.Settings != nil && cd.Settings[serviceID] != nil {
chat.data.Settings[serviceID] = cd.Settings[serviceID]
}
return err
}
|
go
|
func (chat *Chat) SaveSetting(key string, value interface{}) error {
key = strings.ToLower(key)
serviceID := chat.ctx.getServiceID()
var cd chatData
_, err := chat.ctx.db.C("chats").FindId(chat.ID).Select(bson.M{"settings." + serviceID: 1}).
Apply(
mgo.Change{
Update: bson.M{
"$set": bson.M{"settings." + serviceID + "." + key: value},
"$setOnInsert": bson.M{"createdat": time.Now()},
},
Upsert: true,
ReturnNew: true,
},
&cd)
if err == nil && chat.data != nil && chat.data.Settings != nil && cd.Settings != nil && cd.Settings[serviceID] != nil {
chat.data.Settings[serviceID] = cd.Settings[serviceID]
}
return err
}
|
[
"func",
"(",
"chat",
"*",
"Chat",
")",
"SaveSetting",
"(",
"key",
"string",
",",
"value",
"interface",
"{",
"}",
")",
"error",
"{",
"key",
"=",
"strings",
".",
"ToLower",
"(",
"key",
")",
"\n",
"serviceID",
":=",
"chat",
".",
"ctx",
".",
"getServiceID",
"(",
")",
"\n",
"var",
"cd",
"chatData",
"\n",
"_",
",",
"err",
":=",
"chat",
".",
"ctx",
".",
"db",
".",
"C",
"(",
"\"",
"\"",
")",
".",
"FindId",
"(",
"chat",
".",
"ID",
")",
".",
"Select",
"(",
"bson",
".",
"M",
"{",
"\"",
"\"",
"+",
"serviceID",
":",
"1",
"}",
")",
".",
"Apply",
"(",
"mgo",
".",
"Change",
"{",
"Update",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
"+",
"serviceID",
"+",
"\"",
"\"",
"+",
"key",
":",
"value",
"}",
",",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"time",
".",
"Now",
"(",
")",
"}",
",",
"}",
",",
"Upsert",
":",
"true",
",",
"ReturnNew",
":",
"true",
",",
"}",
",",
"&",
"cd",
")",
"\n\n",
"if",
"err",
"==",
"nil",
"&&",
"chat",
".",
"data",
"!=",
"nil",
"&&",
"chat",
".",
"data",
".",
"Settings",
"!=",
"nil",
"&&",
"cd",
".",
"Settings",
"!=",
"nil",
"&&",
"cd",
".",
"Settings",
"[",
"serviceID",
"]",
"!=",
"nil",
"{",
"chat",
".",
"data",
".",
"Settings",
"[",
"serviceID",
"]",
"=",
"cd",
".",
"Settings",
"[",
"serviceID",
"]",
"\n",
"}",
"\n\n",
"return",
"err",
"\n",
"}"
] |
// SaveSetting sets Chat's setting for service with specific key
|
[
"SaveSetting",
"sets",
"Chat",
"s",
"setting",
"for",
"service",
"with",
"specific",
"key"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/data.go#L895-L917
|
train
|
requilence/integram
|
data.go
|
SaveSetting
|
func (user *User) SaveSetting(key string, value interface{}) error {
if user.ID == 0 {
return errors.New("SaveSetting: user is empty")
}
key = strings.ToLower(key)
serviceID := user.ctx.getServiceID()
var ud userData
_, err := user.ctx.db.C("users").FindId(user.ID).Select(bson.M{"settings." + serviceID: 1}).
Apply(
mgo.Change{
Update: bson.M{
"$set": bson.M{"settings." + serviceID + "." + key: value},
"$setOnInsert": bson.M{"createdat": time.Now()},
},
Upsert: true,
ReturnNew: true,
},
&ud)
if err == nil && user.data != nil && user.data.Settings != nil && ud.Settings != nil && ud.Settings[serviceID] != nil {
user.data.Settings[serviceID] = ud.Settings[serviceID]
}
return err
}
|
go
|
func (user *User) SaveSetting(key string, value interface{}) error {
if user.ID == 0 {
return errors.New("SaveSetting: user is empty")
}
key = strings.ToLower(key)
serviceID := user.ctx.getServiceID()
var ud userData
_, err := user.ctx.db.C("users").FindId(user.ID).Select(bson.M{"settings." + serviceID: 1}).
Apply(
mgo.Change{
Update: bson.M{
"$set": bson.M{"settings." + serviceID + "." + key: value},
"$setOnInsert": bson.M{"createdat": time.Now()},
},
Upsert: true,
ReturnNew: true,
},
&ud)
if err == nil && user.data != nil && user.data.Settings != nil && ud.Settings != nil && ud.Settings[serviceID] != nil {
user.data.Settings[serviceID] = ud.Settings[serviceID]
}
return err
}
|
[
"func",
"(",
"user",
"*",
"User",
")",
"SaveSetting",
"(",
"key",
"string",
",",
"value",
"interface",
"{",
"}",
")",
"error",
"{",
"if",
"user",
".",
"ID",
"==",
"0",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"key",
"=",
"strings",
".",
"ToLower",
"(",
"key",
")",
"\n",
"serviceID",
":=",
"user",
".",
"ctx",
".",
"getServiceID",
"(",
")",
"\n\n",
"var",
"ud",
"userData",
"\n",
"_",
",",
"err",
":=",
"user",
".",
"ctx",
".",
"db",
".",
"C",
"(",
"\"",
"\"",
")",
".",
"FindId",
"(",
"user",
".",
"ID",
")",
".",
"Select",
"(",
"bson",
".",
"M",
"{",
"\"",
"\"",
"+",
"serviceID",
":",
"1",
"}",
")",
".",
"Apply",
"(",
"mgo",
".",
"Change",
"{",
"Update",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
"+",
"serviceID",
"+",
"\"",
"\"",
"+",
"key",
":",
"value",
"}",
",",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"time",
".",
"Now",
"(",
")",
"}",
",",
"}",
",",
"Upsert",
":",
"true",
",",
"ReturnNew",
":",
"true",
",",
"}",
",",
"&",
"ud",
")",
"\n\n",
"if",
"err",
"==",
"nil",
"&&",
"user",
".",
"data",
"!=",
"nil",
"&&",
"user",
".",
"data",
".",
"Settings",
"!=",
"nil",
"&&",
"ud",
".",
"Settings",
"!=",
"nil",
"&&",
"ud",
".",
"Settings",
"[",
"serviceID",
"]",
"!=",
"nil",
"{",
"user",
".",
"data",
".",
"Settings",
"[",
"serviceID",
"]",
"=",
"ud",
".",
"Settings",
"[",
"serviceID",
"]",
"\n",
"}",
"\n\n",
"return",
"err",
"\n",
"}"
] |
// SaveSetting sets User's setting for service with specific key
|
[
"SaveSetting",
"sets",
"User",
"s",
"setting",
"for",
"service",
"with",
"specific",
"key"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/data.go#L920-L947
|
train
|
requilence/integram
|
data.go
|
AuthTempToken
|
func (user *User) AuthTempToken() string {
host := user.ctx.ServiceBaseURL.Host
if host == "" {
host = user.ctx.Service().DefaultBaseURL.Host
}
serviceBaseURL := user.ctx.ServiceBaseURL.String()
if serviceBaseURL == "" {
serviceBaseURL = user.ctx.Service().DefaultBaseURL.String()
}
ps, _ := user.protectedSettings()
if ps.AuthTempToken != "" {
fmt.Println("found AuthTempToken:" + ps.AuthTempToken)
oAuthIDCacheFound := oAuthIDCacheVal{}
if exists := user.Cache("auth_"+ps.AuthTempToken, &oAuthIDCacheFound); !exists {
oAuthIDCacheFound = oAuthIDCacheVal{BaseURL: serviceBaseURL}
user.SetCache("auth_"+ps.AuthTempToken, oAuthIDCacheFound, time.Hour*24)
}
u, _ := url.Parse(oAuthIDCacheFound.BaseURL)
if u != nil && u.Host == host {
return ps.AuthTempToken
}
}
rnd := strings.ToLower(rndStr.Get(16))
user.SetCache("auth_"+rnd, oAuthIDCacheVal{BaseURL: serviceBaseURL}, time.Hour*24)
err := user.saveProtectedSetting("AuthTempToken", rnd)
if err != nil {
user.ctx.Log().WithError(err).Error("Error saving AuthTempToken")
}
return rnd
}
|
go
|
func (user *User) AuthTempToken() string {
host := user.ctx.ServiceBaseURL.Host
if host == "" {
host = user.ctx.Service().DefaultBaseURL.Host
}
serviceBaseURL := user.ctx.ServiceBaseURL.String()
if serviceBaseURL == "" {
serviceBaseURL = user.ctx.Service().DefaultBaseURL.String()
}
ps, _ := user.protectedSettings()
if ps.AuthTempToken != "" {
fmt.Println("found AuthTempToken:" + ps.AuthTempToken)
oAuthIDCacheFound := oAuthIDCacheVal{}
if exists := user.Cache("auth_"+ps.AuthTempToken, &oAuthIDCacheFound); !exists {
oAuthIDCacheFound = oAuthIDCacheVal{BaseURL: serviceBaseURL}
user.SetCache("auth_"+ps.AuthTempToken, oAuthIDCacheFound, time.Hour*24)
}
u, _ := url.Parse(oAuthIDCacheFound.BaseURL)
if u != nil && u.Host == host {
return ps.AuthTempToken
}
}
rnd := strings.ToLower(rndStr.Get(16))
user.SetCache("auth_"+rnd, oAuthIDCacheVal{BaseURL: serviceBaseURL}, time.Hour*24)
err := user.saveProtectedSetting("AuthTempToken", rnd)
if err != nil {
user.ctx.Log().WithError(err).Error("Error saving AuthTempToken")
}
return rnd
}
|
[
"func",
"(",
"user",
"*",
"User",
")",
"AuthTempToken",
"(",
")",
"string",
"{",
"host",
":=",
"user",
".",
"ctx",
".",
"ServiceBaseURL",
".",
"Host",
"\n",
"if",
"host",
"==",
"\"",
"\"",
"{",
"host",
"=",
"user",
".",
"ctx",
".",
"Service",
"(",
")",
".",
"DefaultBaseURL",
".",
"Host",
"\n",
"}",
"\n\n",
"serviceBaseURL",
":=",
"user",
".",
"ctx",
".",
"ServiceBaseURL",
".",
"String",
"(",
")",
"\n",
"if",
"serviceBaseURL",
"==",
"\"",
"\"",
"{",
"serviceBaseURL",
"=",
"user",
".",
"ctx",
".",
"Service",
"(",
")",
".",
"DefaultBaseURL",
".",
"String",
"(",
")",
"\n",
"}",
"\n\n",
"ps",
",",
"_",
":=",
"user",
".",
"protectedSettings",
"(",
")",
"\n",
"if",
"ps",
".",
"AuthTempToken",
"!=",
"\"",
"\"",
"{",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
"+",
"ps",
".",
"AuthTempToken",
")",
"\n\n",
"oAuthIDCacheFound",
":=",
"oAuthIDCacheVal",
"{",
"}",
"\n",
"if",
"exists",
":=",
"user",
".",
"Cache",
"(",
"\"",
"\"",
"+",
"ps",
".",
"AuthTempToken",
",",
"&",
"oAuthIDCacheFound",
")",
";",
"!",
"exists",
"{",
"oAuthIDCacheFound",
"=",
"oAuthIDCacheVal",
"{",
"BaseURL",
":",
"serviceBaseURL",
"}",
"\n",
"user",
".",
"SetCache",
"(",
"\"",
"\"",
"+",
"ps",
".",
"AuthTempToken",
",",
"oAuthIDCacheFound",
",",
"time",
".",
"Hour",
"*",
"24",
")",
"\n",
"}",
"\n\n",
"u",
",",
"_",
":=",
"url",
".",
"Parse",
"(",
"oAuthIDCacheFound",
".",
"BaseURL",
")",
"\n\n",
"if",
"u",
"!=",
"nil",
"&&",
"u",
".",
"Host",
"==",
"host",
"{",
"return",
"ps",
".",
"AuthTempToken",
"\n",
"}",
"\n",
"}",
"\n\n",
"rnd",
":=",
"strings",
".",
"ToLower",
"(",
"rndStr",
".",
"Get",
"(",
"16",
")",
")",
"\n",
"user",
".",
"SetCache",
"(",
"\"",
"\"",
"+",
"rnd",
",",
"oAuthIDCacheVal",
"{",
"BaseURL",
":",
"serviceBaseURL",
"}",
",",
"time",
".",
"Hour",
"*",
"24",
")",
"\n\n",
"err",
":=",
"user",
".",
"saveProtectedSetting",
"(",
"\"",
"\"",
",",
"rnd",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"user",
".",
"ctx",
".",
"Log",
"(",
")",
".",
"WithError",
"(",
"err",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"rnd",
"\n",
"}"
] |
// AuthTempToken returns Auth token used in OAuth process to associate TG user with OAuth creditianals
|
[
"AuthTempToken",
"returns",
"Auth",
"token",
"used",
"in",
"OAuth",
"process",
"to",
"associate",
"TG",
"user",
"with",
"OAuth",
"creditianals"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/data.go#L950-L988
|
train
|
requilence/integram
|
data.go
|
OauthRedirectURL
|
func (user *User) OauthRedirectURL() string {
providerID := user.ctx.OAuthProvider().internalID()
if providerID == user.ctx.ServiceName {
return fmt.Sprintf("%s/auth/%s", Config.BaseURL, user.ctx.ServiceName)
}
return fmt.Sprintf("%s/auth/%s/%s", Config.BaseURL, user.ctx.ServiceName, providerID)
}
|
go
|
func (user *User) OauthRedirectURL() string {
providerID := user.ctx.OAuthProvider().internalID()
if providerID == user.ctx.ServiceName {
return fmt.Sprintf("%s/auth/%s", Config.BaseURL, user.ctx.ServiceName)
}
return fmt.Sprintf("%s/auth/%s/%s", Config.BaseURL, user.ctx.ServiceName, providerID)
}
|
[
"func",
"(",
"user",
"*",
"User",
")",
"OauthRedirectURL",
"(",
")",
"string",
"{",
"providerID",
":=",
"user",
".",
"ctx",
".",
"OAuthProvider",
"(",
")",
".",
"internalID",
"(",
")",
"\n",
"if",
"providerID",
"==",
"user",
".",
"ctx",
".",
"ServiceName",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"Config",
".",
"BaseURL",
",",
"user",
".",
"ctx",
".",
"ServiceName",
")",
"\n",
"}",
"\n\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"Config",
".",
"BaseURL",
",",
"user",
".",
"ctx",
".",
"ServiceName",
",",
"providerID",
")",
"\n",
"}"
] |
// OauthRedirectURL used in OAuth process as returning URL
|
[
"OauthRedirectURL",
"used",
"in",
"OAuth",
"process",
"as",
"returning",
"URL"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/data.go#L991-L998
|
train
|
requilence/integram
|
data.go
|
OauthInitURL
|
func (user *User) OauthInitURL() string {
authTempToken := user.AuthTempToken()
s := user.ctx.Service()
if authTempToken == "" {
user.ctx.Log().Error("authTempToken is empty")
return ""
}
if s.DefaultOAuth2 != nil {
provider := user.ctx.OAuthProvider()
return provider.OAuth2Client(user.ctx).AuthCodeURL(authTempToken, oauth2.AccessTypeOffline)
}
if s.DefaultOAuth1 != nil {
return fmt.Sprintf("%s/oauth1/%s/%s", Config.BaseURL, s.Name, authTempToken)
}
return ""
}
|
go
|
func (user *User) OauthInitURL() string {
authTempToken := user.AuthTempToken()
s := user.ctx.Service()
if authTempToken == "" {
user.ctx.Log().Error("authTempToken is empty")
return ""
}
if s.DefaultOAuth2 != nil {
provider := user.ctx.OAuthProvider()
return provider.OAuth2Client(user.ctx).AuthCodeURL(authTempToken, oauth2.AccessTypeOffline)
}
if s.DefaultOAuth1 != nil {
return fmt.Sprintf("%s/oauth1/%s/%s", Config.BaseURL, s.Name, authTempToken)
}
return ""
}
|
[
"func",
"(",
"user",
"*",
"User",
")",
"OauthInitURL",
"(",
")",
"string",
"{",
"authTempToken",
":=",
"user",
".",
"AuthTempToken",
"(",
")",
"\n",
"s",
":=",
"user",
".",
"ctx",
".",
"Service",
"(",
")",
"\n",
"if",
"authTempToken",
"==",
"\"",
"\"",
"{",
"user",
".",
"ctx",
".",
"Log",
"(",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"if",
"s",
".",
"DefaultOAuth2",
"!=",
"nil",
"{",
"provider",
":=",
"user",
".",
"ctx",
".",
"OAuthProvider",
"(",
")",
"\n\n",
"return",
"provider",
".",
"OAuth2Client",
"(",
"user",
".",
"ctx",
")",
".",
"AuthCodeURL",
"(",
"authTempToken",
",",
"oauth2",
".",
"AccessTypeOffline",
")",
"\n",
"}",
"\n",
"if",
"s",
".",
"DefaultOAuth1",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"Config",
".",
"BaseURL",
",",
"s",
".",
"Name",
",",
"authTempToken",
")",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] |
// OauthInitURL used in OAuth process as returning URL
|
[
"OauthInitURL",
"used",
"in",
"OAuth",
"process",
"as",
"returning",
"URL"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/data.go#L1001-L1017
|
train
|
requilence/integram
|
data.go
|
OAuthHTTPClient
|
func (user *User) OAuthHTTPClient() *http.Client {
ps, _ := user.protectedSettings()
if ps == nil {
return nil
}
if ps.OAuthToken == "" {
return nil
}
if user.ctx.Service().DefaultOAuth2 != nil {
ts := user.ctx.OAuthProvider().OAuth2Client(user.ctx).TokenSource(oauth2.NoContext, &oauth2.Token{AccessToken: ps.OAuthToken, RefreshToken: ps.OAuthRefreshToken, Expiry: *ps.OAuthExpireDate, TokenType: "Bearer"})
if ps.OAuthExpireDate != nil && ps.OAuthExpireDate.Before(time.Now().Add(time.Second*5)) {
token, err := ts.Token()
if err != nil {
if strings.Contains(err.Error(), "revoked") || strings.Contains(err.Error(), "invalid_grant") {
ps.OAuthToken = ""
ps.OAuthExpireDate = nil
user.saveProtectedSettings()
//todo: provide revoked callback
}
user.ctx.Log().WithError(err).Error("OAuth token refresh failed")
return nil
}
if token != nil {
ps.OAuthToken = token.AccessToken
if token.RefreshToken != "" {
ps.OAuthRefreshToken = token.RefreshToken
}
ps.OAuthExpireDate = &token.Expiry
user.saveProtectedSettings()
}
}
return oauth2.NewClient(oauth2.NoContext, ts)
} else if user.ctx.Service().DefaultOAuth1 != nil {
//todo make a correct httpclient
return http.DefaultClient
}
return nil
}
|
go
|
func (user *User) OAuthHTTPClient() *http.Client {
ps, _ := user.protectedSettings()
if ps == nil {
return nil
}
if ps.OAuthToken == "" {
return nil
}
if user.ctx.Service().DefaultOAuth2 != nil {
ts := user.ctx.OAuthProvider().OAuth2Client(user.ctx).TokenSource(oauth2.NoContext, &oauth2.Token{AccessToken: ps.OAuthToken, RefreshToken: ps.OAuthRefreshToken, Expiry: *ps.OAuthExpireDate, TokenType: "Bearer"})
if ps.OAuthExpireDate != nil && ps.OAuthExpireDate.Before(time.Now().Add(time.Second*5)) {
token, err := ts.Token()
if err != nil {
if strings.Contains(err.Error(), "revoked") || strings.Contains(err.Error(), "invalid_grant") {
ps.OAuthToken = ""
ps.OAuthExpireDate = nil
user.saveProtectedSettings()
//todo: provide revoked callback
}
user.ctx.Log().WithError(err).Error("OAuth token refresh failed")
return nil
}
if token != nil {
ps.OAuthToken = token.AccessToken
if token.RefreshToken != "" {
ps.OAuthRefreshToken = token.RefreshToken
}
ps.OAuthExpireDate = &token.Expiry
user.saveProtectedSettings()
}
}
return oauth2.NewClient(oauth2.NoContext, ts)
} else if user.ctx.Service().DefaultOAuth1 != nil {
//todo make a correct httpclient
return http.DefaultClient
}
return nil
}
|
[
"func",
"(",
"user",
"*",
"User",
")",
"OAuthHTTPClient",
"(",
")",
"*",
"http",
".",
"Client",
"{",
"ps",
",",
"_",
":=",
"user",
".",
"protectedSettings",
"(",
")",
"\n\n",
"if",
"ps",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"if",
"ps",
".",
"OAuthToken",
"==",
"\"",
"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"if",
"user",
".",
"ctx",
".",
"Service",
"(",
")",
".",
"DefaultOAuth2",
"!=",
"nil",
"{",
"ts",
":=",
"user",
".",
"ctx",
".",
"OAuthProvider",
"(",
")",
".",
"OAuth2Client",
"(",
"user",
".",
"ctx",
")",
".",
"TokenSource",
"(",
"oauth2",
".",
"NoContext",
",",
"&",
"oauth2",
".",
"Token",
"{",
"AccessToken",
":",
"ps",
".",
"OAuthToken",
",",
"RefreshToken",
":",
"ps",
".",
"OAuthRefreshToken",
",",
"Expiry",
":",
"*",
"ps",
".",
"OAuthExpireDate",
",",
"TokenType",
":",
"\"",
"\"",
"}",
")",
"\n",
"if",
"ps",
".",
"OAuthExpireDate",
"!=",
"nil",
"&&",
"ps",
".",
"OAuthExpireDate",
".",
"Before",
"(",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"time",
".",
"Second",
"*",
"5",
")",
")",
"{",
"token",
",",
"err",
":=",
"ts",
".",
"Token",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"strings",
".",
"Contains",
"(",
"err",
".",
"Error",
"(",
")",
",",
"\"",
"\"",
")",
"||",
"strings",
".",
"Contains",
"(",
"err",
".",
"Error",
"(",
")",
",",
"\"",
"\"",
")",
"{",
"ps",
".",
"OAuthToken",
"=",
"\"",
"\"",
"\n",
"ps",
".",
"OAuthExpireDate",
"=",
"nil",
"\n",
"user",
".",
"saveProtectedSettings",
"(",
")",
"\n",
"//todo: provide revoked callback",
"}",
"\n",
"user",
".",
"ctx",
".",
"Log",
"(",
")",
".",
"WithError",
"(",
"err",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"if",
"token",
"!=",
"nil",
"{",
"ps",
".",
"OAuthToken",
"=",
"token",
".",
"AccessToken",
"\n",
"if",
"token",
".",
"RefreshToken",
"!=",
"\"",
"\"",
"{",
"ps",
".",
"OAuthRefreshToken",
"=",
"token",
".",
"RefreshToken",
"\n",
"}",
"\n",
"ps",
".",
"OAuthExpireDate",
"=",
"&",
"token",
".",
"Expiry",
"\n",
"user",
".",
"saveProtectedSettings",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"oauth2",
".",
"NewClient",
"(",
"oauth2",
".",
"NoContext",
",",
"ts",
")",
"\n",
"}",
"else",
"if",
"user",
".",
"ctx",
".",
"Service",
"(",
")",
".",
"DefaultOAuth1",
"!=",
"nil",
"{",
"//todo make a correct httpclient",
"return",
"http",
".",
"DefaultClient",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// OAuthHTTPClient returns HTTP client with Bearer authorization headers
|
[
"OAuthHTTPClient",
"returns",
"HTTP",
"client",
"with",
"Bearer",
"authorization",
"headers"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/data.go#L1024-L1066
|
train
|
requilence/integram
|
data.go
|
OAuthToken
|
func (user *User) OAuthToken() string {
// todo: oauthtoken per host?
/*
host := user.ctx.ServiceBaseURL.Host
if host == "" {
host = user.ctx.Service().DefaultBaseURL.Host
}
*/
ps, _ := user.protectedSettings()
if ps != nil {
if ps.OAuthExpireDate != nil && ps.OAuthExpireDate.Before(time.Now().Add(time.Second*5)) {
token, err := user.ctx.OAuthProvider().OAuth2Client(user.ctx).TokenSource(oauth2.NoContext, &oauth2.Token{AccessToken: ps.OAuthToken, Expiry: *ps.OAuthExpireDate, RefreshToken: ps.OAuthRefreshToken}).Token()
if err != nil {
if strings.Contains(err.Error(), "revoked") || strings.Contains(err.Error(), "invalid_grant") {
//remove stored OAuthToken
//todo: provide revoked callback
ps.OAuthToken = ""
ps.OAuthExpireDate = nil
user.saveProtectedSettings()
}
user.ctx.Log().WithError(err).Error("OAuth token refresh failed")
return ""
}
if token != nil {
ps.OAuthToken = token.AccessToken
if token.RefreshToken != "" {
ps.OAuthRefreshToken = token.RefreshToken
}
ps.OAuthExpireDate = &token.Expiry
user.saveProtectedSettings()
}
}
return ps.OAuthToken
}
return ""
}
|
go
|
func (user *User) OAuthToken() string {
// todo: oauthtoken per host?
/*
host := user.ctx.ServiceBaseURL.Host
if host == "" {
host = user.ctx.Service().DefaultBaseURL.Host
}
*/
ps, _ := user.protectedSettings()
if ps != nil {
if ps.OAuthExpireDate != nil && ps.OAuthExpireDate.Before(time.Now().Add(time.Second*5)) {
token, err := user.ctx.OAuthProvider().OAuth2Client(user.ctx).TokenSource(oauth2.NoContext, &oauth2.Token{AccessToken: ps.OAuthToken, Expiry: *ps.OAuthExpireDate, RefreshToken: ps.OAuthRefreshToken}).Token()
if err != nil {
if strings.Contains(err.Error(), "revoked") || strings.Contains(err.Error(), "invalid_grant") {
//remove stored OAuthToken
//todo: provide revoked callback
ps.OAuthToken = ""
ps.OAuthExpireDate = nil
user.saveProtectedSettings()
}
user.ctx.Log().WithError(err).Error("OAuth token refresh failed")
return ""
}
if token != nil {
ps.OAuthToken = token.AccessToken
if token.RefreshToken != "" {
ps.OAuthRefreshToken = token.RefreshToken
}
ps.OAuthExpireDate = &token.Expiry
user.saveProtectedSettings()
}
}
return ps.OAuthToken
}
return ""
}
|
[
"func",
"(",
"user",
"*",
"User",
")",
"OAuthToken",
"(",
")",
"string",
"{",
"// todo: oauthtoken per host?",
"/*\n\t\thost := user.ctx.ServiceBaseURL.Host\n\n\t\tif host == \"\" {\n\t\t\thost = user.ctx.Service().DefaultBaseURL.Host\n\t\t}\n\t*/",
"ps",
",",
"_",
":=",
"user",
".",
"protectedSettings",
"(",
")",
"\n\n",
"if",
"ps",
"!=",
"nil",
"{",
"if",
"ps",
".",
"OAuthExpireDate",
"!=",
"nil",
"&&",
"ps",
".",
"OAuthExpireDate",
".",
"Before",
"(",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"time",
".",
"Second",
"*",
"5",
")",
")",
"{",
"token",
",",
"err",
":=",
"user",
".",
"ctx",
".",
"OAuthProvider",
"(",
")",
".",
"OAuth2Client",
"(",
"user",
".",
"ctx",
")",
".",
"TokenSource",
"(",
"oauth2",
".",
"NoContext",
",",
"&",
"oauth2",
".",
"Token",
"{",
"AccessToken",
":",
"ps",
".",
"OAuthToken",
",",
"Expiry",
":",
"*",
"ps",
".",
"OAuthExpireDate",
",",
"RefreshToken",
":",
"ps",
".",
"OAuthRefreshToken",
"}",
")",
".",
"Token",
"(",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"strings",
".",
"Contains",
"(",
"err",
".",
"Error",
"(",
")",
",",
"\"",
"\"",
")",
"||",
"strings",
".",
"Contains",
"(",
"err",
".",
"Error",
"(",
")",
",",
"\"",
"\"",
")",
"{",
"//remove stored OAuthToken",
"//todo: provide revoked callback",
"ps",
".",
"OAuthToken",
"=",
"\"",
"\"",
"\n",
"ps",
".",
"OAuthExpireDate",
"=",
"nil",
"\n",
"user",
".",
"saveProtectedSettings",
"(",
")",
"\n",
"}",
"\n",
"user",
".",
"ctx",
".",
"Log",
"(",
")",
".",
"WithError",
"(",
"err",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"if",
"token",
"!=",
"nil",
"{",
"ps",
".",
"OAuthToken",
"=",
"token",
".",
"AccessToken",
"\n",
"if",
"token",
".",
"RefreshToken",
"!=",
"\"",
"\"",
"{",
"ps",
".",
"OAuthRefreshToken",
"=",
"token",
".",
"RefreshToken",
"\n",
"}",
"\n",
"ps",
".",
"OAuthExpireDate",
"=",
"&",
"token",
".",
"Expiry",
"\n",
"user",
".",
"saveProtectedSettings",
"(",
")",
"\n\n",
"}",
"\n\n",
"}",
"\n",
"return",
"ps",
".",
"OAuthToken",
"\n",
"}",
"\n\n",
"return",
"\"",
"\"",
"\n",
"}"
] |
// OAuthToken returns OAuthToken for service
|
[
"OAuthToken",
"returns",
"OAuthToken",
"for",
"service"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/data.go#L1083-L1125
|
train
|
requilence/integram
|
data.go
|
ResetOAuthToken
|
func (user *User) ResetOAuthToken() error {
err := user.saveProtectedSetting("OAuthToken", "")
if err != nil {
user.ctx.Log().WithError(err).Error("ResetOAuthToken error")
}
return err
}
|
go
|
func (user *User) ResetOAuthToken() error {
err := user.saveProtectedSetting("OAuthToken", "")
if err != nil {
user.ctx.Log().WithError(err).Error("ResetOAuthToken error")
}
return err
}
|
[
"func",
"(",
"user",
"*",
"User",
")",
"ResetOAuthToken",
"(",
")",
"error",
"{",
"err",
":=",
"user",
".",
"saveProtectedSetting",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"user",
".",
"ctx",
".",
"Log",
"(",
")",
".",
"WithError",
"(",
"err",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] |
// ResetOAuthToken reset OAuthToken for service
|
[
"ResetOAuthToken",
"reset",
"OAuthToken",
"for",
"service"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/data.go#L1128-L1134
|
train
|
requilence/integram
|
data.go
|
WebPreview
|
func (c *Context) WebPreview(title string, headline string, text string, serviceURL string, imageURL string) (WebPreviewURL string) {
token := rndStr.Get(10)
if title == "" {
title = c.Service().NameToPrint
c.Log().WithField("token", token).Warn("webPreview: title is empty")
}
if headline == "" {
c.Log().WithField("token", token).Warn("webPreview: headline is empty")
headline = "-"
}
wp := webPreview{
title,
headline,
text,
serviceURL,
imageURL,
token,
"",
0,
time.Now(),
}
wp.Hash = wp.CalculateHash()
var wpExists webPreview
c.db.C("previews").Find(bson.M{"hash": wp.Hash}).One(&wpExists)
if wpExists.Token != "" {
wp = wpExists
} else {
err := c.db.C("previews").Insert(wp)
if err != nil {
// Wow! So jackpot! Much collision
wp.Token = rndStr.Get(10)
err = c.db.C("previews").Insert(wp)
c.Log().WithError(err).Error("Can't add webpreview")
}
}
return Config.BaseURL + "/a/" + wp.Token
}
|
go
|
func (c *Context) WebPreview(title string, headline string, text string, serviceURL string, imageURL string) (WebPreviewURL string) {
token := rndStr.Get(10)
if title == "" {
title = c.Service().NameToPrint
c.Log().WithField("token", token).Warn("webPreview: title is empty")
}
if headline == "" {
c.Log().WithField("token", token).Warn("webPreview: headline is empty")
headline = "-"
}
wp := webPreview{
title,
headline,
text,
serviceURL,
imageURL,
token,
"",
0,
time.Now(),
}
wp.Hash = wp.CalculateHash()
var wpExists webPreview
c.db.C("previews").Find(bson.M{"hash": wp.Hash}).One(&wpExists)
if wpExists.Token != "" {
wp = wpExists
} else {
err := c.db.C("previews").Insert(wp)
if err != nil {
// Wow! So jackpot! Much collision
wp.Token = rndStr.Get(10)
err = c.db.C("previews").Insert(wp)
c.Log().WithError(err).Error("Can't add webpreview")
}
}
return Config.BaseURL + "/a/" + wp.Token
}
|
[
"func",
"(",
"c",
"*",
"Context",
")",
"WebPreview",
"(",
"title",
"string",
",",
"headline",
"string",
",",
"text",
"string",
",",
"serviceURL",
"string",
",",
"imageURL",
"string",
")",
"(",
"WebPreviewURL",
"string",
")",
"{",
"token",
":=",
"rndStr",
".",
"Get",
"(",
"10",
")",
"\n",
"if",
"title",
"==",
"\"",
"\"",
"{",
"title",
"=",
"c",
".",
"Service",
"(",
")",
".",
"NameToPrint",
"\n",
"c",
".",
"Log",
"(",
")",
".",
"WithField",
"(",
"\"",
"\"",
",",
"token",
")",
".",
"Warn",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"headline",
"==",
"\"",
"\"",
"{",
"c",
".",
"Log",
"(",
")",
".",
"WithField",
"(",
"\"",
"\"",
",",
"token",
")",
".",
"Warn",
"(",
"\"",
"\"",
")",
"\n",
"headline",
"=",
"\"",
"\"",
"\n\n",
"}",
"\n",
"wp",
":=",
"webPreview",
"{",
"title",
",",
"headline",
",",
"text",
",",
"serviceURL",
",",
"imageURL",
",",
"token",
",",
"\"",
"\"",
",",
"0",
",",
"time",
".",
"Now",
"(",
")",
",",
"}",
"\n\n",
"wp",
".",
"Hash",
"=",
"wp",
".",
"CalculateHash",
"(",
")",
"\n\n",
"var",
"wpExists",
"webPreview",
"\n",
"c",
".",
"db",
".",
"C",
"(",
"\"",
"\"",
")",
".",
"Find",
"(",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"wp",
".",
"Hash",
"}",
")",
".",
"One",
"(",
"&",
"wpExists",
")",
"\n\n",
"if",
"wpExists",
".",
"Token",
"!=",
"\"",
"\"",
"{",
"wp",
"=",
"wpExists",
"\n",
"}",
"else",
"{",
"err",
":=",
"c",
".",
"db",
".",
"C",
"(",
"\"",
"\"",
")",
".",
"Insert",
"(",
"wp",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"// Wow! So jackpot! Much collision",
"wp",
".",
"Token",
"=",
"rndStr",
".",
"Get",
"(",
"10",
")",
"\n",
"err",
"=",
"c",
".",
"db",
".",
"C",
"(",
"\"",
"\"",
")",
".",
"Insert",
"(",
"wp",
")",
"\n",
"c",
".",
"Log",
"(",
")",
".",
"WithError",
"(",
"err",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n\n",
"}",
"\n",
"}",
"\n\n",
"return",
"Config",
".",
"BaseURL",
"+",
"\"",
"\"",
"+",
"wp",
".",
"Token",
"\n\n",
"}"
] |
// WebPreview generate fake webpreview and store it in DB. Telegram will resolve it as we need
|
[
"WebPreview",
"generate",
"fake",
"webpreview",
"and",
"store",
"it",
"in",
"DB",
".",
"Telegram",
"will",
"resolve",
"it",
"as",
"we",
"need"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/data.go#L1188-L1233
|
train
|
requilence/integram
|
context.go
|
SetServiceBaseURL
|
func (c *Context) SetServiceBaseURL(domainOrURL string) {
u, _ := getBaseURL(domainOrURL)
if u != nil && u.Host != "" {
c.ServiceBaseURL = *u
} else if domainOrURL != "" {
c.ServiceBaseURL = url.URL{Scheme: "https", Host: domainOrURL}
} else {
c.Log().Error("Can't use SetServiceHostFromURL with empty arg")
}
}
|
go
|
func (c *Context) SetServiceBaseURL(domainOrURL string) {
u, _ := getBaseURL(domainOrURL)
if u != nil && u.Host != "" {
c.ServiceBaseURL = *u
} else if domainOrURL != "" {
c.ServiceBaseURL = url.URL{Scheme: "https", Host: domainOrURL}
} else {
c.Log().Error("Can't use SetServiceHostFromURL with empty arg")
}
}
|
[
"func",
"(",
"c",
"*",
"Context",
")",
"SetServiceBaseURL",
"(",
"domainOrURL",
"string",
")",
"{",
"u",
",",
"_",
":=",
"getBaseURL",
"(",
"domainOrURL",
")",
"\n\n",
"if",
"u",
"!=",
"nil",
"&&",
"u",
".",
"Host",
"!=",
"\"",
"\"",
"{",
"c",
".",
"ServiceBaseURL",
"=",
"*",
"u",
"\n",
"}",
"else",
"if",
"domainOrURL",
"!=",
"\"",
"\"",
"{",
"c",
".",
"ServiceBaseURL",
"=",
"url",
".",
"URL",
"{",
"Scheme",
":",
"\"",
"\"",
",",
"Host",
":",
"domainOrURL",
"}",
"\n",
"}",
"else",
"{",
"c",
".",
"Log",
"(",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}"
] |
// SetServiceBaseURL set the baseURL for the current request. Useful when service can be self-hosted. The actual service URL can be found in the incoming webhook
|
[
"SetServiceBaseURL",
"set",
"the",
"baseURL",
"for",
"the",
"current",
"request",
".",
"Useful",
"when",
"service",
"can",
"be",
"self",
"-",
"hosted",
".",
"The",
"actual",
"service",
"URL",
"can",
"be",
"found",
"in",
"the",
"incoming",
"webhook"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/context.go#L68-L78
|
train
|
requilence/integram
|
context.go
|
SaveOAuthProvider
|
func (c *Context) SaveOAuthProvider(baseURL url.URL, id string, secret string) (*OAuthProvider, error) {
if id == "" || secret == "" {
return nil, errors.New("id and secret must not be empty")
}
baseURL.Host = strings.ToLower(baseURL.Host)
provider := OAuthProvider{BaseURL: baseURL, ID: id, Secret: secret, Service: c.ServiceName}
//TODO: multiply installations on one host are not available
c.db.C("oauth_providers").UpsertId(provider.internalID(), provider.toBson())
return &provider, nil
}
|
go
|
func (c *Context) SaveOAuthProvider(baseURL url.URL, id string, secret string) (*OAuthProvider, error) {
if id == "" || secret == "" {
return nil, errors.New("id and secret must not be empty")
}
baseURL.Host = strings.ToLower(baseURL.Host)
provider := OAuthProvider{BaseURL: baseURL, ID: id, Secret: secret, Service: c.ServiceName}
//TODO: multiply installations on one host are not available
c.db.C("oauth_providers").UpsertId(provider.internalID(), provider.toBson())
return &provider, nil
}
|
[
"func",
"(",
"c",
"*",
"Context",
")",
"SaveOAuthProvider",
"(",
"baseURL",
"url",
".",
"URL",
",",
"id",
"string",
",",
"secret",
"string",
")",
"(",
"*",
"OAuthProvider",
",",
"error",
")",
"{",
"if",
"id",
"==",
"\"",
"\"",
"||",
"secret",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"baseURL",
".",
"Host",
"=",
"strings",
".",
"ToLower",
"(",
"baseURL",
".",
"Host",
")",
"\n\n",
"provider",
":=",
"OAuthProvider",
"{",
"BaseURL",
":",
"baseURL",
",",
"ID",
":",
"id",
",",
"Secret",
":",
"secret",
",",
"Service",
":",
"c",
".",
"ServiceName",
"}",
"\n",
"//TODO: multiply installations on one host are not available",
"c",
".",
"db",
".",
"C",
"(",
"\"",
"\"",
")",
".",
"UpsertId",
"(",
"provider",
".",
"internalID",
"(",
")",
",",
"provider",
".",
"toBson",
"(",
")",
")",
"\n\n",
"return",
"&",
"provider",
",",
"nil",
"\n",
"}"
] |
// SaveOAuthProvider add the OAuth client to DB. Useful when the new OAuth provider registred for self-hosted services
|
[
"SaveOAuthProvider",
"add",
"the",
"OAuth",
"client",
"to",
"DB",
".",
"Useful",
"when",
"the",
"new",
"OAuth",
"provider",
"registred",
"for",
"self",
"-",
"hosted",
"services"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/context.go#L81-L93
|
train
|
requilence/integram
|
context.go
|
OAuthProvider
|
func (c *Context) OAuthProvider() *OAuthProvider {
service := c.Service()
if c.ServiceBaseURL.Host == "" || c.ServiceBaseURL.Host == service.DefaultBaseURL.Host {
return service.DefaultOAuthProvider()
} else if c.ServiceBaseURL.Host != "" {
p, _ := findOauthProviderByHost(c.db, c.ServiceBaseURL.Host)
if p == nil {
p = &OAuthProvider{BaseURL: c.ServiceBaseURL, Service: c.ServiceName}
}
/*if err != nil {
c.Log().WithError(err).WithField("host", c.ServiceBaseURL.Host).Error("Can't get OAuthProvider")
}*/
return p
}
c.Log().Error("Can't get OAuthProvider – empty ServiceBaseURL")
return nil
}
|
go
|
func (c *Context) OAuthProvider() *OAuthProvider {
service := c.Service()
if c.ServiceBaseURL.Host == "" || c.ServiceBaseURL.Host == service.DefaultBaseURL.Host {
return service.DefaultOAuthProvider()
} else if c.ServiceBaseURL.Host != "" {
p, _ := findOauthProviderByHost(c.db, c.ServiceBaseURL.Host)
if p == nil {
p = &OAuthProvider{BaseURL: c.ServiceBaseURL, Service: c.ServiceName}
}
/*if err != nil {
c.Log().WithError(err).WithField("host", c.ServiceBaseURL.Host).Error("Can't get OAuthProvider")
}*/
return p
}
c.Log().Error("Can't get OAuthProvider – empty ServiceBaseURL")
return nil
}
|
[
"func",
"(",
"c",
"*",
"Context",
")",
"OAuthProvider",
"(",
")",
"*",
"OAuthProvider",
"{",
"service",
":=",
"c",
".",
"Service",
"(",
")",
"\n",
"if",
"c",
".",
"ServiceBaseURL",
".",
"Host",
"==",
"\"",
"\"",
"||",
"c",
".",
"ServiceBaseURL",
".",
"Host",
"==",
"service",
".",
"DefaultBaseURL",
".",
"Host",
"{",
"return",
"service",
".",
"DefaultOAuthProvider",
"(",
")",
"\n",
"}",
"else",
"if",
"c",
".",
"ServiceBaseURL",
".",
"Host",
"!=",
"\"",
"\"",
"{",
"p",
",",
"_",
":=",
"findOauthProviderByHost",
"(",
"c",
".",
"db",
",",
"c",
".",
"ServiceBaseURL",
".",
"Host",
")",
"\n",
"if",
"p",
"==",
"nil",
"{",
"p",
"=",
"&",
"OAuthProvider",
"{",
"BaseURL",
":",
"c",
".",
"ServiceBaseURL",
",",
"Service",
":",
"c",
".",
"ServiceName",
"}",
"\n",
"}",
"\n",
"/*if err != nil {\n\t\t\tc.Log().WithError(err).WithField(\"host\", c.ServiceBaseURL.Host).Error(\"Can't get OAuthProvider\")\n\t\t}*/",
"return",
"p",
"\n",
"}",
"\n",
"c",
".",
"Log",
"(",
")",
".",
"Error",
"(",
"\"",
"",
"",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// OAuthProvider details. Useful for services that can be installed on your own side
|
[
"OAuthProvider",
"details",
".",
"Useful",
"for",
"services",
"that",
"can",
"be",
"installed",
"on",
"your",
"own",
"side"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/context.go#L96-L116
|
train
|
requilence/integram
|
context.go
|
OAuth1Client
|
func (o *OAuthProvider) OAuth1Client(c *Context) *oauth.Consumer {
if o.ID == "" {
log.Error(errors.New("Can't get OAuth1Client – ID not set"))
return nil
}
service := c.Service()
config := service.DefaultOAuth1
if config.AccessTokenReceiver == nil {
log.Error(errors.New("Can't get OAuth1Client – AccessTokenReceiver not set"))
return nil
}
config.Key = o.ID
config.Secret = o.Secret
config.AccessTokenURL = replaceBaseURL(config.AccessTokenURL, o.BaseURL)
config.AuthorizeTokenURL = replaceBaseURL(config.AuthorizeTokenURL, o.BaseURL)
config.RequestTokenURL = replaceBaseURL(config.RequestTokenURL, o.BaseURL)
consumer := oauth.NewConsumer(
o.ID,
o.Secret,
oauth.ServiceProvider{
RequestTokenUrl: config.RequestTokenURL,
AuthorizeTokenUrl: config.AuthorizeTokenURL,
AccessTokenUrl: config.AccessTokenURL,
},
)
consumer.AdditionalAuthorizationUrlParams = service.DefaultOAuth1.AdditionalAuthorizationURLParams
return consumer
}
|
go
|
func (o *OAuthProvider) OAuth1Client(c *Context) *oauth.Consumer {
if o.ID == "" {
log.Error(errors.New("Can't get OAuth1Client – ID not set"))
return nil
}
service := c.Service()
config := service.DefaultOAuth1
if config.AccessTokenReceiver == nil {
log.Error(errors.New("Can't get OAuth1Client – AccessTokenReceiver not set"))
return nil
}
config.Key = o.ID
config.Secret = o.Secret
config.AccessTokenURL = replaceBaseURL(config.AccessTokenURL, o.BaseURL)
config.AuthorizeTokenURL = replaceBaseURL(config.AuthorizeTokenURL, o.BaseURL)
config.RequestTokenURL = replaceBaseURL(config.RequestTokenURL, o.BaseURL)
consumer := oauth.NewConsumer(
o.ID,
o.Secret,
oauth.ServiceProvider{
RequestTokenUrl: config.RequestTokenURL,
AuthorizeTokenUrl: config.AuthorizeTokenURL,
AccessTokenUrl: config.AccessTokenURL,
},
)
consumer.AdditionalAuthorizationUrlParams = service.DefaultOAuth1.AdditionalAuthorizationURLParams
return consumer
}
|
[
"func",
"(",
"o",
"*",
"OAuthProvider",
")",
"OAuth1Client",
"(",
"c",
"*",
"Context",
")",
"*",
"oauth",
".",
"Consumer",
"{",
"if",
"o",
".",
"ID",
"==",
"\"",
"\"",
"{",
"log",
".",
"Error",
"(",
"errors",
".",
"New",
"(",
"\"",
")",
"",
"",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"service",
":=",
"c",
".",
"Service",
"(",
")",
"\n",
"config",
":=",
"service",
".",
"DefaultOAuth1",
"\n\n",
"if",
"config",
".",
"AccessTokenReceiver",
"==",
"nil",
"{",
"log",
".",
"Error",
"(",
"errors",
".",
"New",
"(",
"\"",
")",
"",
"",
"\n\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"config",
".",
"Key",
"=",
"o",
".",
"ID",
"\n",
"config",
".",
"Secret",
"=",
"o",
".",
"Secret",
"\n",
"config",
".",
"AccessTokenURL",
"=",
"replaceBaseURL",
"(",
"config",
".",
"AccessTokenURL",
",",
"o",
".",
"BaseURL",
")",
"\n",
"config",
".",
"AuthorizeTokenURL",
"=",
"replaceBaseURL",
"(",
"config",
".",
"AuthorizeTokenURL",
",",
"o",
".",
"BaseURL",
")",
"\n",
"config",
".",
"RequestTokenURL",
"=",
"replaceBaseURL",
"(",
"config",
".",
"RequestTokenURL",
",",
"o",
".",
"BaseURL",
")",
"\n\n",
"consumer",
":=",
"oauth",
".",
"NewConsumer",
"(",
"o",
".",
"ID",
",",
"o",
".",
"Secret",
",",
"oauth",
".",
"ServiceProvider",
"{",
"RequestTokenUrl",
":",
"config",
".",
"RequestTokenURL",
",",
"AuthorizeTokenUrl",
":",
"config",
".",
"AuthorizeTokenURL",
",",
"AccessTokenUrl",
":",
"config",
".",
"AccessTokenURL",
",",
"}",
",",
")",
"\n",
"consumer",
".",
"AdditionalAuthorizationUrlParams",
"=",
"service",
".",
"DefaultOAuth1",
".",
"AdditionalAuthorizationURLParams",
"\n",
"return",
"consumer",
"\n",
"}"
] |
// OAuth1Client returns oauth.Consumer using OAuthProvider details
|
[
"OAuth1Client",
"returns",
"oauth",
".",
"Consumer",
"using",
"OAuthProvider",
"details"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/context.go#L134-L167
|
train
|
requilence/integram
|
context.go
|
OAuth2Client
|
func (o *OAuthProvider) OAuth2Client(c *Context) *oauth2.Config {
if o.ID == "" {
return nil
}
service := c.Service()
if service.DefaultOAuth2 == nil {
return nil
}
config := service.DefaultOAuth2.Config
config.ClientID = o.ID
config.ClientSecret = o.Secret
if c.User.ID != 0 {
config.RedirectURL = c.User.OauthRedirectURL()
}
config.Endpoint = oauth2.Endpoint{
AuthURL: replaceBaseURL(config.Endpoint.AuthURL, o.BaseURL),
TokenURL: replaceBaseURL(config.Endpoint.TokenURL, o.BaseURL),
}
return &config
}
|
go
|
func (o *OAuthProvider) OAuth2Client(c *Context) *oauth2.Config {
if o.ID == "" {
return nil
}
service := c.Service()
if service.DefaultOAuth2 == nil {
return nil
}
config := service.DefaultOAuth2.Config
config.ClientID = o.ID
config.ClientSecret = o.Secret
if c.User.ID != 0 {
config.RedirectURL = c.User.OauthRedirectURL()
}
config.Endpoint = oauth2.Endpoint{
AuthURL: replaceBaseURL(config.Endpoint.AuthURL, o.BaseURL),
TokenURL: replaceBaseURL(config.Endpoint.TokenURL, o.BaseURL),
}
return &config
}
|
[
"func",
"(",
"o",
"*",
"OAuthProvider",
")",
"OAuth2Client",
"(",
"c",
"*",
"Context",
")",
"*",
"oauth2",
".",
"Config",
"{",
"if",
"o",
".",
"ID",
"==",
"\"",
"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"service",
":=",
"c",
".",
"Service",
"(",
")",
"\n\n",
"if",
"service",
".",
"DefaultOAuth2",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"config",
":=",
"service",
".",
"DefaultOAuth2",
".",
"Config",
"\n\n",
"config",
".",
"ClientID",
"=",
"o",
".",
"ID",
"\n",
"config",
".",
"ClientSecret",
"=",
"o",
".",
"Secret",
"\n",
"if",
"c",
".",
"User",
".",
"ID",
"!=",
"0",
"{",
"config",
".",
"RedirectURL",
"=",
"c",
".",
"User",
".",
"OauthRedirectURL",
"(",
")",
"\n",
"}",
"\n\n",
"config",
".",
"Endpoint",
"=",
"oauth2",
".",
"Endpoint",
"{",
"AuthURL",
":",
"replaceBaseURL",
"(",
"config",
".",
"Endpoint",
".",
"AuthURL",
",",
"o",
".",
"BaseURL",
")",
",",
"TokenURL",
":",
"replaceBaseURL",
"(",
"config",
".",
"Endpoint",
".",
"TokenURL",
",",
"o",
".",
"BaseURL",
")",
",",
"}",
"\n\n",
"return",
"&",
"config",
"\n",
"}"
] |
// OAuth2Client returns oauth2.Config using OAuthProvider details
|
[
"OAuth2Client",
"returns",
"oauth2",
".",
"Config",
"using",
"OAuthProvider",
"details"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/context.go#L170-L196
|
train
|
requilence/integram
|
context.go
|
Param
|
func (wc *WebhookContext) Param(s string) string {
return wc.gin.Param(s)
}
|
go
|
func (wc *WebhookContext) Param(s string) string {
return wc.gin.Param(s)
}
|
[
"func",
"(",
"wc",
"*",
"WebhookContext",
")",
"Param",
"(",
"s",
"string",
")",
"string",
"{",
"return",
"wc",
".",
"gin",
".",
"Param",
"(",
"s",
")",
"\n",
"}"
] |
// Param return param from url
|
[
"Param",
"return",
"param",
"from",
"url"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/context.go#L213-L215
|
train
|
requilence/integram
|
context.go
|
Headers
|
func (wc *WebhookContext) Headers() map[string][]string {
return map[string][]string(wc.gin.Request.Header)
}
|
go
|
func (wc *WebhookContext) Headers() map[string][]string {
return map[string][]string(wc.gin.Request.Header)
}
|
[
"func",
"(",
"wc",
"*",
"WebhookContext",
")",
"Headers",
"(",
")",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
"{",
"return",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
"(",
"wc",
".",
"gin",
".",
"Request",
".",
"Header",
")",
"\n",
"}"
] |
// Headers returns the headers of request
|
[
"Headers",
"returns",
"the",
"headers",
"of",
"request"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/context.go#L239-L241
|
train
|
requilence/integram
|
context.go
|
Redirect
|
func (wc *WebhookContext) Redirect(code int, s string) {
wc.gin.Redirect(code, s)
}
|
go
|
func (wc *WebhookContext) Redirect(code int, s string) {
wc.gin.Redirect(code, s)
}
|
[
"func",
"(",
"wc",
"*",
"WebhookContext",
")",
"Redirect",
"(",
"code",
"int",
",",
"s",
"string",
")",
"{",
"wc",
".",
"gin",
".",
"Redirect",
"(",
"code",
",",
"s",
")",
"\n",
"}"
] |
// Redirect send the Location header
|
[
"Redirect",
"send",
"the",
"Location",
"header"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/context.go#L254-L256
|
train
|
requilence/integram
|
context.go
|
KeyboardAnswer
|
func (c *Context) KeyboardAnswer() (data string, buttonText string) {
keyboard, err := c.keyboard()
if err != nil || keyboard.ChatID == 0 {
log.WithError(err).Error("Can't get stored keyboard")
return
}
// In group chat keyboard answer always include msg_id of original message that generate this keyboard
if c.Chat.ID < 0 && c.Message.ReplyToMsgID != keyboard.MsgID {
return
}
if c.Message.Text == "" {
return
}
var ok bool
if data, ok = keyboard.Keyboard[checksumString(c.Message.Text)]; ok {
buttonText = c.Message.Text
log.Debugf("button pressed [%v], %v\n", data, c.Message.Text)
}
return
}
|
go
|
func (c *Context) KeyboardAnswer() (data string, buttonText string) {
keyboard, err := c.keyboard()
if err != nil || keyboard.ChatID == 0 {
log.WithError(err).Error("Can't get stored keyboard")
return
}
// In group chat keyboard answer always include msg_id of original message that generate this keyboard
if c.Chat.ID < 0 && c.Message.ReplyToMsgID != keyboard.MsgID {
return
}
if c.Message.Text == "" {
return
}
var ok bool
if data, ok = keyboard.Keyboard[checksumString(c.Message.Text)]; ok {
buttonText = c.Message.Text
log.Debugf("button pressed [%v], %v\n", data, c.Message.Text)
}
return
}
|
[
"func",
"(",
"c",
"*",
"Context",
")",
"KeyboardAnswer",
"(",
")",
"(",
"data",
"string",
",",
"buttonText",
"string",
")",
"{",
"keyboard",
",",
"err",
":=",
"c",
".",
"keyboard",
"(",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"||",
"keyboard",
".",
"ChatID",
"==",
"0",
"{",
"log",
".",
"WithError",
"(",
"err",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// In group chat keyboard answer always include msg_id of original message that generate this keyboard",
"if",
"c",
".",
"Chat",
".",
"ID",
"<",
"0",
"&&",
"c",
".",
"Message",
".",
"ReplyToMsgID",
"!=",
"keyboard",
".",
"MsgID",
"{",
"return",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"Message",
".",
"Text",
"==",
"\"",
"\"",
"{",
"return",
"\n",
"}",
"\n\n",
"var",
"ok",
"bool",
"\n\n",
"if",
"data",
",",
"ok",
"=",
"keyboard",
".",
"Keyboard",
"[",
"checksumString",
"(",
"c",
".",
"Message",
".",
"Text",
")",
"]",
";",
"ok",
"{",
"buttonText",
"=",
"c",
".",
"Message",
".",
"Text",
"\n",
"log",
".",
"Debugf",
"(",
"\"",
"\\n",
"\"",
",",
"data",
",",
"c",
".",
"Message",
".",
"Text",
")",
"\n",
"}",
"\n\n",
"return",
"\n\n",
"}"
] |
// KeyboardAnswer retrieve the data related to pressed button
// buttonText will be returned only in case this button relates to the one in db for this chat
|
[
"KeyboardAnswer",
"retrieve",
"the",
"data",
"related",
"to",
"pressed",
"button",
"buttonText",
"will",
"be",
"returned",
"only",
"in",
"case",
"this",
"button",
"relates",
"to",
"the",
"one",
"in",
"db",
"for",
"this",
"chat"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/context.go#L260-L286
|
train
|
requilence/integram
|
context.go
|
keyboard
|
func (c *Context) keyboard() (chatKeyboard, error) {
udata, _ := c.User.getData()
chatID := c.Chat.ID
for _, kb := range udata.KeyboardPerChat {
if kb.ChatID == chatID && kb.BotID == c.Bot().ID {
return kb, nil
}
}
cdata, _ := c.Chat.getData()
for _, kb := range cdata.KeyboardPerBot {
if kb.ChatID == chatID && kb.BotID == c.Bot().ID {
return kb, nil
}
}
return chatKeyboard{}, nil
}
|
go
|
func (c *Context) keyboard() (chatKeyboard, error) {
udata, _ := c.User.getData()
chatID := c.Chat.ID
for _, kb := range udata.KeyboardPerChat {
if kb.ChatID == chatID && kb.BotID == c.Bot().ID {
return kb, nil
}
}
cdata, _ := c.Chat.getData()
for _, kb := range cdata.KeyboardPerBot {
if kb.ChatID == chatID && kb.BotID == c.Bot().ID {
return kb, nil
}
}
return chatKeyboard{}, nil
}
|
[
"func",
"(",
"c",
"*",
"Context",
")",
"keyboard",
"(",
")",
"(",
"chatKeyboard",
",",
"error",
")",
"{",
"udata",
",",
"_",
":=",
"c",
".",
"User",
".",
"getData",
"(",
")",
"\n",
"chatID",
":=",
"c",
".",
"Chat",
".",
"ID",
"\n\n",
"for",
"_",
",",
"kb",
":=",
"range",
"udata",
".",
"KeyboardPerChat",
"{",
"if",
"kb",
".",
"ChatID",
"==",
"chatID",
"&&",
"kb",
".",
"BotID",
"==",
"c",
".",
"Bot",
"(",
")",
".",
"ID",
"{",
"return",
"kb",
",",
"nil",
"\n",
"}",
"\n\n",
"}",
"\n\n",
"cdata",
",",
"_",
":=",
"c",
".",
"Chat",
".",
"getData",
"(",
")",
"\n\n",
"for",
"_",
",",
"kb",
":=",
"range",
"cdata",
".",
"KeyboardPerBot",
"{",
"if",
"kb",
".",
"ChatID",
"==",
"chatID",
"&&",
"kb",
".",
"BotID",
"==",
"c",
".",
"Bot",
"(",
")",
".",
"ID",
"{",
"return",
"kb",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"chatKeyboard",
"{",
"}",
",",
"nil",
"\n",
"}"
] |
// Keyboard retrieve keyboard for the current chat if set otherwise empty keyboard is returned
|
[
"Keyboard",
"retrieve",
"keyboard",
"for",
"the",
"current",
"chat",
"if",
"set",
"otherwise",
"empty",
"keyboard",
"is",
"returned"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/context.go#L351-L372
|
train
|
requilence/integram
|
context.go
|
Log
|
func (c *Context) Log() *log.Entry {
fields := log.Fields{"service": c.ServiceName}
if Config.Debug {
pc := make([]uintptr, 10)
runtime.Callers(2, pc)
f := runtime.FuncForPC(pc[0])
fields["file"], fields["line"] = f.FileLine(pc[0])
fields["func"] = f.Name()
}
if c.User.ID > 0 {
fields["user"] = c.User.ID
}
if c.Chat.ID != 0 {
fields["chat"] = c.Chat.ID
}
if c.Message != nil {
fields["msg"] = c.Message.GetTextHash()
}
if c.ChosenInlineResult != nil {
fields["chosenresult"] = c.ChosenInlineResult
}
if c.InlineQuery != nil {
fields["inlinequery"] = c.InlineQuery
}
if c.Callback != nil {
fields["callback"] = c.Callback.Data
fields["callback_id"] = c.Callback.ID
if c.Callback.Message.MsgID > 0 {
fields["callback_msgid"] = c.Callback.Message.MsgID
} else {
fields["callback_inlinemsgid"] = c.Callback.Message.InlineMsgID
}
}
if c.gin != nil {
fields["url"] = c.gin.Request.Method + " " + c.gin.Request.URL.String()
fields["ip"] = c.gin.Request.RemoteAddr
}
fields["domain"] = c.ServiceBaseURL.Host
return log.WithFields(fields)
}
|
go
|
func (c *Context) Log() *log.Entry {
fields := log.Fields{"service": c.ServiceName}
if Config.Debug {
pc := make([]uintptr, 10)
runtime.Callers(2, pc)
f := runtime.FuncForPC(pc[0])
fields["file"], fields["line"] = f.FileLine(pc[0])
fields["func"] = f.Name()
}
if c.User.ID > 0 {
fields["user"] = c.User.ID
}
if c.Chat.ID != 0 {
fields["chat"] = c.Chat.ID
}
if c.Message != nil {
fields["msg"] = c.Message.GetTextHash()
}
if c.ChosenInlineResult != nil {
fields["chosenresult"] = c.ChosenInlineResult
}
if c.InlineQuery != nil {
fields["inlinequery"] = c.InlineQuery
}
if c.Callback != nil {
fields["callback"] = c.Callback.Data
fields["callback_id"] = c.Callback.ID
if c.Callback.Message.MsgID > 0 {
fields["callback_msgid"] = c.Callback.Message.MsgID
} else {
fields["callback_inlinemsgid"] = c.Callback.Message.InlineMsgID
}
}
if c.gin != nil {
fields["url"] = c.gin.Request.Method + " " + c.gin.Request.URL.String()
fields["ip"] = c.gin.Request.RemoteAddr
}
fields["domain"] = c.ServiceBaseURL.Host
return log.WithFields(fields)
}
|
[
"func",
"(",
"c",
"*",
"Context",
")",
"Log",
"(",
")",
"*",
"log",
".",
"Entry",
"{",
"fields",
":=",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"c",
".",
"ServiceName",
"}",
"\n\n",
"if",
"Config",
".",
"Debug",
"{",
"pc",
":=",
"make",
"(",
"[",
"]",
"uintptr",
",",
"10",
")",
"\n",
"runtime",
".",
"Callers",
"(",
"2",
",",
"pc",
")",
"\n",
"f",
":=",
"runtime",
".",
"FuncForPC",
"(",
"pc",
"[",
"0",
"]",
")",
"\n",
"fields",
"[",
"\"",
"\"",
"]",
",",
"fields",
"[",
"\"",
"\"",
"]",
"=",
"f",
".",
"FileLine",
"(",
"pc",
"[",
"0",
"]",
")",
"\n",
"fields",
"[",
"\"",
"\"",
"]",
"=",
"f",
".",
"Name",
"(",
")",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"User",
".",
"ID",
">",
"0",
"{",
"fields",
"[",
"\"",
"\"",
"]",
"=",
"c",
".",
"User",
".",
"ID",
"\n",
"}",
"\n",
"if",
"c",
".",
"Chat",
".",
"ID",
"!=",
"0",
"{",
"fields",
"[",
"\"",
"\"",
"]",
"=",
"c",
".",
"Chat",
".",
"ID",
"\n",
"}",
"\n",
"if",
"c",
".",
"Message",
"!=",
"nil",
"{",
"fields",
"[",
"\"",
"\"",
"]",
"=",
"c",
".",
"Message",
".",
"GetTextHash",
"(",
")",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"ChosenInlineResult",
"!=",
"nil",
"{",
"fields",
"[",
"\"",
"\"",
"]",
"=",
"c",
".",
"ChosenInlineResult",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"InlineQuery",
"!=",
"nil",
"{",
"fields",
"[",
"\"",
"\"",
"]",
"=",
"c",
".",
"InlineQuery",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"Callback",
"!=",
"nil",
"{",
"fields",
"[",
"\"",
"\"",
"]",
"=",
"c",
".",
"Callback",
".",
"Data",
"\n",
"fields",
"[",
"\"",
"\"",
"]",
"=",
"c",
".",
"Callback",
".",
"ID",
"\n\n",
"if",
"c",
".",
"Callback",
".",
"Message",
".",
"MsgID",
">",
"0",
"{",
"fields",
"[",
"\"",
"\"",
"]",
"=",
"c",
".",
"Callback",
".",
"Message",
".",
"MsgID",
"\n",
"}",
"else",
"{",
"fields",
"[",
"\"",
"\"",
"]",
"=",
"c",
".",
"Callback",
".",
"Message",
".",
"InlineMsgID",
"\n",
"}",
"\n\n",
"}",
"\n\n",
"if",
"c",
".",
"gin",
"!=",
"nil",
"{",
"fields",
"[",
"\"",
"\"",
"]",
"=",
"c",
".",
"gin",
".",
"Request",
".",
"Method",
"+",
"\"",
"\"",
"+",
"c",
".",
"gin",
".",
"Request",
".",
"URL",
".",
"String",
"(",
")",
"\n",
"fields",
"[",
"\"",
"\"",
"]",
"=",
"c",
".",
"gin",
".",
"Request",
".",
"RemoteAddr",
"\n",
"}",
"\n\n",
"fields",
"[",
"\"",
"\"",
"]",
"=",
"c",
".",
"ServiceBaseURL",
".",
"Host",
"\n\n",
"return",
"log",
".",
"WithFields",
"(",
"fields",
")",
"\n",
"}"
] |
// Log creates the logrus entry and attach corresponding info from the context
|
[
"Log",
"creates",
"the",
"logrus",
"entry",
"and",
"attach",
"corresponding",
"info",
"from",
"the",
"context"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/context.go#L375-L424
|
train
|
requilence/integram
|
context.go
|
Service
|
func (c *Context) Service() *Service {
s, _ := serviceByName(c.ServiceName)
return s
}
|
go
|
func (c *Context) Service() *Service {
s, _ := serviceByName(c.ServiceName)
return s
}
|
[
"func",
"(",
"c",
"*",
"Context",
")",
"Service",
"(",
")",
"*",
"Service",
"{",
"s",
",",
"_",
":=",
"serviceByName",
"(",
"c",
".",
"ServiceName",
")",
"\n",
"return",
"s",
"\n",
"}"
] |
// Service related to the current context
|
[
"Service",
"related",
"to",
"the",
"current",
"context"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/context.go#L432-L435
|
train
|
requilence/integram
|
context.go
|
EditPressedMessageText
|
func (c *Context) EditPressedMessageText(text string) error {
if c.Callback == nil {
return errors.New("EditPressedMessageText: Callback is not presented")
}
return c.EditMessageText(c.Callback.Message, text)
}
|
go
|
func (c *Context) EditPressedMessageText(text string) error {
if c.Callback == nil {
return errors.New("EditPressedMessageText: Callback is not presented")
}
return c.EditMessageText(c.Callback.Message, text)
}
|
[
"func",
"(",
"c",
"*",
"Context",
")",
"EditPressedMessageText",
"(",
"text",
"string",
")",
"error",
"{",
"if",
"c",
".",
"Callback",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"c",
".",
"EditMessageText",
"(",
"c",
".",
"Callback",
".",
"Message",
",",
"text",
")",
"\n",
"}"
] |
// EditPressedMessageText edit the text in the msg where user taped it in case this request is triggered by inlineButton callback
|
[
"EditPressedMessageText",
"edit",
"the",
"text",
"in",
"the",
"msg",
"where",
"user",
"taped",
"it",
"in",
"case",
"this",
"request",
"is",
"triggered",
"by",
"inlineButton",
"callback"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/context.go#L443-L449
|
train
|
requilence/integram
|
context.go
|
EditPressedMessageTextAndInlineKeyboard
|
func (c *Context) EditPressedMessageTextAndInlineKeyboard(text string, kb InlineKeyboard) error {
if c.Callback == nil {
return errors.New("EditPressedMessageTextAndInlineKeyboard: Callback is not presented")
}
return c.EditMessageTextAndInlineKeyboard(c.Callback.Message, c.Callback.Message.InlineKeyboardMarkup.State, text, kb)
}
|
go
|
func (c *Context) EditPressedMessageTextAndInlineKeyboard(text string, kb InlineKeyboard) error {
if c.Callback == nil {
return errors.New("EditPressedMessageTextAndInlineKeyboard: Callback is not presented")
}
return c.EditMessageTextAndInlineKeyboard(c.Callback.Message, c.Callback.Message.InlineKeyboardMarkup.State, text, kb)
}
|
[
"func",
"(",
"c",
"*",
"Context",
")",
"EditPressedMessageTextAndInlineKeyboard",
"(",
"text",
"string",
",",
"kb",
"InlineKeyboard",
")",
"error",
"{",
"if",
"c",
".",
"Callback",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"c",
".",
"EditMessageTextAndInlineKeyboard",
"(",
"c",
".",
"Callback",
".",
"Message",
",",
"c",
".",
"Callback",
".",
"Message",
".",
"InlineKeyboardMarkup",
".",
"State",
",",
"text",
",",
"kb",
")",
"\n",
"}"
] |
// EditPressedMessageTextAndInlineKeyboard edit the text and inline keyboard in the msg where user taped it in case this request is triggered by inlineButton callback
|
[
"EditPressedMessageTextAndInlineKeyboard",
"edit",
"the",
"text",
"and",
"inline",
"keyboard",
"in",
"the",
"msg",
"where",
"user",
"taped",
"it",
"in",
"case",
"this",
"request",
"is",
"triggered",
"by",
"inlineButton",
"callback"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/context.go#L452-L458
|
train
|
requilence/integram
|
context.go
|
EditPressedInlineKeyboard
|
func (c *Context) EditPressedInlineKeyboard(kb InlineKeyboard) error {
if c.Callback == nil {
return errors.New("EditPressedInlineKeyboard: Callback is not presented")
}
return c.EditInlineKeyboard(c.Callback.Message, c.Callback.Message.InlineKeyboardMarkup.State, kb)
}
|
go
|
func (c *Context) EditPressedInlineKeyboard(kb InlineKeyboard) error {
if c.Callback == nil {
return errors.New("EditPressedInlineKeyboard: Callback is not presented")
}
return c.EditInlineKeyboard(c.Callback.Message, c.Callback.Message.InlineKeyboardMarkup.State, kb)
}
|
[
"func",
"(",
"c",
"*",
"Context",
")",
"EditPressedInlineKeyboard",
"(",
"kb",
"InlineKeyboard",
")",
"error",
"{",
"if",
"c",
".",
"Callback",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"c",
".",
"EditInlineKeyboard",
"(",
"c",
".",
"Callback",
".",
"Message",
",",
"c",
".",
"Callback",
".",
"Message",
".",
"InlineKeyboardMarkup",
".",
"State",
",",
"kb",
")",
"\n",
"}"
] |
// EditPressedInlineKeyboard edit the inline keyboard in the msg where user taped it in case this request is triggered by inlineButton callback
|
[
"EditPressedInlineKeyboard",
"edit",
"the",
"inline",
"keyboard",
"in",
"the",
"msg",
"where",
"user",
"taped",
"it",
"in",
"case",
"this",
"request",
"is",
"triggered",
"by",
"inlineButton",
"callback"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/context.go#L461-L467
|
train
|
requilence/integram
|
context.go
|
EditPressedInlineButton
|
func (c *Context) EditPressedInlineButton(newState int, newText string) error {
log.WithField("newText", newText).WithField("newState", newState).Info("EditPressedInlineButton")
if c.Callback == nil {
return errors.New("EditPressedInlineButton: Callback is not presented")
}
return c.EditInlineStateButton(c.Callback.Message, c.Callback.Message.InlineKeyboardMarkup.State, c.Callback.State, c.Callback.Data, newState, newText)
}
|
go
|
func (c *Context) EditPressedInlineButton(newState int, newText string) error {
log.WithField("newText", newText).WithField("newState", newState).Info("EditPressedInlineButton")
if c.Callback == nil {
return errors.New("EditPressedInlineButton: Callback is not presented")
}
return c.EditInlineStateButton(c.Callback.Message, c.Callback.Message.InlineKeyboardMarkup.State, c.Callback.State, c.Callback.Data, newState, newText)
}
|
[
"func",
"(",
"c",
"*",
"Context",
")",
"EditPressedInlineButton",
"(",
"newState",
"int",
",",
"newText",
"string",
")",
"error",
"{",
"log",
".",
"WithField",
"(",
"\"",
"\"",
",",
"newText",
")",
".",
"WithField",
"(",
"\"",
"\"",
",",
"newState",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"if",
"c",
".",
"Callback",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"c",
".",
"EditInlineStateButton",
"(",
"c",
".",
"Callback",
".",
"Message",
",",
"c",
".",
"Callback",
".",
"Message",
".",
"InlineKeyboardMarkup",
".",
"State",
",",
"c",
".",
"Callback",
".",
"State",
",",
"c",
".",
"Callback",
".",
"Data",
",",
"newState",
",",
"newText",
")",
"\n",
"}"
] |
// EditPressedInlineButton edit the text and state of pressed inline button in case this request is triggered by inlineButton callback
|
[
"EditPressedInlineButton",
"edit",
"the",
"text",
"and",
"state",
"of",
"pressed",
"inline",
"button",
"in",
"case",
"this",
"request",
"is",
"triggered",
"by",
"inlineButton",
"callback"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/context.go#L470-L477
|
train
|
requilence/integram
|
context.go
|
EditMessageText
|
func (c *Context) EditMessageText(om *OutgoingMessage, text string) error {
if om == nil {
return errors.New("Empty message provided")
}
bot := c.Bot()
if om.ParseMode == "HTML" {
textCleared, err := sanitize.HTMLAllowing(text, []string{"a", "b", "strong", "i", "em", "a", "code", "pre"}, []string{"href"})
if err == nil && textCleared != "" {
text = textCleared
}
}
om.Text = text
prevTextHash := om.TextHash
om.TextHash = om.GetTextHash()
if om.TextHash == prevTextHash {
c.Log().Debugf("EditMessageText – message (_id=%s botid=%v id=%v) not updated text have not changed", om.ID.Hex(), bot.ID, om.MsgID)
return nil
}
_, err := bot.API.Send(tg.EditMessageTextConfig{
BaseEdit: tg.BaseEdit{
ChatID: om.ChatID,
MessageID: om.MsgID,
ReplyMarkup: &tg.InlineKeyboardMarkup{InlineKeyboard: om.InlineKeyboardMarkup.tg()},
},
ParseMode: om.ParseMode,
DisableWebPagePreview: !om.WebPreview,
Text: text,
})
if err != nil {
if err.(tg.Error).IsCantAccessChat() || err.(tg.Error).ChatMigrated() {
if c.Callback != nil && c.Callback.AnsweredAt == nil {
c.AnswerCallbackQuery("Sorry, message can be outdated. Bot can't edit messages created before converting to the Super Group", false)
}
} else if err.(tg.Error).IsAntiFlood() {
c.Log().WithError(err).Warn("TG Anti flood activated")
}
} else {
err = c.db.C("messages").UpdateId(om.ID, bson.M{"$set": bson.M{"texthash": om.TextHash}})
}
return err
}
|
go
|
func (c *Context) EditMessageText(om *OutgoingMessage, text string) error {
if om == nil {
return errors.New("Empty message provided")
}
bot := c.Bot()
if om.ParseMode == "HTML" {
textCleared, err := sanitize.HTMLAllowing(text, []string{"a", "b", "strong", "i", "em", "a", "code", "pre"}, []string{"href"})
if err == nil && textCleared != "" {
text = textCleared
}
}
om.Text = text
prevTextHash := om.TextHash
om.TextHash = om.GetTextHash()
if om.TextHash == prevTextHash {
c.Log().Debugf("EditMessageText – message (_id=%s botid=%v id=%v) not updated text have not changed", om.ID.Hex(), bot.ID, om.MsgID)
return nil
}
_, err := bot.API.Send(tg.EditMessageTextConfig{
BaseEdit: tg.BaseEdit{
ChatID: om.ChatID,
MessageID: om.MsgID,
ReplyMarkup: &tg.InlineKeyboardMarkup{InlineKeyboard: om.InlineKeyboardMarkup.tg()},
},
ParseMode: om.ParseMode,
DisableWebPagePreview: !om.WebPreview,
Text: text,
})
if err != nil {
if err.(tg.Error).IsCantAccessChat() || err.(tg.Error).ChatMigrated() {
if c.Callback != nil && c.Callback.AnsweredAt == nil {
c.AnswerCallbackQuery("Sorry, message can be outdated. Bot can't edit messages created before converting to the Super Group", false)
}
} else if err.(tg.Error).IsAntiFlood() {
c.Log().WithError(err).Warn("TG Anti flood activated")
}
} else {
err = c.db.C("messages").UpdateId(om.ID, bson.M{"$set": bson.M{"texthash": om.TextHash}})
}
return err
}
|
[
"func",
"(",
"c",
"*",
"Context",
")",
"EditMessageText",
"(",
"om",
"*",
"OutgoingMessage",
",",
"text",
"string",
")",
"error",
"{",
"if",
"om",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"bot",
":=",
"c",
".",
"Bot",
"(",
")",
"\n",
"if",
"om",
".",
"ParseMode",
"==",
"\"",
"\"",
"{",
"textCleared",
",",
"err",
":=",
"sanitize",
".",
"HTMLAllowing",
"(",
"text",
",",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
")",
"\n\n",
"if",
"err",
"==",
"nil",
"&&",
"textCleared",
"!=",
"\"",
"\"",
"{",
"text",
"=",
"textCleared",
"\n",
"}",
"\n",
"}",
"\n",
"om",
".",
"Text",
"=",
"text",
"\n",
"prevTextHash",
":=",
"om",
".",
"TextHash",
"\n",
"om",
".",
"TextHash",
"=",
"om",
".",
"GetTextHash",
"(",
")",
"\n\n\n",
"if",
"om",
".",
"TextHash",
"==",
"prevTextHash",
"{",
"c",
".",
"Log",
"(",
")",
".",
"Debugf",
"(",
"\"",
" ",
"o",
".I",
"D",
".H",
"e",
"x()",
",",
" ",
"b",
"t.I",
"D",
", ",
"o",
".M",
"s",
"gID)",
"",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n\n",
"_",
",",
"err",
":=",
"bot",
".",
"API",
".",
"Send",
"(",
"tg",
".",
"EditMessageTextConfig",
"{",
"BaseEdit",
":",
"tg",
".",
"BaseEdit",
"{",
"ChatID",
":",
"om",
".",
"ChatID",
",",
"MessageID",
":",
"om",
".",
"MsgID",
",",
"ReplyMarkup",
":",
"&",
"tg",
".",
"InlineKeyboardMarkup",
"{",
"InlineKeyboard",
":",
"om",
".",
"InlineKeyboardMarkup",
".",
"tg",
"(",
")",
"}",
",",
"}",
",",
"ParseMode",
":",
"om",
".",
"ParseMode",
",",
"DisableWebPagePreview",
":",
"!",
"om",
".",
"WebPreview",
",",
"Text",
":",
"text",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
".",
"(",
"tg",
".",
"Error",
")",
".",
"IsCantAccessChat",
"(",
")",
"||",
"err",
".",
"(",
"tg",
".",
"Error",
")",
".",
"ChatMigrated",
"(",
")",
"{",
"if",
"c",
".",
"Callback",
"!=",
"nil",
"&&",
"c",
".",
"Callback",
".",
"AnsweredAt",
"==",
"nil",
"{",
"c",
".",
"AnswerCallbackQuery",
"(",
"\"",
"\"",
",",
"false",
")",
"\n",
"}",
"\n",
"}",
"else",
"if",
"err",
".",
"(",
"tg",
".",
"Error",
")",
".",
"IsAntiFlood",
"(",
")",
"{",
"c",
".",
"Log",
"(",
")",
".",
"WithError",
"(",
"err",
")",
".",
"Warn",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"err",
"=",
"c",
".",
"db",
".",
"C",
"(",
"\"",
"\"",
")",
".",
"UpdateId",
"(",
"om",
".",
"ID",
",",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"om",
".",
"TextHash",
"}",
"}",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] |
// EditMessageText edit the text of message previously sent by the bot
|
[
"EditMessageText",
"edit",
"the",
"text",
"of",
"message",
"previously",
"sent",
"by",
"the",
"bot"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/context.go#L480-L526
|
train
|
requilence/integram
|
context.go
|
EditMessagesTextWithEventID
|
func (c *Context) EditMessagesTextWithEventID(eventID string, text string) (edited int, err error) {
var messages []OutgoingMessage
//update MAX_MSGS_TO_UPDATE_WITH_EVENTID last bot messages
c.db.C("messages").Find(bson.M{"botid": c.Bot().ID, "eventid": eventID}).Sort("-_id").Limit(MaxMsgsToUpdateWithEventID).All(&messages)
for _, message := range messages {
err = c.EditMessageText(&message, text)
if err != nil {
c.Log().WithError(err).WithField("eventid", eventID).Error("EditMessagesTextWithEventID")
} else {
edited++
}
}
return edited, err
}
|
go
|
func (c *Context) EditMessagesTextWithEventID(eventID string, text string) (edited int, err error) {
var messages []OutgoingMessage
//update MAX_MSGS_TO_UPDATE_WITH_EVENTID last bot messages
c.db.C("messages").Find(bson.M{"botid": c.Bot().ID, "eventid": eventID}).Sort("-_id").Limit(MaxMsgsToUpdateWithEventID).All(&messages)
for _, message := range messages {
err = c.EditMessageText(&message, text)
if err != nil {
c.Log().WithError(err).WithField("eventid", eventID).Error("EditMessagesTextWithEventID")
} else {
edited++
}
}
return edited, err
}
|
[
"func",
"(",
"c",
"*",
"Context",
")",
"EditMessagesTextWithEventID",
"(",
"eventID",
"string",
",",
"text",
"string",
")",
"(",
"edited",
"int",
",",
"err",
"error",
")",
"{",
"var",
"messages",
"[",
"]",
"OutgoingMessage",
"\n",
"//update MAX_MSGS_TO_UPDATE_WITH_EVENTID last bot messages",
"c",
".",
"db",
".",
"C",
"(",
"\"",
"\"",
")",
".",
"Find",
"(",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"c",
".",
"Bot",
"(",
")",
".",
"ID",
",",
"\"",
"\"",
":",
"eventID",
"}",
")",
".",
"Sort",
"(",
"\"",
"\"",
")",
".",
"Limit",
"(",
"MaxMsgsToUpdateWithEventID",
")",
".",
"All",
"(",
"&",
"messages",
")",
"\n",
"for",
"_",
",",
"message",
":=",
"range",
"messages",
"{",
"err",
"=",
"c",
".",
"EditMessageText",
"(",
"&",
"message",
",",
"text",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"c",
".",
"Log",
"(",
")",
".",
"WithError",
"(",
"err",
")",
".",
"WithField",
"(",
"\"",
"\"",
",",
"eventID",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"edited",
"++",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"edited",
",",
"err",
"\n",
"}"
] |
// EditMessagesTextWithEventID edit the last MaxMsgsToUpdateWithEventID messages' text with the corresponding eventID in ALL chats
|
[
"EditMessagesTextWithEventID",
"edit",
"the",
"last",
"MaxMsgsToUpdateWithEventID",
"messages",
"text",
"with",
"the",
"corresponding",
"eventID",
"in",
"ALL",
"chats"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/context.go#L529-L542
|
train
|
requilence/integram
|
context.go
|
EditMessageTextWithMessageID
|
func (c *Context) EditMessageTextWithMessageID(msgID bson.ObjectId, text string) (edited int, err error) {
var message OutgoingMessage
c.db.C("messages").Find(bson.M{"_id": msgID, "botid": c.Bot().ID}).One(&message)
err = c.EditMessageText(&message, text)
if err != nil {
c.Log().WithError(err).WithField("msgid", msgID).Error("EditMessageTextWithMessageID")
} else {
edited++
}
return edited, err
}
|
go
|
func (c *Context) EditMessageTextWithMessageID(msgID bson.ObjectId, text string) (edited int, err error) {
var message OutgoingMessage
c.db.C("messages").Find(bson.M{"_id": msgID, "botid": c.Bot().ID}).One(&message)
err = c.EditMessageText(&message, text)
if err != nil {
c.Log().WithError(err).WithField("msgid", msgID).Error("EditMessageTextWithMessageID")
} else {
edited++
}
return edited, err
}
|
[
"func",
"(",
"c",
"*",
"Context",
")",
"EditMessageTextWithMessageID",
"(",
"msgID",
"bson",
".",
"ObjectId",
",",
"text",
"string",
")",
"(",
"edited",
"int",
",",
"err",
"error",
")",
"{",
"var",
"message",
"OutgoingMessage",
"\n\n",
"c",
".",
"db",
".",
"C",
"(",
"\"",
"\"",
")",
".",
"Find",
"(",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"msgID",
",",
"\"",
"\"",
":",
"c",
".",
"Bot",
"(",
")",
".",
"ID",
"}",
")",
".",
"One",
"(",
"&",
"message",
")",
"\n",
"err",
"=",
"c",
".",
"EditMessageText",
"(",
"&",
"message",
",",
"text",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"c",
".",
"Log",
"(",
")",
".",
"WithError",
"(",
"err",
")",
".",
"WithField",
"(",
"\"",
"\"",
",",
"msgID",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"edited",
"++",
"\n",
"}",
"\n\n",
"return",
"edited",
",",
"err",
"\n",
"}"
] |
// EditMessagesTextWithMessageID edit the one message text with by message BSON ID
|
[
"EditMessagesTextWithMessageID",
"edit",
"the",
"one",
"message",
"text",
"with",
"by",
"message",
"BSON",
"ID"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/context.go#L545-L557
|
train
|
requilence/integram
|
context.go
|
EditMessagesWithEventID
|
func (c *Context) EditMessagesWithEventID(eventID string, fromState string, text string, kb InlineKeyboard) (edited int, err error) {
var messages []OutgoingMessage
f := bson.M{"botid": c.Bot().ID, "eventid": eventID}
if fromState != "" {
f["inlinekeyboardmarkup.state"] = fromState
}
//update MAX_MSGS_TO_UPDATE_WITH_EVENTID last bot messages
c.db.C("messages").Find(f).Sort("-_id").Limit(MaxMsgsToUpdateWithEventID).All(&messages)
for _, message := range messages {
err = c.EditMessageTextAndInlineKeyboard(&message, fromState, text, kb)
if err != nil {
c.Log().WithError(err).WithField("eventid", eventID).Error("EditMessagesWithEventID")
} else {
edited++
}
}
return edited, err
}
|
go
|
func (c *Context) EditMessagesWithEventID(eventID string, fromState string, text string, kb InlineKeyboard) (edited int, err error) {
var messages []OutgoingMessage
f := bson.M{"botid": c.Bot().ID, "eventid": eventID}
if fromState != "" {
f["inlinekeyboardmarkup.state"] = fromState
}
//update MAX_MSGS_TO_UPDATE_WITH_EVENTID last bot messages
c.db.C("messages").Find(f).Sort("-_id").Limit(MaxMsgsToUpdateWithEventID).All(&messages)
for _, message := range messages {
err = c.EditMessageTextAndInlineKeyboard(&message, fromState, text, kb)
if err != nil {
c.Log().WithError(err).WithField("eventid", eventID).Error("EditMessagesWithEventID")
} else {
edited++
}
}
return edited, err
}
|
[
"func",
"(",
"c",
"*",
"Context",
")",
"EditMessagesWithEventID",
"(",
"eventID",
"string",
",",
"fromState",
"string",
",",
"text",
"string",
",",
"kb",
"InlineKeyboard",
")",
"(",
"edited",
"int",
",",
"err",
"error",
")",
"{",
"var",
"messages",
"[",
"]",
"OutgoingMessage",
"\n",
"f",
":=",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"c",
".",
"Bot",
"(",
")",
".",
"ID",
",",
"\"",
"\"",
":",
"eventID",
"}",
"\n",
"if",
"fromState",
"!=",
"\"",
"\"",
"{",
"f",
"[",
"\"",
"\"",
"]",
"=",
"fromState",
"\n",
"}",
"\n\n",
"//update MAX_MSGS_TO_UPDATE_WITH_EVENTID last bot messages",
"c",
".",
"db",
".",
"C",
"(",
"\"",
"\"",
")",
".",
"Find",
"(",
"f",
")",
".",
"Sort",
"(",
"\"",
"\"",
")",
".",
"Limit",
"(",
"MaxMsgsToUpdateWithEventID",
")",
".",
"All",
"(",
"&",
"messages",
")",
"\n",
"for",
"_",
",",
"message",
":=",
"range",
"messages",
"{",
"err",
"=",
"c",
".",
"EditMessageTextAndInlineKeyboard",
"(",
"&",
"message",
",",
"fromState",
",",
"text",
",",
"kb",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"c",
".",
"Log",
"(",
")",
".",
"WithError",
"(",
"err",
")",
".",
"WithField",
"(",
"\"",
"\"",
",",
"eventID",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"edited",
"++",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"edited",
",",
"err",
"\n",
"}"
] |
// EditMessagesWithEventID edit the last MaxMsgsToUpdateWithEventID messages' text and inline keyboard with the corresponding eventID in ALL chats
|
[
"EditMessagesWithEventID",
"edit",
"the",
"last",
"MaxMsgsToUpdateWithEventID",
"messages",
"text",
"and",
"inline",
"keyboard",
"with",
"the",
"corresponding",
"eventID",
"in",
"ALL",
"chats"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/context.go#L560-L578
|
train
|
requilence/integram
|
context.go
|
DeleteMessagesWithEventID
|
func (c *Context) DeleteMessagesWithEventID(eventID string) (deleted int, err error) {
var messages []OutgoingMessage
f := bson.M{"botid": c.Bot().ID, "eventid": eventID}
//update MAX_MSGS_TO_UPDATE_WITH_EVENTID last bot messages
c.db.C("messages").Find(f).Sort("-_id").Limit(MaxMsgsToUpdateWithEventID).All(&messages)
for _, message := range messages {
err = c.DeleteMessage(&message)
if err != nil {
c.Log().WithError(err).WithField("eventid", eventID).Error("DeleteMessagesWithEventID")
} else {
deleted++
}
}
return deleted, err
}
|
go
|
func (c *Context) DeleteMessagesWithEventID(eventID string) (deleted int, err error) {
var messages []OutgoingMessage
f := bson.M{"botid": c.Bot().ID, "eventid": eventID}
//update MAX_MSGS_TO_UPDATE_WITH_EVENTID last bot messages
c.db.C("messages").Find(f).Sort("-_id").Limit(MaxMsgsToUpdateWithEventID).All(&messages)
for _, message := range messages {
err = c.DeleteMessage(&message)
if err != nil {
c.Log().WithError(err).WithField("eventid", eventID).Error("DeleteMessagesWithEventID")
} else {
deleted++
}
}
return deleted, err
}
|
[
"func",
"(",
"c",
"*",
"Context",
")",
"DeleteMessagesWithEventID",
"(",
"eventID",
"string",
")",
"(",
"deleted",
"int",
",",
"err",
"error",
")",
"{",
"var",
"messages",
"[",
"]",
"OutgoingMessage",
"\n",
"f",
":=",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"c",
".",
"Bot",
"(",
")",
".",
"ID",
",",
"\"",
"\"",
":",
"eventID",
"}",
"\n\n",
"//update MAX_MSGS_TO_UPDATE_WITH_EVENTID last bot messages",
"c",
".",
"db",
".",
"C",
"(",
"\"",
"\"",
")",
".",
"Find",
"(",
"f",
")",
".",
"Sort",
"(",
"\"",
"\"",
")",
".",
"Limit",
"(",
"MaxMsgsToUpdateWithEventID",
")",
".",
"All",
"(",
"&",
"messages",
")",
"\n",
"for",
"_",
",",
"message",
":=",
"range",
"messages",
"{",
"err",
"=",
"c",
".",
"DeleteMessage",
"(",
"&",
"message",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"c",
".",
"Log",
"(",
")",
".",
"WithError",
"(",
"err",
")",
".",
"WithField",
"(",
"\"",
"\"",
",",
"eventID",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"deleted",
"++",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"deleted",
",",
"err",
"\n",
"}"
] |
// DeleteMessagesWithEventID deletes the last MaxMsgsToUpdateWithEventID messages' text and inline keyboard with the corresponding eventID in ALL chats
|
[
"DeleteMessagesWithEventID",
"deletes",
"the",
"last",
"MaxMsgsToUpdateWithEventID",
"messages",
"text",
"and",
"inline",
"keyboard",
"with",
"the",
"corresponding",
"eventID",
"in",
"ALL",
"chats"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/context.go#L581-L596
|
train
|
requilence/integram
|
context.go
|
DeleteMessage
|
func (c *Context) DeleteMessage(om *OutgoingMessage) error {
bot := c.Bot()
if om.MsgID != 0 {
log.WithField("msgID", om.MsgID).Debug("DeleteMessage")
} else {
om.ChatID = 0
log.WithField("inlineMsgID", om.InlineMsgID).Debug("DeleteMessage")
}
var msg OutgoingMessage
var ci *mgo.ChangeInfo
var err error
ci, err = c.db.C("messages").Find(bson.M{"_id": om.ID}).Apply(mgo.Change{Remove: true}, &msg)
if err != nil {
c.Log().WithError(err).Error("DeleteMessage messages remove error")
}
if msg.BotID == 0 {
c.Log().Warn(fmt.Sprintf("DeleteMessage – message (_id=%s botid=%v id=%v) not found", om.ID, bot.ID, om.MsgID))
return nil
}
if ci.Removed == 0 {
c.Log().Warn(fmt.Sprintf("DeleteMessage – message (_id=%s botid=%v id=%v) not removed ", om.ID, bot.ID, om.MsgID))
return nil
}
_, err = bot.API.Send(tg.DeleteMessageConfig{
ChatID: om.ChatID,
MessageID: om.MsgID,
})
if err != nil {
if err.(tg.Error).IsCantAccessChat() || err.(tg.Error).ChatMigrated() {
if c.Callback != nil {
c.AnswerCallbackQuery("Message can be outdated. Bot can't edit messages created before converting to the Super Group", false)
}
} else if err.(tg.Error).IsAntiFlood() {
c.Log().WithError(err).Warn("TG Anti flood activated")
}
// Oops. error is occurred – revert the original message
c.db.C("messages").Insert(om)
return err
}
return nil
}
|
go
|
func (c *Context) DeleteMessage(om *OutgoingMessage) error {
bot := c.Bot()
if om.MsgID != 0 {
log.WithField("msgID", om.MsgID).Debug("DeleteMessage")
} else {
om.ChatID = 0
log.WithField("inlineMsgID", om.InlineMsgID).Debug("DeleteMessage")
}
var msg OutgoingMessage
var ci *mgo.ChangeInfo
var err error
ci, err = c.db.C("messages").Find(bson.M{"_id": om.ID}).Apply(mgo.Change{Remove: true}, &msg)
if err != nil {
c.Log().WithError(err).Error("DeleteMessage messages remove error")
}
if msg.BotID == 0 {
c.Log().Warn(fmt.Sprintf("DeleteMessage – message (_id=%s botid=%v id=%v) not found", om.ID, bot.ID, om.MsgID))
return nil
}
if ci.Removed == 0 {
c.Log().Warn(fmt.Sprintf("DeleteMessage – message (_id=%s botid=%v id=%v) not removed ", om.ID, bot.ID, om.MsgID))
return nil
}
_, err = bot.API.Send(tg.DeleteMessageConfig{
ChatID: om.ChatID,
MessageID: om.MsgID,
})
if err != nil {
if err.(tg.Error).IsCantAccessChat() || err.(tg.Error).ChatMigrated() {
if c.Callback != nil {
c.AnswerCallbackQuery("Message can be outdated. Bot can't edit messages created before converting to the Super Group", false)
}
} else if err.(tg.Error).IsAntiFlood() {
c.Log().WithError(err).Warn("TG Anti flood activated")
}
// Oops. error is occurred – revert the original message
c.db.C("messages").Insert(om)
return err
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"Context",
")",
"DeleteMessage",
"(",
"om",
"*",
"OutgoingMessage",
")",
"error",
"{",
"bot",
":=",
"c",
".",
"Bot",
"(",
")",
"\n",
"if",
"om",
".",
"MsgID",
"!=",
"0",
"{",
"log",
".",
"WithField",
"(",
"\"",
"\"",
",",
"om",
".",
"MsgID",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"om",
".",
"ChatID",
"=",
"0",
"\n",
"log",
".",
"WithField",
"(",
"\"",
"\"",
",",
"om",
".",
"InlineMsgID",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"var",
"msg",
"OutgoingMessage",
"\n",
"var",
"ci",
"*",
"mgo",
".",
"ChangeInfo",
"\n",
"var",
"err",
"error",
"\n\n",
"ci",
",",
"err",
"=",
"c",
".",
"db",
".",
"C",
"(",
"\"",
"\"",
")",
".",
"Find",
"(",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"om",
".",
"ID",
"}",
")",
".",
"Apply",
"(",
"mgo",
".",
"Change",
"{",
"Remove",
":",
"true",
"}",
",",
"&",
"msg",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"c",
".",
"Log",
"(",
")",
".",
"WithError",
"(",
"err",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"msg",
".",
"BotID",
"==",
"0",
"{",
"c",
".",
"Log",
"(",
")",
".",
"Warn",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
" ",
"o",
".I",
"D",
", ",
"b",
"t.I",
"D",
", ",
"o",
".M",
"s",
"gID))",
"",
"",
"\n",
"return",
"nil",
"\n\n",
"}",
"\n",
"if",
"ci",
".",
"Removed",
"==",
"0",
"{",
"c",
".",
"Log",
"(",
")",
".",
"Warn",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
" ",
"o",
".I",
"D",
", ",
"b",
"t.I",
"D",
", ",
"o",
".M",
"s",
"gID))",
"",
"",
"\n\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"_",
",",
"err",
"=",
"bot",
".",
"API",
".",
"Send",
"(",
"tg",
".",
"DeleteMessageConfig",
"{",
"ChatID",
":",
"om",
".",
"ChatID",
",",
"MessageID",
":",
"om",
".",
"MsgID",
",",
"}",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
".",
"(",
"tg",
".",
"Error",
")",
".",
"IsCantAccessChat",
"(",
")",
"||",
"err",
".",
"(",
"tg",
".",
"Error",
")",
".",
"ChatMigrated",
"(",
")",
"{",
"if",
"c",
".",
"Callback",
"!=",
"nil",
"{",
"c",
".",
"AnswerCallbackQuery",
"(",
"\"",
"\"",
",",
"false",
")",
"\n",
"}",
"\n",
"}",
"else",
"if",
"err",
".",
"(",
"tg",
".",
"Error",
")",
".",
"IsAntiFlood",
"(",
")",
"{",
"c",
".",
"Log",
"(",
")",
".",
"WithError",
"(",
"err",
")",
".",
"Warn",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"// Oops. error is occurred – revert the original message",
"c",
".",
"db",
".",
"C",
"(",
"\"",
"\"",
")",
".",
"Insert",
"(",
"om",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// DeleteMessage deletes the outgoing message's text and inline keyboard
|
[
"DeleteMessage",
"deletes",
"the",
"outgoing",
"message",
"s",
"text",
"and",
"inline",
"keyboard"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/context.go#L599-L648
|
train
|
requilence/integram
|
context.go
|
EditInlineKeyboard
|
func (c *Context) EditInlineKeyboard(om *OutgoingMessage, fromState string, kb InlineKeyboard) error {
bot := c.Bot()
if om.MsgID != 0 {
log.WithField("msgID", om.MsgID).Debug("EditMessageTextAndInlineKeyboard")
} else {
om.ChatID = 0
log.WithField("inlineMsgID", om.InlineMsgID).Debug("EditMessageTextAndInlineKeyboard")
}
var msg OutgoingMessage
_, err := c.db.C("messages").Find(bson.M{"_id": om.ID, "$or": []bson.M{{"inlinekeyboardmarkup.state": fromState}, {"inlinekeyboardmarkup": bson.M{"$exists": false}}}}).Apply(mgo.Change{Update: bson.M{"$set": bson.M{"inlinekeyboardmarkup": kb}}}, &msg)
if msg.BotID == 0 {
return fmt.Errorf("EditInlineKeyboard – message (botid=%v id=%v state %s) not found", bot.ID, om.MsgID, fromState)
}
tgKeyboard := kb.tg()
prevTGKeyboard := om.InlineKeyboardMarkup.tg()
if whetherTGInlineKeyboardsAreEqual(prevTGKeyboard, tgKeyboard) {
c.Log().Debugf("EditMessageTextAndInlineKeyboard – message (_id=%s botid=%v id=%v state %s) not updated both text and kb have not changed", om.ID, bot.ID, om.MsgID, fromState)
return nil
}
_, err = bot.API.Send(tg.EditMessageReplyMarkupConfig{
BaseEdit: tg.BaseEdit{
ChatID: om.ChatID,
MessageID: om.MsgID,
InlineMessageID: om.InlineMsgID,
ReplyMarkup: &tg.InlineKeyboardMarkup{InlineKeyboard: tgKeyboard},
},
})
if err != nil {
if err.(tg.Error).IsCantAccessChat() || err.(tg.Error).ChatMigrated() {
if c.Callback != nil {
c.AnswerCallbackQuery("Message can be outdated. Bot can't edit messages created before converting to the Super Group", false)
}
} else if err.(tg.Error).IsAntiFlood() {
c.Log().WithError(err).Warn("TG Anti flood activated")
}
// Oops. error is occurred – revert the original keyboard
err := c.db.C("messages").Update(bson.M{"_id": msg.ID}, bson.M{"$set": bson.M{"inlinekeyboardmarkup": msg.InlineKeyboardMarkup}})
return err
}
return nil
}
|
go
|
func (c *Context) EditInlineKeyboard(om *OutgoingMessage, fromState string, kb InlineKeyboard) error {
bot := c.Bot()
if om.MsgID != 0 {
log.WithField("msgID", om.MsgID).Debug("EditMessageTextAndInlineKeyboard")
} else {
om.ChatID = 0
log.WithField("inlineMsgID", om.InlineMsgID).Debug("EditMessageTextAndInlineKeyboard")
}
var msg OutgoingMessage
_, err := c.db.C("messages").Find(bson.M{"_id": om.ID, "$or": []bson.M{{"inlinekeyboardmarkup.state": fromState}, {"inlinekeyboardmarkup": bson.M{"$exists": false}}}}).Apply(mgo.Change{Update: bson.M{"$set": bson.M{"inlinekeyboardmarkup": kb}}}, &msg)
if msg.BotID == 0 {
return fmt.Errorf("EditInlineKeyboard – message (botid=%v id=%v state %s) not found", bot.ID, om.MsgID, fromState)
}
tgKeyboard := kb.tg()
prevTGKeyboard := om.InlineKeyboardMarkup.tg()
if whetherTGInlineKeyboardsAreEqual(prevTGKeyboard, tgKeyboard) {
c.Log().Debugf("EditMessageTextAndInlineKeyboard – message (_id=%s botid=%v id=%v state %s) not updated both text and kb have not changed", om.ID, bot.ID, om.MsgID, fromState)
return nil
}
_, err = bot.API.Send(tg.EditMessageReplyMarkupConfig{
BaseEdit: tg.BaseEdit{
ChatID: om.ChatID,
MessageID: om.MsgID,
InlineMessageID: om.InlineMsgID,
ReplyMarkup: &tg.InlineKeyboardMarkup{InlineKeyboard: tgKeyboard},
},
})
if err != nil {
if err.(tg.Error).IsCantAccessChat() || err.(tg.Error).ChatMigrated() {
if c.Callback != nil {
c.AnswerCallbackQuery("Message can be outdated. Bot can't edit messages created before converting to the Super Group", false)
}
} else if err.(tg.Error).IsAntiFlood() {
c.Log().WithError(err).Warn("TG Anti flood activated")
}
// Oops. error is occurred – revert the original keyboard
err := c.db.C("messages").Update(bson.M{"_id": msg.ID}, bson.M{"$set": bson.M{"inlinekeyboardmarkup": msg.InlineKeyboardMarkup}})
return err
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"Context",
")",
"EditInlineKeyboard",
"(",
"om",
"*",
"OutgoingMessage",
",",
"fromState",
"string",
",",
"kb",
"InlineKeyboard",
")",
"error",
"{",
"bot",
":=",
"c",
".",
"Bot",
"(",
")",
"\n",
"if",
"om",
".",
"MsgID",
"!=",
"0",
"{",
"log",
".",
"WithField",
"(",
"\"",
"\"",
",",
"om",
".",
"MsgID",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"om",
".",
"ChatID",
"=",
"0",
"\n",
"log",
".",
"WithField",
"(",
"\"",
"\"",
",",
"om",
".",
"InlineMsgID",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"var",
"msg",
"OutgoingMessage",
"\n\n",
"_",
",",
"err",
":=",
"c",
".",
"db",
".",
"C",
"(",
"\"",
"\"",
")",
".",
"Find",
"(",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"om",
".",
"ID",
",",
"\"",
"\"",
":",
"[",
"]",
"bson",
".",
"M",
"{",
"{",
"\"",
"\"",
":",
"fromState",
"}",
",",
"{",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"false",
"}",
"}",
"}",
"}",
")",
".",
"Apply",
"(",
"mgo",
".",
"Change",
"{",
"Update",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"kb",
"}",
"}",
"}",
",",
"&",
"msg",
")",
"\n\n",
"if",
"msg",
".",
"BotID",
"==",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
" ",
"b",
"t.I",
"D",
", ",
"o",
".M",
"s",
"gID, ",
"f",
"omState)",
"",
"\n",
"}",
"\n\n",
"tgKeyboard",
":=",
"kb",
".",
"tg",
"(",
")",
"\n",
"prevTGKeyboard",
":=",
"om",
".",
"InlineKeyboardMarkup",
".",
"tg",
"(",
")",
"\n",
"if",
"whetherTGInlineKeyboardsAreEqual",
"(",
"prevTGKeyboard",
",",
"tgKeyboard",
")",
"{",
"c",
".",
"Log",
"(",
")",
".",
"Debugf",
"(",
"\"",
" ",
"o",
".I",
"D",
", ",
"b",
"t.I",
"D",
", ",
"o",
".M",
"s",
"gID, ",
"f",
"omState)",
"",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"_",
",",
"err",
"=",
"bot",
".",
"API",
".",
"Send",
"(",
"tg",
".",
"EditMessageReplyMarkupConfig",
"{",
"BaseEdit",
":",
"tg",
".",
"BaseEdit",
"{",
"ChatID",
":",
"om",
".",
"ChatID",
",",
"MessageID",
":",
"om",
".",
"MsgID",
",",
"InlineMessageID",
":",
"om",
".",
"InlineMsgID",
",",
"ReplyMarkup",
":",
"&",
"tg",
".",
"InlineKeyboardMarkup",
"{",
"InlineKeyboard",
":",
"tgKeyboard",
"}",
",",
"}",
",",
"}",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
".",
"(",
"tg",
".",
"Error",
")",
".",
"IsCantAccessChat",
"(",
")",
"||",
"err",
".",
"(",
"tg",
".",
"Error",
")",
".",
"ChatMigrated",
"(",
")",
"{",
"if",
"c",
".",
"Callback",
"!=",
"nil",
"{",
"c",
".",
"AnswerCallbackQuery",
"(",
"\"",
"\"",
",",
"false",
")",
"\n",
"}",
"\n",
"}",
"else",
"if",
"err",
".",
"(",
"tg",
".",
"Error",
")",
".",
"IsAntiFlood",
"(",
")",
"{",
"c",
".",
"Log",
"(",
")",
".",
"WithError",
"(",
"err",
")",
".",
"Warn",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"// Oops. error is occurred – revert the original keyboard",
"err",
":=",
"c",
".",
"db",
".",
"C",
"(",
"\"",
"\"",
")",
".",
"Update",
"(",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"msg",
".",
"ID",
"}",
",",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"msg",
".",
"InlineKeyboardMarkup",
"}",
"}",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n\n",
"}"
] |
// EditInlineKeyboard edit the outgoing message's inline keyboard
|
[
"EditInlineKeyboard",
"edit",
"the",
"outgoing",
"message",
"s",
"inline",
"keyboard"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/context.go#L732-L780
|
train
|
requilence/integram
|
context.go
|
EditInlineButton
|
func (c *Context) EditInlineButton(om *OutgoingMessage, kbState string, buttonData string, newButtonText string) error {
return c.EditInlineStateButton(om, kbState, 0, buttonData, 0, newButtonText)
}
|
go
|
func (c *Context) EditInlineButton(om *OutgoingMessage, kbState string, buttonData string, newButtonText string) error {
return c.EditInlineStateButton(om, kbState, 0, buttonData, 0, newButtonText)
}
|
[
"func",
"(",
"c",
"*",
"Context",
")",
"EditInlineButton",
"(",
"om",
"*",
"OutgoingMessage",
",",
"kbState",
"string",
",",
"buttonData",
"string",
",",
"newButtonText",
"string",
")",
"error",
"{",
"return",
"c",
".",
"EditInlineStateButton",
"(",
"om",
",",
"kbState",
",",
"0",
",",
"buttonData",
",",
"0",
",",
"newButtonText",
")",
"\n\n",
"}"
] |
// EditInlineButton edit the outgoing message's inline button
|
[
"EditInlineButton",
"edit",
"the",
"outgoing",
"message",
"s",
"inline",
"button"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/context.go#L783-L786
|
train
|
requilence/integram
|
context.go
|
EditInlineStateButton
|
func (c *Context) EditInlineStateButton(om *OutgoingMessage, kbState string, oldButtonState int, buttonData string, newButtonState int, newButtonText string) error {
if oldButtonState > 9 || oldButtonState < 0 {
c.Log().WithField("data", buttonData).WithField("text", newButtonText).Errorf("EditInlineStateButton – oldButtonState must be [0-9], %d recived", oldButtonState)
}
if newButtonState > 9 || newButtonState < 0 {
c.Log().WithField("data", buttonData).WithField("text", newButtonText).Errorf("EditInlineStateButton – newButtonState must be [0-9], %d recived", newButtonState)
}
bot := c.Bot()
var msg OutgoingMessage
c.db.C("messages").Find(bson.M{"_id": om.ID, "inlinekeyboardmarkup.state": kbState}).One(&msg)
// need a more thread safe solution to switch stored keyboard
if msg.BotID == 0 {
return fmt.Errorf("EditInlineButton – message (botid=%v id=%v(%v) state %s) not found", bot.ID, om.MsgID, om.InlineMsgID, kbState)
}
i, j, _ := msg.InlineKeyboardMarkup.Find(buttonData)
if i < 0 {
return fmt.Errorf("EditInlineButton – button %v not found in message (botid=%v id=%v(%v) state %s) not found", buttonData, bot.ID, om.MsgID, om.InlineMsgID, kbState)
}
//first of all – change stored keyboard to avoid simultaneously changing requests
set := bson.M{fmt.Sprintf("inlinekeyboardmarkup.buttons.%d.%d.text", i, j): newButtonText}
if newButtonState != oldButtonState {
set = bson.M{fmt.Sprintf("inlinekeyboardmarkup.buttons.%d.%d.text", i, j): newButtonText, fmt.Sprintf("inlinekeyboardmarkup.buttons.%d.%d.state", i, j): newButtonState}
}
info, err := c.db.C("messages").UpdateAll(bson.M{"_id": msg.ID, "inlinekeyboardmarkup.state": kbState, fmt.Sprintf("inlinekeyboardmarkup.buttons.%d.%d.data", i, j): buttonData}, bson.M{"$set": set})
if info.Updated == 0 {
// another one thread safe check
return fmt.Errorf("EditInlineButton – button[%d][%d] %v not found in message (botid=%v id=%v(%v) state %s) not found", i, j, buttonData, bot.ID, om.MsgID, om.InlineMsgID, kbState)
}
kb := msg.InlineKeyboardMarkup
kb.Buttons[i][j].Text = newButtonText
kb.Buttons[i][j].State = newButtonState
// todo: the stored keyboard can differ from actual because we update the whole keyboard in TG but update only target button locally
// But maybe it's ok...
_, err = bot.API.Send(tg.EditMessageReplyMarkupConfig{
BaseEdit: tg.BaseEdit{
ChatID: om.ChatID,
MessageID: om.MsgID,
InlineMessageID: om.InlineMsgID,
ReplyMarkup: &tg.InlineKeyboardMarkup{InlineKeyboard: kb.tg()},
},
})
if err != nil {
// Oops. error is occurred – revert the original keyboard
err := c.db.C("messages").UpdateId(msg.ID, bson.M{"$set": bson.M{"inlinekeyboardmarkup": msg.InlineKeyboardMarkup}})
return err
}
return nil
}
|
go
|
func (c *Context) EditInlineStateButton(om *OutgoingMessage, kbState string, oldButtonState int, buttonData string, newButtonState int, newButtonText string) error {
if oldButtonState > 9 || oldButtonState < 0 {
c.Log().WithField("data", buttonData).WithField("text", newButtonText).Errorf("EditInlineStateButton – oldButtonState must be [0-9], %d recived", oldButtonState)
}
if newButtonState > 9 || newButtonState < 0 {
c.Log().WithField("data", buttonData).WithField("text", newButtonText).Errorf("EditInlineStateButton – newButtonState must be [0-9], %d recived", newButtonState)
}
bot := c.Bot()
var msg OutgoingMessage
c.db.C("messages").Find(bson.M{"_id": om.ID, "inlinekeyboardmarkup.state": kbState}).One(&msg)
// need a more thread safe solution to switch stored keyboard
if msg.BotID == 0 {
return fmt.Errorf("EditInlineButton – message (botid=%v id=%v(%v) state %s) not found", bot.ID, om.MsgID, om.InlineMsgID, kbState)
}
i, j, _ := msg.InlineKeyboardMarkup.Find(buttonData)
if i < 0 {
return fmt.Errorf("EditInlineButton – button %v not found in message (botid=%v id=%v(%v) state %s) not found", buttonData, bot.ID, om.MsgID, om.InlineMsgID, kbState)
}
//first of all – change stored keyboard to avoid simultaneously changing requests
set := bson.M{fmt.Sprintf("inlinekeyboardmarkup.buttons.%d.%d.text", i, j): newButtonText}
if newButtonState != oldButtonState {
set = bson.M{fmt.Sprintf("inlinekeyboardmarkup.buttons.%d.%d.text", i, j): newButtonText, fmt.Sprintf("inlinekeyboardmarkup.buttons.%d.%d.state", i, j): newButtonState}
}
info, err := c.db.C("messages").UpdateAll(bson.M{"_id": msg.ID, "inlinekeyboardmarkup.state": kbState, fmt.Sprintf("inlinekeyboardmarkup.buttons.%d.%d.data", i, j): buttonData}, bson.M{"$set": set})
if info.Updated == 0 {
// another one thread safe check
return fmt.Errorf("EditInlineButton – button[%d][%d] %v not found in message (botid=%v id=%v(%v) state %s) not found", i, j, buttonData, bot.ID, om.MsgID, om.InlineMsgID, kbState)
}
kb := msg.InlineKeyboardMarkup
kb.Buttons[i][j].Text = newButtonText
kb.Buttons[i][j].State = newButtonState
// todo: the stored keyboard can differ from actual because we update the whole keyboard in TG but update only target button locally
// But maybe it's ok...
_, err = bot.API.Send(tg.EditMessageReplyMarkupConfig{
BaseEdit: tg.BaseEdit{
ChatID: om.ChatID,
MessageID: om.MsgID,
InlineMessageID: om.InlineMsgID,
ReplyMarkup: &tg.InlineKeyboardMarkup{InlineKeyboard: kb.tg()},
},
})
if err != nil {
// Oops. error is occurred – revert the original keyboard
err := c.db.C("messages").UpdateId(msg.ID, bson.M{"$set": bson.M{"inlinekeyboardmarkup": msg.InlineKeyboardMarkup}})
return err
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"Context",
")",
"EditInlineStateButton",
"(",
"om",
"*",
"OutgoingMessage",
",",
"kbState",
"string",
",",
"oldButtonState",
"int",
",",
"buttonData",
"string",
",",
"newButtonState",
"int",
",",
"newButtonText",
"string",
")",
"error",
"{",
"if",
"oldButtonState",
">",
"9",
"||",
"oldButtonState",
"<",
"0",
"{",
"c",
".",
"Log",
"(",
")",
".",
"WithField",
"(",
"\"",
"\"",
",",
"buttonData",
")",
".",
"WithField",
"(",
"\"",
"\"",
",",
"newButtonText",
")",
".",
"Errorf",
"(",
"\"",
" ",
"o",
"dButtonState)",
"",
"\n",
"}",
"\n\n",
"if",
"newButtonState",
">",
"9",
"||",
"newButtonState",
"<",
"0",
"{",
"c",
".",
"Log",
"(",
")",
".",
"WithField",
"(",
"\"",
"\"",
",",
"buttonData",
")",
".",
"WithField",
"(",
"\"",
"\"",
",",
"newButtonText",
")",
".",
"Errorf",
"(",
"\"",
" ",
"n",
"wButtonState)",
"",
"\n",
"}",
"\n\n",
"bot",
":=",
"c",
".",
"Bot",
"(",
")",
"\n\n",
"var",
"msg",
"OutgoingMessage",
"\n",
"c",
".",
"db",
".",
"C",
"(",
"\"",
"\"",
")",
".",
"Find",
"(",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"om",
".",
"ID",
",",
"\"",
"\"",
":",
"kbState",
"}",
")",
".",
"One",
"(",
"&",
"msg",
")",
"\n",
"// need a more thread safe solution to switch stored keyboard",
"if",
"msg",
".",
"BotID",
"==",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
" ",
"b",
"t.I",
"D",
", ",
"o",
".M",
"s",
"gID, ",
"o",
".I",
"n",
"lineMsgID, ",
"k",
"State)",
"",
"\n",
"}",
"\n",
"i",
",",
"j",
",",
"_",
":=",
"msg",
".",
"InlineKeyboardMarkup",
".",
"Find",
"(",
"buttonData",
")",
"\n\n",
"if",
"i",
"<",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
" ",
"b",
"ttonData, ",
"b",
"t.I",
"D",
", ",
"o",
".M",
"s",
"gID, ",
"o",
".I",
"n",
"lineMsgID, ",
"k",
"State)",
"",
"\n",
"}",
"\n\n",
"//first of all – change stored keyboard to avoid simultaneously changing requests",
"set",
":=",
"bson",
".",
"M",
"{",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"i",
",",
"j",
")",
":",
"newButtonText",
"}",
"\n\n",
"if",
"newButtonState",
"!=",
"oldButtonState",
"{",
"set",
"=",
"bson",
".",
"M",
"{",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"i",
",",
"j",
")",
":",
"newButtonText",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"i",
",",
"j",
")",
":",
"newButtonState",
"}",
"\n",
"}",
"\n\n",
"info",
",",
"err",
":=",
"c",
".",
"db",
".",
"C",
"(",
"\"",
"\"",
")",
".",
"UpdateAll",
"(",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"msg",
".",
"ID",
",",
"\"",
"\"",
":",
"kbState",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"i",
",",
"j",
")",
":",
"buttonData",
"}",
",",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"set",
"}",
")",
"\n\n",
"if",
"info",
".",
"Updated",
"==",
"0",
"{",
"// another one thread safe check",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
" ",
"i",
" ",
"j",
" ",
"b",
"ttonData, ",
"b",
"t.I",
"D",
", ",
"o",
".M",
"s",
"gID, ",
"o",
".I",
"n",
"lineMsgID, ",
"k",
"State)",
"",
"\n",
"}",
"\n\n",
"kb",
":=",
"msg",
".",
"InlineKeyboardMarkup",
"\n",
"kb",
".",
"Buttons",
"[",
"i",
"]",
"[",
"j",
"]",
".",
"Text",
"=",
"newButtonText",
"\n",
"kb",
".",
"Buttons",
"[",
"i",
"]",
"[",
"j",
"]",
".",
"State",
"=",
"newButtonState",
"\n\n",
"// todo: the stored keyboard can differ from actual because we update the whole keyboard in TG but update only target button locally",
"// But maybe it's ok...",
"_",
",",
"err",
"=",
"bot",
".",
"API",
".",
"Send",
"(",
"tg",
".",
"EditMessageReplyMarkupConfig",
"{",
"BaseEdit",
":",
"tg",
".",
"BaseEdit",
"{",
"ChatID",
":",
"om",
".",
"ChatID",
",",
"MessageID",
":",
"om",
".",
"MsgID",
",",
"InlineMessageID",
":",
"om",
".",
"InlineMsgID",
",",
"ReplyMarkup",
":",
"&",
"tg",
".",
"InlineKeyboardMarkup",
"{",
"InlineKeyboard",
":",
"kb",
".",
"tg",
"(",
")",
"}",
",",
"}",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// Oops. error is occurred – revert the original keyboard",
"err",
":=",
"c",
".",
"db",
".",
"C",
"(",
"\"",
"\"",
")",
".",
"UpdateId",
"(",
"msg",
".",
"ID",
",",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"bson",
".",
"M",
"{",
"\"",
"\"",
":",
"msg",
".",
"InlineKeyboardMarkup",
"}",
"}",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// EditInlineStateButton edit the outgoing message's inline button with a state
|
[
"EditInlineStateButton",
"edit",
"the",
"outgoing",
"message",
"s",
"inline",
"button",
"with",
"a",
"state"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/context.go#L789-L847
|
train
|
requilence/integram
|
context.go
|
AnswerInlineQueryWithPM
|
func (c *Context) AnswerInlineQueryWithPM(text string, parameter string) error {
bot := c.Bot()
_, err := bot.API.AnswerInlineQuery(tg.InlineConfig{IsPersonal: true, InlineQueryID: c.InlineQuery.ID, SwitchPMText: text, SwitchPMParameter: parameter})
n := time.Now()
c.inlineQueryAnsweredAt = &n
return err
}
|
go
|
func (c *Context) AnswerInlineQueryWithPM(text string, parameter string) error {
bot := c.Bot()
_, err := bot.API.AnswerInlineQuery(tg.InlineConfig{IsPersonal: true, InlineQueryID: c.InlineQuery.ID, SwitchPMText: text, SwitchPMParameter: parameter})
n := time.Now()
c.inlineQueryAnsweredAt = &n
return err
}
|
[
"func",
"(",
"c",
"*",
"Context",
")",
"AnswerInlineQueryWithPM",
"(",
"text",
"string",
",",
"parameter",
"string",
")",
"error",
"{",
"bot",
":=",
"c",
".",
"Bot",
"(",
")",
"\n",
"_",
",",
"err",
":=",
"bot",
".",
"API",
".",
"AnswerInlineQuery",
"(",
"tg",
".",
"InlineConfig",
"{",
"IsPersonal",
":",
"true",
",",
"InlineQueryID",
":",
"c",
".",
"InlineQuery",
".",
"ID",
",",
"SwitchPMText",
":",
"text",
",",
"SwitchPMParameter",
":",
"parameter",
"}",
")",
"\n",
"n",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"c",
".",
"inlineQueryAnsweredAt",
"=",
"&",
"n",
"\n",
"return",
"err",
"\n",
"}"
] |
// AnswerInlineQueryWithPM answer the inline query that triggered this request with Private Message redirect tip
|
[
"AnswerInlineQueryWithPM",
"answer",
"the",
"inline",
"query",
"that",
"triggered",
"this",
"request",
"with",
"Private",
"Message",
"redirect",
"tip"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/context.go#L868-L874
|
train
|
requilence/integram
|
context.go
|
AnswerCallbackQuery
|
func (c *Context) AnswerCallbackQuery(text string, showAlert bool) error {
if c.Callback == nil {
return errors.New("Callback to answer is not presented")
}
if c.Callback.AnsweredAt != nil {
return errors.New("Callback already answered")
}
bot := c.Bot()
_, err := bot.API.AnswerCallbackQuery(tg.CallbackConfig{CallbackQueryID: c.Callback.ID, Text: text, ShowAlert: showAlert})
if err == nil {
n := time.Now()
c.Callback.AnsweredAt = &n
}
return err
}
|
go
|
func (c *Context) AnswerCallbackQuery(text string, showAlert bool) error {
if c.Callback == nil {
return errors.New("Callback to answer is not presented")
}
if c.Callback.AnsweredAt != nil {
return errors.New("Callback already answered")
}
bot := c.Bot()
_, err := bot.API.AnswerCallbackQuery(tg.CallbackConfig{CallbackQueryID: c.Callback.ID, Text: text, ShowAlert: showAlert})
if err == nil {
n := time.Now()
c.Callback.AnsweredAt = &n
}
return err
}
|
[
"func",
"(",
"c",
"*",
"Context",
")",
"AnswerCallbackQuery",
"(",
"text",
"string",
",",
"showAlert",
"bool",
")",
"error",
"{",
"if",
"c",
".",
"Callback",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"Callback",
".",
"AnsweredAt",
"!=",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"bot",
":=",
"c",
".",
"Bot",
"(",
")",
"\n\n",
"_",
",",
"err",
":=",
"bot",
".",
"API",
".",
"AnswerCallbackQuery",
"(",
"tg",
".",
"CallbackConfig",
"{",
"CallbackQueryID",
":",
"c",
".",
"Callback",
".",
"ID",
",",
"Text",
":",
"text",
",",
"ShowAlert",
":",
"showAlert",
"}",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"n",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"c",
".",
"Callback",
".",
"AnsweredAt",
"=",
"&",
"n",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] |
// AnswerCallbackQuery answer the inline keyboard callback query that triggered this request with toast or alert
|
[
"AnswerCallbackQuery",
"answer",
"the",
"inline",
"keyboard",
"callback",
"query",
"that",
"triggered",
"this",
"request",
"with",
"toast",
"or",
"alert"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/context.go#L883-L900
|
train
|
requilence/integram
|
context.go
|
NewMessage
|
func (c *Context) NewMessage() *OutgoingMessage {
bot := c.Bot()
msg := &OutgoingMessage{}
msg.BotID = bot.ID
msg.FromID = bot.ID
msg.WebPreview = true
if c.Chat.ID != 0 {
msg.ChatID = c.Chat.ID
} else {
msg.ChatID = c.User.ID
}
msg.ctx = c
return msg
}
|
go
|
func (c *Context) NewMessage() *OutgoingMessage {
bot := c.Bot()
msg := &OutgoingMessage{}
msg.BotID = bot.ID
msg.FromID = bot.ID
msg.WebPreview = true
if c.Chat.ID != 0 {
msg.ChatID = c.Chat.ID
} else {
msg.ChatID = c.User.ID
}
msg.ctx = c
return msg
}
|
[
"func",
"(",
"c",
"*",
"Context",
")",
"NewMessage",
"(",
")",
"*",
"OutgoingMessage",
"{",
"bot",
":=",
"c",
".",
"Bot",
"(",
")",
"\n",
"msg",
":=",
"&",
"OutgoingMessage",
"{",
"}",
"\n",
"msg",
".",
"BotID",
"=",
"bot",
".",
"ID",
"\n",
"msg",
".",
"FromID",
"=",
"bot",
".",
"ID",
"\n",
"msg",
".",
"WebPreview",
"=",
"true",
"\n",
"if",
"c",
".",
"Chat",
".",
"ID",
"!=",
"0",
"{",
"msg",
".",
"ChatID",
"=",
"c",
".",
"Chat",
".",
"ID",
"\n",
"}",
"else",
"{",
"msg",
".",
"ChatID",
"=",
"c",
".",
"User",
".",
"ID",
"\n",
"}",
"\n",
"msg",
".",
"ctx",
"=",
"c",
"\n",
"return",
"msg",
"\n",
"}"
] |
// NewMessage creates the message targeted to the current chat
|
[
"NewMessage",
"creates",
"the",
"message",
"targeted",
"to",
"the",
"current",
"chat"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/context.go#L903-L916
|
train
|
requilence/integram
|
context.go
|
SendAction
|
func (c *Context) SendAction(s string) error {
_, err := c.Bot().API.Send(tg.NewChatAction(c.Chat.ID, s))
return err
}
|
go
|
func (c *Context) SendAction(s string) error {
_, err := c.Bot().API.Send(tg.NewChatAction(c.Chat.ID, s))
return err
}
|
[
"func",
"(",
"c",
"*",
"Context",
")",
"SendAction",
"(",
"s",
"string",
")",
"error",
"{",
"_",
",",
"err",
":=",
"c",
".",
"Bot",
"(",
")",
".",
"API",
".",
"Send",
"(",
"tg",
".",
"NewChatAction",
"(",
"c",
".",
"Chat",
".",
"ID",
",",
"s",
")",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// SendAction send the one of "typing", "upload_photo", "record_video", "upload_video", "record_audio", "upload_audio", "upload_document", "find_location"
|
[
"SendAction",
"send",
"the",
"one",
"of",
"typing",
"upload_photo",
"record_video",
"upload_video",
"record_audio",
"upload_audio",
"upload_document",
"find_location"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/context.go#L919-L922
|
train
|
requilence/integram
|
context.go
|
DownloadURL
|
func (c *Context) DownloadURL(url string) (filePath string, err error) {
ext := filepath.Ext(url)
out, err := ioutil.TempFile("", fmt.Sprintf("%d_%d", c.Bot().ID, c.Chat.ID))
if err != nil {
return "", err
}
out.Close()
os.Rename(out.Name(), out.Name()+ext)
out, err = os.OpenFile(out.Name()+ext, os.O_RDWR, 0666)
if err != nil {
return "", err
}
defer out.Close()
resp, err := http.Get(url)
if err != nil {
return "", err
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return "", errors.New("non 2xx resp status")
}
defer resp.Body.Close()
_, err = io.Copy(out, resp.Body)
if err != nil {
return "", err
}
return out.Name(), nil
}
|
go
|
func (c *Context) DownloadURL(url string) (filePath string, err error) {
ext := filepath.Ext(url)
out, err := ioutil.TempFile("", fmt.Sprintf("%d_%d", c.Bot().ID, c.Chat.ID))
if err != nil {
return "", err
}
out.Close()
os.Rename(out.Name(), out.Name()+ext)
out, err = os.OpenFile(out.Name()+ext, os.O_RDWR, 0666)
if err != nil {
return "", err
}
defer out.Close()
resp, err := http.Get(url)
if err != nil {
return "", err
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return "", errors.New("non 2xx resp status")
}
defer resp.Body.Close()
_, err = io.Copy(out, resp.Body)
if err != nil {
return "", err
}
return out.Name(), nil
}
|
[
"func",
"(",
"c",
"*",
"Context",
")",
"DownloadURL",
"(",
"url",
"string",
")",
"(",
"filePath",
"string",
",",
"err",
"error",
")",
"{",
"ext",
":=",
"filepath",
".",
"Ext",
"(",
"url",
")",
"\n",
"out",
",",
"err",
":=",
"ioutil",
".",
"TempFile",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"c",
".",
"Bot",
"(",
")",
".",
"ID",
",",
"c",
".",
"Chat",
".",
"ID",
")",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"out",
".",
"Close",
"(",
")",
"\n",
"os",
".",
"Rename",
"(",
"out",
".",
"Name",
"(",
")",
",",
"out",
".",
"Name",
"(",
")",
"+",
"ext",
")",
"\n\n",
"out",
",",
"err",
"=",
"os",
".",
"OpenFile",
"(",
"out",
".",
"Name",
"(",
")",
"+",
"ext",
",",
"os",
".",
"O_RDWR",
",",
"0666",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"defer",
"out",
".",
"Close",
"(",
")",
"\n\n",
"resp",
",",
"err",
":=",
"http",
".",
"Get",
"(",
"url",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"if",
"resp",
".",
"StatusCode",
"<",
"200",
"||",
"resp",
".",
"StatusCode",
">",
"299",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"_",
",",
"err",
"=",
"io",
".",
"Copy",
"(",
"out",
",",
"resp",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"out",
".",
"Name",
"(",
")",
",",
"nil",
"\n",
"}"
] |
// DownloadURL downloads the remote URL and returns the local file path
|
[
"DownloadURL",
"downloads",
"the",
"remote",
"URL",
"and",
"returns",
"the",
"local",
"file",
"path"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/context.go#L925-L958
|
train
|
requilence/integram
|
context.go
|
RAW
|
func (wc *WebhookContext) RAW() (*[]byte, error) {
var err error
if wc.body == nil {
wc.firstParse = true
wc.body, err = ioutil.ReadAll(wc.gin.Request.Body)
if err != nil {
return nil, err
}
}
return &wc.body, nil
}
|
go
|
func (wc *WebhookContext) RAW() (*[]byte, error) {
var err error
if wc.body == nil {
wc.firstParse = true
wc.body, err = ioutil.ReadAll(wc.gin.Request.Body)
if err != nil {
return nil, err
}
}
return &wc.body, nil
}
|
[
"func",
"(",
"wc",
"*",
"WebhookContext",
")",
"RAW",
"(",
")",
"(",
"*",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n",
"if",
"wc",
".",
"body",
"==",
"nil",
"{",
"wc",
".",
"firstParse",
"=",
"true",
"\n",
"wc",
".",
"body",
",",
"err",
"=",
"ioutil",
".",
"ReadAll",
"(",
"wc",
".",
"gin",
".",
"Request",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"&",
"wc",
".",
"body",
",",
"nil",
"\n",
"}"
] |
// RAW returns request's body
|
[
"RAW",
"returns",
"request",
"s",
"body"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/context.go#L961-L971
|
train
|
requilence/integram
|
context.go
|
JSON
|
func (wc *WebhookContext) JSON(out interface{}) error {
var err error
if wc.body == nil {
wc.firstParse = true
wc.body, err = ioutil.ReadAll(wc.gin.Request.Body)
if err != nil {
return err
}
}
err = json.Unmarshal(wc.body, out)
if err != nil && strings.HasPrefix(string(wc.body), "payload=") {
s := string(wc.body)
s, err = uurl.QueryUnescape(s[8:])
if err != nil {
return err
}
err = json.Unmarshal([]byte(s), out)
}
return err
}
|
go
|
func (wc *WebhookContext) JSON(out interface{}) error {
var err error
if wc.body == nil {
wc.firstParse = true
wc.body, err = ioutil.ReadAll(wc.gin.Request.Body)
if err != nil {
return err
}
}
err = json.Unmarshal(wc.body, out)
if err != nil && strings.HasPrefix(string(wc.body), "payload=") {
s := string(wc.body)
s, err = uurl.QueryUnescape(s[8:])
if err != nil {
return err
}
err = json.Unmarshal([]byte(s), out)
}
return err
}
|
[
"func",
"(",
"wc",
"*",
"WebhookContext",
")",
"JSON",
"(",
"out",
"interface",
"{",
"}",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"if",
"wc",
".",
"body",
"==",
"nil",
"{",
"wc",
".",
"firstParse",
"=",
"true",
"\n",
"wc",
".",
"body",
",",
"err",
"=",
"ioutil",
".",
"ReadAll",
"(",
"wc",
".",
"gin",
".",
"Request",
".",
"Body",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"wc",
".",
"body",
",",
"out",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"&&",
"strings",
".",
"HasPrefix",
"(",
"string",
"(",
"wc",
".",
"body",
")",
",",
"\"",
"\"",
")",
"{",
"s",
":=",
"string",
"(",
"wc",
".",
"body",
")",
"\n",
"s",
",",
"err",
"=",
"uurl",
".",
"QueryUnescape",
"(",
"s",
"[",
"8",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"[",
"]",
"byte",
"(",
"s",
")",
",",
"out",
")",
"\n\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] |
// JSON decodes the JSON in the request's body to the out interface
|
[
"JSON",
"decodes",
"the",
"JSON",
"in",
"the",
"request",
"s",
"body",
"to",
"the",
"out",
"interface"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/context.go#L974-L996
|
train
|
requilence/integram
|
context.go
|
Form
|
func (wc *WebhookContext) Form() uurl.Values {
//todo: bug, RAW() unavailable after ParseForm()
wc.gin.Request.ParseForm()
return wc.gin.Request.PostForm
}
|
go
|
func (wc *WebhookContext) Form() uurl.Values {
//todo: bug, RAW() unavailable after ParseForm()
wc.gin.Request.ParseForm()
return wc.gin.Request.PostForm
}
|
[
"func",
"(",
"wc",
"*",
"WebhookContext",
")",
"Form",
"(",
")",
"uurl",
".",
"Values",
"{",
"//todo: bug, RAW() unavailable after ParseForm()",
"wc",
".",
"gin",
".",
"Request",
".",
"ParseForm",
"(",
")",
"\n",
"return",
"wc",
".",
"gin",
".",
"Request",
".",
"PostForm",
"\n",
"}"
] |
// Form decodes the POST form in the request's body to the out interface
|
[
"Form",
"decodes",
"the",
"POST",
"form",
"in",
"the",
"request",
"s",
"body",
"to",
"the",
"out",
"interface"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/context.go#L999-L1003
|
train
|
requilence/integram
|
tgupdates.go
|
IsEventBotAddedToGroup
|
func (m *IncomingMessage) IsEventBotAddedToGroup() bool {
if (len(m.NewChatMembers) > 0 && m.NewChatMembers[0].ID == m.BotID) || m.GroupChatCreated || m.SuperGroupChatCreated {
return true
}
return false
}
|
go
|
func (m *IncomingMessage) IsEventBotAddedToGroup() bool {
if (len(m.NewChatMembers) > 0 && m.NewChatMembers[0].ID == m.BotID) || m.GroupChatCreated || m.SuperGroupChatCreated {
return true
}
return false
}
|
[
"func",
"(",
"m",
"*",
"IncomingMessage",
")",
"IsEventBotAddedToGroup",
"(",
")",
"bool",
"{",
"if",
"(",
"len",
"(",
"m",
".",
"NewChatMembers",
")",
">",
"0",
"&&",
"m",
".",
"NewChatMembers",
"[",
"0",
"]",
".",
"ID",
"==",
"m",
".",
"BotID",
")",
"||",
"m",
".",
"GroupChatCreated",
"||",
"m",
".",
"SuperGroupChatCreated",
"{",
"return",
"true",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// IsEventBotAddedToGroup returns true if user created a new group with bot as member or add the bot to existing group
|
[
"IsEventBotAddedToGroup",
"returns",
"true",
"if",
"user",
"created",
"a",
"new",
"group",
"with",
"bot",
"as",
"member",
"or",
"add",
"the",
"bot",
"to",
"existing",
"group"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/tgupdates.go#L768-L773
|
train
|
requilence/integram
|
tgupdates.go
|
GetCommand
|
func (m *IncomingMessage) GetCommand() (string, string) {
text := m.Text
if !strings.HasPrefix(text, "/") {
return "", text
}
r, _ := regexp.Compile("^/([a-zA-Z0-9_]+)(?:@[a-zA-Z0-9_]+)?.?(.*)?$")
match := r.FindStringSubmatch(text)
if len(match) == 3 {
return match[1], match[2]
} else if len(match) == 2 {
return match[1], ""
}
return "", ""
}
|
go
|
func (m *IncomingMessage) GetCommand() (string, string) {
text := m.Text
if !strings.HasPrefix(text, "/") {
return "", text
}
r, _ := regexp.Compile("^/([a-zA-Z0-9_]+)(?:@[a-zA-Z0-9_]+)?.?(.*)?$")
match := r.FindStringSubmatch(text)
if len(match) == 3 {
return match[1], match[2]
} else if len(match) == 2 {
return match[1], ""
}
return "", ""
}
|
[
"func",
"(",
"m",
"*",
"IncomingMessage",
")",
"GetCommand",
"(",
")",
"(",
"string",
",",
"string",
")",
"{",
"text",
":=",
"m",
".",
"Text",
"\n\n",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"text",
",",
"\"",
"\"",
")",
"{",
"return",
"\"",
"\"",
",",
"text",
"\n",
"}",
"\n",
"r",
",",
"_",
":=",
"regexp",
".",
"Compile",
"(",
"\"",
"\"",
")",
"\n",
"match",
":=",
"r",
".",
"FindStringSubmatch",
"(",
"text",
")",
"\n",
"if",
"len",
"(",
"match",
")",
"==",
"3",
"{",
"return",
"match",
"[",
"1",
"]",
",",
"match",
"[",
"2",
"]",
"\n",
"}",
"else",
"if",
"len",
"(",
"match",
")",
"==",
"2",
"{",
"return",
"match",
"[",
"1",
"]",
",",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
",",
"\"",
"\"",
"\n\n",
"}"
] |
// GetCommand parses received message text for bot command. Returns the command and after command text if presented
|
[
"GetCommand",
"parses",
"received",
"message",
"text",
"for",
"bot",
"command",
".",
"Returns",
"the",
"command",
"and",
"after",
"command",
"text",
"if",
"presented"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/tgupdates.go#L776-L791
|
train
|
requilence/integram
|
bots.go
|
Find
|
func (keyboard *InlineKeyboard) Find(buttonData string) (i, j int, but *InlineButton) {
for i, buttonsRow := range keyboard.Buttons {
for j, button := range buttonsRow {
if button.Data == buttonData {
return i, j, &button
}
}
}
return -1, -1, nil
}
|
go
|
func (keyboard *InlineKeyboard) Find(buttonData string) (i, j int, but *InlineButton) {
for i, buttonsRow := range keyboard.Buttons {
for j, button := range buttonsRow {
if button.Data == buttonData {
return i, j, &button
}
}
}
return -1, -1, nil
}
|
[
"func",
"(",
"keyboard",
"*",
"InlineKeyboard",
")",
"Find",
"(",
"buttonData",
"string",
")",
"(",
"i",
",",
"j",
"int",
",",
"but",
"*",
"InlineButton",
")",
"{",
"for",
"i",
",",
"buttonsRow",
":=",
"range",
"keyboard",
".",
"Buttons",
"{",
"for",
"j",
",",
"button",
":=",
"range",
"buttonsRow",
"{",
"if",
"button",
".",
"Data",
"==",
"buttonData",
"{",
"return",
"i",
",",
"j",
",",
"&",
"button",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"-",
"1",
",",
"-",
"1",
",",
"nil",
"\n",
"}"
] |
// Find the InlineButton in Keyboard by the Data
|
[
"Find",
"the",
"InlineButton",
"in",
"Keyboard",
"by",
"the",
"Data"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/bots.go#L305-L314
|
train
|
requilence/integram
|
bots.go
|
EditText
|
func (keyboard *InlineKeyboard) EditText(buttonData string, newText string) {
for i, buttonsRow := range keyboard.Buttons {
for j, button := range buttonsRow {
if button.Data == buttonData {
keyboard.Buttons[i][j].Text = newText
return
}
}
}
}
|
go
|
func (keyboard *InlineKeyboard) EditText(buttonData string, newText string) {
for i, buttonsRow := range keyboard.Buttons {
for j, button := range buttonsRow {
if button.Data == buttonData {
keyboard.Buttons[i][j].Text = newText
return
}
}
}
}
|
[
"func",
"(",
"keyboard",
"*",
"InlineKeyboard",
")",
"EditText",
"(",
"buttonData",
"string",
",",
"newText",
"string",
")",
"{",
"for",
"i",
",",
"buttonsRow",
":=",
"range",
"keyboard",
".",
"Buttons",
"{",
"for",
"j",
",",
"button",
":=",
"range",
"buttonsRow",
"{",
"if",
"button",
".",
"Data",
"==",
"buttonData",
"{",
"keyboard",
".",
"Buttons",
"[",
"i",
"]",
"[",
"j",
"]",
".",
"Text",
"=",
"newText",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// EditText find the InlineButton in Keyboard by the Data and change the text of that button
|
[
"EditText",
"find",
"the",
"InlineButton",
"in",
"Keyboard",
"by",
"the",
"Data",
"and",
"change",
"the",
"text",
"of",
"that",
"button"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/bots.go#L317-L326
|
train
|
requilence/integram
|
bots.go
|
AddPMSwitchButton
|
func (keyboard *InlineKeyboard) AddPMSwitchButton(b *Bot, text string, param string) {
if len(keyboard.Buttons) > 0 && len(keyboard.Buttons[0]) > 0 && keyboard.Buttons[0][0].Text == text {
return
}
keyboard.PrependRows(InlineButtons{InlineButton{Text: text, URL: b.PMURL(param)}})
}
|
go
|
func (keyboard *InlineKeyboard) AddPMSwitchButton(b *Bot, text string, param string) {
if len(keyboard.Buttons) > 0 && len(keyboard.Buttons[0]) > 0 && keyboard.Buttons[0][0].Text == text {
return
}
keyboard.PrependRows(InlineButtons{InlineButton{Text: text, URL: b.PMURL(param)}})
}
|
[
"func",
"(",
"keyboard",
"*",
"InlineKeyboard",
")",
"AddPMSwitchButton",
"(",
"b",
"*",
"Bot",
",",
"text",
"string",
",",
"param",
"string",
")",
"{",
"if",
"len",
"(",
"keyboard",
".",
"Buttons",
")",
">",
"0",
"&&",
"len",
"(",
"keyboard",
".",
"Buttons",
"[",
"0",
"]",
")",
">",
"0",
"&&",
"keyboard",
".",
"Buttons",
"[",
"0",
"]",
"[",
"0",
"]",
".",
"Text",
"==",
"text",
"{",
"return",
"\n",
"}",
"\n",
"keyboard",
".",
"PrependRows",
"(",
"InlineButtons",
"{",
"InlineButton",
"{",
"Text",
":",
"text",
",",
"URL",
":",
"b",
".",
"PMURL",
"(",
"param",
")",
"}",
"}",
")",
"\n",
"}"
] |
// AddPMSwitchButton add the button to switch to PM as a first row in the InlineKeyboard
|
[
"AddPMSwitchButton",
"add",
"the",
"button",
"to",
"switch",
"to",
"PM",
"as",
"a",
"first",
"row",
"in",
"the",
"InlineKeyboard"
] |
7d85c728a299bf2ad121ae1874c0bd39fc48c231
|
https://github.com/requilence/integram/blob/7d85c728a299bf2ad121ae1874c0bd39fc48c231/bots.go#L329-L334
|
train
|
Subsets and Splits
SQL Console for semeru/code-text-go
Retrieves a limited set of code samples with their languages, with a specific case adjustment for 'Go' language.