4
0
mirror of https://github.com/cwinfo/matterbridge.git synced 2025-10-07 17:13:58 +00:00

Update dependencies (#1822)

This commit is contained in:
Wim
2022-05-02 00:10:54 +02:00
committed by GitHub
parent 888c8b9a84
commit 81e6f75aa4
54 changed files with 640 additions and 232 deletions

View File

@@ -7,9 +7,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [1.5.4] - 2022-04-25
* Windows: add missing defer to `Watcher.WatchList` [#447](https://github.com/fsnotify/fsnotify/pull/447)
* go.mod: use latest x/sys [#444](https://github.com/fsnotify/fsnotify/pull/444)
* Fix compilation for OpenBSD [#443](https://github.com/fsnotify/fsnotify/pull/443)
## [1.5.3] - 2022-04-22
* This version is retracted. An incorrect branch is published accidentally [#445](https://github.com/fsnotify/fsnotify/issues/445)
## [1.5.2] - 2022-04-21
* Add a feature to return the directories and files that are being monitored [#374](https://github.com/fsnotify/fsnotify/pull/374)
* Fix potential crash on windows if `raw.FileNameLength` exceeds `syscall.MAX_PATH` [#361](https://github.com/fsnotify/fsnotify/pull/361)
* Allow build on unsupported GOOS [#424](https://github.com/fsnotify/fsnotify/pull/424)
* Don't set `poller.fd` twice in `newFdPoller` [#406](https://github.com/fsnotify/fsnotify/pull/406)
* fix go vet warnings: call to `(*T).Fatalf` from a non-test goroutine [#416](https://github.com/fsnotify/fsnotify/pull/416)
## [1.5.1] - 2021-08-24
* Revert Add AddRaw to not follow symlinks
* Revert Add AddRaw to not follow symlinks [#394](https://github.com/fsnotify/fsnotify/pull/394)
## [1.5.0] - 2021-08-20

View File

@@ -48,18 +48,6 @@ fsnotify uses build tags to compile different code on Linux, BSD, macOS, and Win
Before doing a pull request, please do your best to test your changes on multiple platforms, and list which platforms you were able/unable to test on.
To aid in cross-platform testing there is a Vagrantfile for Linux and BSD.
* Install [Vagrant](http://www.vagrantup.com/) and [VirtualBox](https://www.virtualbox.org/)
* Setup [Vagrant Gopher](https://github.com/nathany/vagrant-gopher) in your `src` folder.
* Run `vagrant up` from the project folder. You can also setup just one box with `vagrant up linux` or `vagrant up bsd` (note: the BSD box doesn't support Windows hosts at this time, and NFS may prompt for your host OS password)
* Once setup, you can run the test suite on a given OS with a single command `vagrant ssh linux -c 'cd fsnotify/fsnotify; go test'`.
* When you're done, you will want to halt or destroy the Vagrant boxes.
Notice: fsnotify file system events won't trigger in shared folders. The tests get around this limitation by using the /tmp directory.
Right now there is no equivalent solution for Windows and macOS, but there are Windows VMs [freely available from Microsoft](http://www.modern.ie/en-us/virtualization-tools#downloads).
### Maintainers
Help maintaining fsnotify is welcome. To be a maintainer:
@@ -67,11 +55,6 @@ Help maintaining fsnotify is welcome. To be a maintainer:
* Submit a pull request and sign the CLA as above.
* You must be able to run the test suite on Mac, Windows, Linux and BSD.
To keep master clean, the fsnotify project uses the "apply mail" workflow outlined in Nathaniel Talbott's post ["Merge pull request" Considered Harmful][am]. This requires installing [hub][].
All code changes should be internal pull requests.
Releases are tagged using [Semantic Versioning](http://semver.org/).
[hub]: https://github.com/github/hub
[am]: http://blog.spreedly.com/2014/06/24/merge-pull-request-considered-harmful/#.VGa5yZPF_Zs

View File

@@ -1,40 +1,120 @@
# WARNING
# File system notifications for Go
If you are reading this, you use `master` branch of this repository,
which is wrong.
[![Go Reference](https://pkg.go.dev/badge/github.com/fsnotify/fsnotify.svg)](https://pkg.go.dev/github.com/fsnotify/fsnotify) [![Go Report Card](https://goreportcard.com/badge/github.com/fsnotify/fsnotify)](https://goreportcard.com/report/github.com/fsnotify/fsnotify) [![Maintainers Wanted](https://img.shields.io/badge/maintainers-wanted-red.svg)](https://github.com/fsnotify/fsnotify/issues/413)
This branch
- should not be used;
- is not maintained;
- is not supported;
- will be removed soon.
fsnotify utilizes [`golang.org/x/sys`](https://pkg.go.dev/golang.org/x/sys) rather than [`syscall`](https://pkg.go.dev/syscall) from the standard library.
You should switch to using the default branch instead.
Cross platform: Windows, Linux, BSD and macOS.
## Using git
| Adapter | OS | Status |
| --------------------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| inotify | Linux 2.6.27 or later, Android\* | Supported |
| kqueue | BSD, macOS, iOS\* | Supported |
| ReadDirectoryChangesW | Windows | Supported |
| FSEvents | macOS | [Planned](https://github.com/fsnotify/fsnotify/issues/11) |
| FEN | Solaris 11 | [In Progress](https://github.com/fsnotify/fsnotify/pull/371) |
| fanotify | Linux 2.6.37+ | [Maybe](https://github.com/fsnotify/fsnotify/issues/114) |
| USN Journals | Windows | [Maybe](https://github.com/fsnotify/fsnotify/issues/53) |
| Polling | *All* | [Maybe](https://github.com/fsnotify/fsnotify/issues/9) |
Here's how to switch your existing local copy of this repository from `master`
to `main` (assuming the remote name is `origin`):
\* Android and iOS are untested.
```
git branch -m master main
git fetch origin
git branch -u origin/main main
git remote set-head origin -a
Please see [the documentation](https://pkg.go.dev/github.com/fsnotify/fsnotify) and consult the [FAQ](#faq) for usage information.
## API stability
fsnotify is a fork of [howeyc/fsnotify](https://github.com/howeyc/fsnotify) with a new API as of v1.0. The API is based on [this design document](http://goo.gl/MrYxyA).
All [releases](https://github.com/fsnotify/fsnotify/releases) are tagged based on [Semantic Versioning](http://semver.org/).
## Usage
```go
package main
import (
"log"
"github.com/fsnotify/fsnotify"
)
func main() {
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
defer watcher.Close()
done := make(chan bool)
go func() {
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
log.Println("event:", event)
if event.Op&fsnotify.Write == fsnotify.Write {
log.Println("modified file:", event.Name)
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.Println("error:", err)
}
}
}()
err = watcher.Add("/tmp/foo")
if err != nil {
log.Fatal(err)
}
<-done
}
```
In addition to the above, if you want to remove the leftover `origin/master`
remote branch (NOTE this also removes all other remote branches that no longer
exist in `origin`):
## Contributing
```
git remote prune origin
```
Please refer to [CONTRIBUTING][] before opening an issue or pull request.
## Background
## FAQ
The `master` branch was renamed to `main`, causing an issue with
Yocto/OpenEmbedded's meta-virtualization layer, which explicitly refers
to `master` branch of this repository (see #426).
**When a file is moved to another directory is it still being watched?**
No (it shouldn't be, unless you are watching where it was moved to).
**When I watch a directory, are all subdirectories watched as well?**
No, you must add watches for any directory you want to watch (a recursive watcher is on the roadmap [#18][]).
**Do I have to watch the Error and Event channels in a separate goroutine?**
As of now, yes. Looking into making this single-thread friendly (see [howeyc #7][#7])
**Why am I receiving multiple events for the same file on OS X?**
Spotlight indexing on OS X can result in multiple events (see [howeyc #62][#62]). A temporary workaround is to add your folder(s) to the *Spotlight Privacy settings* until we have a native FSEvents implementation (see [#11][]).
**How many files can be watched at once?**
There are OS-specific limits as to how many watches can be created:
* Linux: /proc/sys/fs/inotify/max_user_watches contains the limit, reaching this limit results in a "no space left on device" error.
* BSD / OSX: sysctl variables "kern.maxfiles" and "kern.maxfilesperproc", reaching these limits results in a "too many open files" error.
**Why don't notifications work with NFS filesystems or filesystem in userspace (FUSE)?**
fsnotify requires support from underlying OS to work. The current NFS protocol does not provide network level support for file notifications.
[#62]: https://github.com/howeyc/fsnotify/issues/62
[#18]: https://github.com/fsnotify/fsnotify/issues/18
[#11]: https://github.com/fsnotify/fsnotify/issues/11
[#7]: https://github.com/howeyc/fsnotify/issues/7
[contributing]: https://github.com/fsnotify/fsnotify/blob/master/CONTRIBUTING.md
## Related Projects
* [notify](https://github.com/rjeczalik/notify)
* [fsevents](https://github.com/fsnotify/fsevents)
This temporary branch is created to alleviate the Yocto/OE issue.

View File

@@ -0,0 +1,36 @@
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !darwin && !dragonfly && !freebsd && !openbsd && !linux && !netbsd && !solaris && !windows
// +build !darwin,!dragonfly,!freebsd,!openbsd,!linux,!netbsd,!solaris,!windows
package fsnotify
import (
"fmt"
"runtime"
)
// Watcher watches a set of files, delivering events to a channel.
type Watcher struct{}
// NewWatcher establishes a new watcher with the underlying OS and begins waiting for events.
func NewWatcher() (*Watcher, error) {
return nil, fmt.Errorf("fsnotify not supported on %s", runtime.GOOS)
}
// Close removes all watches and closes the events channel.
func (w *Watcher) Close() error {
return nil
}
// Add starts watching the named file or directory (non-recursively).
func (w *Watcher) Add(name string) error {
return nil
}
// Remove stops watching the the named file or directory (non-recursively).
func (w *Watcher) Remove(name string) error {
return nil
}

View File

@@ -163,6 +163,19 @@ func (w *Watcher) Remove(name string) error {
return nil
}
// WatchList returns the directories and files that are being monitered.
func (w *Watcher) WatchList() []string {
w.mu.Lock()
defer w.mu.Unlock()
entries := make([]string, 0, len(w.watches))
for pathname := range w.watches {
entries = append(entries, pathname)
}
return entries
}
type watch struct {
wd uint32 // Watch descriptor (as returned by the inotify_add_watch() syscall)
flags uint32 // inotify flags of this watch (see inotify(7) for the list of valid flags)

View File

@@ -38,7 +38,6 @@ func newFdPoller(fd int) (*fdPoller, error) {
poller.close()
}
}()
poller.fd = fd
// Create epoll fd
poller.epfd, errno = unix.EpollCreate1(unix.EPOLL_CLOEXEC)

View File

@@ -148,6 +148,19 @@ func (w *Watcher) Remove(name string) error {
return nil
}
// WatchList returns the directories and files that are being monitered.
func (w *Watcher) WatchList() []string {
w.mu.Lock()
defer w.mu.Unlock()
entries := make([]string, 0, len(w.watches))
for pathname := range w.watches {
entries = append(entries, pathname)
}
return entries
}
// Watch all events (except NOTE_EXTEND, NOTE_LINK, NOTE_REVOKE)
const noteAllEvents = unix.NOTE_DELETE | unix.NOTE_WRITE | unix.NOTE_ATTRIB | unix.NOTE_RENAME

View File

@@ -12,6 +12,7 @@ import (
"fmt"
"os"
"path/filepath"
"reflect"
"runtime"
"sync"
"syscall"
@@ -96,6 +97,21 @@ func (w *Watcher) Remove(name string) error {
return <-in.reply
}
// WatchList returns the directories and files that are being monitered.
func (w *Watcher) WatchList() []string {
w.mu.Lock()
defer w.mu.Unlock()
entries := make([]string, 0, len(w.watches))
for _, entry := range w.watches {
for _, watchEntry := range entry {
entries = append(entries, watchEntry.path)
}
}
return entries
}
const (
// Options for AddWatch
sysFSONESHOT = 0x80000000
@@ -452,8 +468,16 @@ func (w *Watcher) readEvents() {
// Point "raw" to the event in the buffer
raw := (*syscall.FileNotifyInformation)(unsafe.Pointer(&watch.buf[offset]))
buf := (*[syscall.MAX_PATH]uint16)(unsafe.Pointer(&raw.FileName))
name := syscall.UTF16ToString(buf[:raw.FileNameLength/2])
// TODO: Consider using unsafe.Slice that is available from go1.17
// https://stackoverflow.com/questions/51187973/how-to-create-an-array-or-a-slice-from-an-array-unsafe-pointer-in-golang
// instead of using a fixed syscall.MAX_PATH buf, we create a buf that is the size of the path name
size := int(raw.FileNameLength / 2)
var buf []uint16
sh := (*reflect.SliceHeader)(unsafe.Pointer(&buf))
sh.Data = uintptr(unsafe.Pointer(&raw.FileName))
sh.Len = size
sh.Cap = size
name := syscall.UTF16ToString(buf)
fullname := filepath.Join(watch.path, name)
var mask uint64

View File

@@ -1,6 +1,6 @@
# Markdown Parser and HTML Renderer for Go
[![pkg.go.dev](https://pkg.go.dev/badge/github.com/gomarkdown/markdown)](https://pkg.go.dev/badge/github.com/gomarkdown/markdown)
[![pkg.go.dev](https://pkg.go.dev/badge/github.com/gomarkdown/markdown)](https://pkg.go.dev/github.com/gomarkdown/markdown)
Package `github.com/gomarkdown/markdown` is a very fast Go library for parsing [Markdown](https://daringfireball.net/projects/markdown/) documents and rendering them to HTML.

View File

@@ -26,8 +26,8 @@ links or code blocks.
// a very dummy render hook that will output "code_replacements" instead of
// <code>${content}</code> emitted by html.Renderer
func renderHookCodeBlock(w io.Writer, node *ast.Node, entering bool) (ast.WalkStatus, bool) {
_, ok := node.Data.(*ast.CodeBlockData)
func renderHookCodeBlock(w io.Writer, node ast.Node, entering bool) (ast.WalkStatus, bool) {
_, ok := node.(*ast.CodeBlock)
if !ok {
return ast.GoToNext, false
}

View File

@@ -28,6 +28,7 @@ linters-settings:
gocritic:
disabled-checks:
- hugeParam
- ifElseChain
enabled-tags:
- diagnostic
- opinionated

View File

@@ -52,7 +52,7 @@ func ParseEvent(raw string) (e *Event) {
i = 0
}
if raw[0] == messagePrefix {
if raw != "" && raw[0] == messagePrefix {
// Prefix ends with a space.
i = strings.IndexByte(raw, eventSpace)
@@ -297,7 +297,9 @@ func (e *Event) Bytes() []byte {
buffer.Truncate(maxLength)
}
out := buffer.Bytes()
// If we truncated in the middle of a utf8 character, we need to remove
// the other (now invalid) bytes.
out := bytes.ToValidUTF8(buffer.Bytes(), nil)
// Strip newlines and carriage returns.
for i := 0; i < len(out); i++ {

View File

@@ -714,6 +714,10 @@ func (m *Client) SetLogLevel(level string) {
}
func (m *Client) HandleRatelimit(name string, resp *model.Response) error {
if resp == nil {
return fmt.Errorf("Got a nil model response from %s", name)
}
if resp.StatusCode != 429 {
return fmt.Errorf("StatusCode error: %d", resp.StatusCode)
}

View File

@@ -22,7 +22,7 @@ a “modified version” or “work based on” Mattermost as these terms are de
MATTERMOST TRADEMARK GUIDELINES
Your use of the mark Mattermost is subject to Mattermost, Inc's prior written approval and our organizations Trademark
Standards of Use at http://www.mattermost.org/trademark-standards-of-use/. For trademark approval or any questions
Standards of Use at https://mattermost.com/trademark-standards-of-use/. For trademark approval or any questions
you have about using these trademarks, please email trademark@mattermost.com
------------------------------------------------------------------------------------------------------------------------------

View File

@@ -178,6 +178,14 @@ func (o *Channel) DeleteAt_() float64 {
return float64(o.DeleteAt)
}
func (o *Channel) LastPostAt_() float64 {
return float64(o.LastPostAt)
}
func (o *Channel) TotalMsgCount_() float64 {
return float64(o.TotalMsgCount)
}
func (o *Channel) DeepCopy() *Channel {
copy := *o
if copy.SchemeId != nil {

View File

@@ -37,12 +37,11 @@ const (
)
// SidebarCategory represents the corresponding DB table
// SortOrder is never returned to the user and only used for queries
type SidebarCategory struct {
Id string `json:"id"`
UserId string `json:"user_id"`
TeamId string `json:"team_id"`
SortOrder int64 `json:"-"`
SortOrder int64 `json:"sort_order"`
Sorting SidebarCategorySorting `json:"sorting"`
Type SidebarCategoryType `json:"type"`
DisplayName string `json:"display_name"`

View File

@@ -7931,3 +7931,16 @@ func (c *Client4) GetUsersWithInvalidEmails(page, perPage int) ([]*User, *Respon
}
return list, BuildResponse(r), nil
}
func (c *Client4) GetAppliedSchemaMigrations() ([]AppliedMigration, *Response, error) {
r, err := c.DoAPIGet(c.systemRoute()+"/schema/version", "")
if err != nil {
return nil, BuildResponse(r), err
}
defer closeBody(r)
var list []AppliedMigration
if jsonErr := json.NewDecoder(r.Body).Decode(&list); jsonErr != nil {
return nil, nil, NewAppError("GetUsers", "api.unmarshal_error", nil, jsonErr.Error(), http.StatusInternalServerError)
}
return list, BuildResponse(r), nil
}

View File

@@ -93,6 +93,9 @@ const (
EmailNotificationContentsFull = "full"
EmailNotificationContentsGeneric = "generic"
EmailSMTPDefaultServer = "localhost"
EmailSMTPDefaultPort = "10025"
SitenameMaxLength = 30
ServiceSettingsDefaultSiteURL = "http://localhost:8065"
@@ -128,9 +131,9 @@ const (
SupportSettingsDefaultTermsOfServiceLink = "https://mattermost.com/terms-of-use/"
SupportSettingsDefaultPrivacyPolicyLink = "https://mattermost.com/privacy-policy/"
SupportSettingsDefaultAboutLink = "https://about.mattermost.com/default-about/"
SupportSettingsDefaultHelpLink = "https://about.mattermost.com/default-help/"
SupportSettingsDefaultReportAProblemLink = "https://about.mattermost.com/default-report-a-problem/"
SupportSettingsDefaultAboutLink = "https://docs.mattermost.com/about/product.html/"
SupportSettingsDefaultHelpLink = "https://mattermost.com/default-help/"
SupportSettingsDefaultReportAProblemLink = "https://mattermost.com/default-report-a-problem/"
SupportSettingsDefaultSupportEmail = ""
SupportSettingsDefaultReAcceptancePeriod = 365
@@ -167,8 +170,8 @@ const (
SamlSettingsDefaultCanonicalAlgorithm = SamlSettingsCanonicalAlgorithmC14n
NativeappSettingsDefaultAppDownloadLink = "https://mattermost.com/download/#mattermostApps"
NativeappSettingsDefaultAndroidAppDownloadLink = "https://about.mattermost.com/mattermost-android-app/"
NativeappSettingsDefaultIosAppDownloadLink = "https://about.mattermost.com/mattermost-ios-app/"
NativeappSettingsDefaultAndroidAppDownloadLink = "https://mattermost.com/mattermost-android-app/"
NativeappSettingsDefaultIosAppDownloadLink = "https://mattermost.com/mattermost-ios-app/"
ExperimentalSettingsDefaultLinkMetadataTimeoutMilliseconds = 5000
@@ -778,7 +781,7 @@ func (s *ServiceSettings) SetDefaults(isUpdate bool) {
}
if s.ThreadAutoFollow == nil {
s.ThreadAutoFollow = NewBool(false)
s.ThreadAutoFollow = NewBool(true)
}
if s.CollapsedThreads == nil {
@@ -1598,11 +1601,11 @@ func (s *EmailSettings) SetDefaults(isUpdate bool) {
}
if s.SMTPServer == nil || *s.SMTPServer == "" {
s.SMTPServer = NewString("localhost")
s.SMTPServer = NewString(EmailSMTPDefaultServer)
}
if s.SMTPPort == nil || *s.SMTPPort == "" {
s.SMTPPort = NewString("10025")
s.SMTPPort = NewString(EmailSMTPDefaultPort)
}
if s.SMTPServerTimeout == nil || *s.SMTPServerTimeout == 0 {
@@ -1739,7 +1742,7 @@ type SupportSettings struct {
AboutLink *string `access:"site_customization,write_restrictable,cloud_restrictable"`
HelpLink *string `access:"site_customization,write_restrictable,cloud_restrictable"`
ReportAProblemLink *string `access:"site_customization,write_restrictable,cloud_restrictable"`
SupportEmail *string `access:"site_customization"`
SupportEmail *string `access:"site_notifications"`
CustomTermsOfServiceEnabled *bool `access:"compliance_custom_terms_of_service"`
CustomTermsOfServiceReAcceptancePeriod *int `access:"compliance_custom_terms_of_service"`
EnableAskCommunityLink *bool `access:"site_customization"`
@@ -2748,6 +2751,11 @@ func (s *PluginSettings) SetDefaults(ls LogSettings) {
s.PluginStates["focalboard"] = &PluginState{Enable: true}
}
if s.PluginStates["com.mattermost.apps"] == nil {
// Enable the Apps plugin by default
s.PluginStates["com.mattermost.apps"] = &PluginState{Enable: true}
}
if s.EnableMarketplace == nil {
s.EnableMarketplace = NewBool(PluginSettingsDefaultEnableMarketplace)
}

View File

@@ -38,9 +38,6 @@ type FeatureFlags struct {
PermalinkPreviews bool
// Enable the Global Header
GlobalHeader bool
// Determine whether when a user gets created, they'll have noisy notifications e.g. Send desktop notifications for all activity
NewAccountNoisy bool
@@ -56,17 +53,11 @@ type FeatureFlags struct {
// Enable Create First Channel
GuidedChannelCreation bool
// Determine after which duration in hours to send a second invitation to someone that didn't join after the initial invite, possible values = ("48", "72")
ResendInviteEmailInterval string
// A/B test for whether radio buttons or toggle button is more effective in in-screen invite to team modal ("none", "toggle")
InviteToTeam string
CustomGroups bool
// Enable inline post editing
InlinePostEditing bool
// Enable DataRetention for Boards
BoardsDataRetention bool
@@ -77,9 +68,6 @@ type FeatureFlags struct {
// Enable special onboarding flow for first admin
UseCaseOnboarding bool
// Enable Workspace optimization dashboard
WorkspaceOptimizationDashboard bool
// Enable GraphQL feature
GraphQL bool
}
@@ -90,26 +78,22 @@ func (f *FeatureFlags) SetDefaults() {
f.CloudDelinquentEmailJobsEnabled = false
f.CollapsedThreads = true
f.EnableRemoteClusterService = false
f.AppsEnabled = false
f.AppsEnabled = true
f.AppBarEnabled = false
f.PluginApps = ""
f.PluginFocalboard = ""
f.PermalinkPreviews = true
f.GlobalHeader = true
f.NewAccountNoisy = false
f.CallsMobile = false
f.BoardsFeatureFlags = ""
f.AddMembersToChannel = "top"
f.GuidedChannelCreation = false
f.ResendInviteEmailInterval = ""
f.InviteToTeam = "none"
f.CustomGroups = true
f.InlinePostEditing = false
f.BoardsDataRetention = false
f.NormalizeLdapDNs = false
f.EnableInactivityCheckJob = true
f.UseCaseOnboarding = true
f.WorkspaceOptimizationDashboard = true
f.GraphQL = false
}
func (f *FeatureFlags) Plugins() map[string]string {

View File

@@ -37,4 +37,5 @@ const (
MigrationKeyAddIntegrationsSubsectionPermissions = "integrations_subsection_permissions"
MigrationKeyAddPlaybooksPermissions = "playbooks_permissions"
MigrationKeyAddCustomUserGroupsPermissions = "custom_groups_permissions"
MigrationKeyAddPlayboosksManageRolesPermissions = "playbooks_manage_roles"
)

View File

@@ -18,17 +18,18 @@ const (
)
type OAuthApp struct {
Id string `json:"id"`
CreatorId string `json:"creator_id"`
CreateAt int64 `json:"create_at"`
UpdateAt int64 `json:"update_at"`
ClientSecret string `json:"client_secret"`
Name string `json:"name"`
Description string `json:"description"`
IconURL string `json:"icon_url"`
CallbackUrls StringArray `json:"callback_urls"`
Homepage string `json:"homepage"`
IsTrusted bool `json:"is_trusted"`
Id string `json:"id"`
CreatorId string `json:"creator_id"`
CreateAt int64 `json:"create_at"`
UpdateAt int64 `json:"update_at"`
ClientSecret string `json:"client_secret"`
Name string `json:"name"`
Description string `json:"description"`
IconURL string `json:"icon_url"`
CallbackUrls StringArray `json:"callback_urls"`
Homepage string `json:"homepage"`
IsTrusted bool `json:"is_trusted"`
MattermostAppID string `json:"mattermost_app_id"`
}
// IsValid validates the app and returns an error if it isn't configured
@@ -83,6 +84,10 @@ func (a *OAuthApp) IsValid() *AppError {
}
}
if len(a.MattermostAppID) > 32 {
return NewAppError("OAuthApp.IsValid", "model.oauth.is_valid.mattermost_app_id.app_error", nil, "app_id="+a.Id, http.StatusBadRequest)
}
return nil
}

View File

@@ -337,12 +337,14 @@ var PermissionSysconsoleWriteExperimentalBleve *Permission
var PermissionPublicPlaybookCreate *Permission
var PermissionPublicPlaybookManageProperties *Permission
var PermissionPublicPlaybookManageMembers *Permission
var PermissionPublicPlaybookManageRoles *Permission
var PermissionPublicPlaybookView *Permission
var PermissionPublicPlaybookMakePrivate *Permission
var PermissionPrivatePlaybookCreate *Permission
var PermissionPrivatePlaybookManageProperties *Permission
var PermissionPrivatePlaybookManageMembers *Permission
var PermissionPrivatePlaybookManageRoles *Permission
var PermissionPrivatePlaybookView *Permission
var PermissionPrivatePlaybookMakePublic *Permission
@@ -1970,6 +1972,13 @@ func initializePermissions() {
PermissionScopePlaybook,
}
PermissionPublicPlaybookManageRoles = &Permission{
"playbook_public_manage_roles",
"",
"",
PermissionScopePlaybook,
}
PermissionPublicPlaybookView = &Permission{
"playbook_public_view",
"",
@@ -2005,6 +2014,13 @@ func initializePermissions() {
PermissionScopePlaybook,
}
PermissionPrivatePlaybookManageRoles = &Permission{
"playbook_private_manage_roles",
"",
"",
PermissionScopePlaybook,
}
PermissionPrivatePlaybookView = &Permission{
"playbook_private_view",
"",
@@ -2327,10 +2343,12 @@ func initializePermissions() {
PlaybookScopedPermissions := []*Permission{
PermissionPublicPlaybookManageProperties,
PermissionPublicPlaybookManageMembers,
PermissionPublicPlaybookManageRoles,
PermissionPublicPlaybookView,
PermissionPublicPlaybookMakePrivate,
PermissionPrivatePlaybookManageProperties,
PermissionPrivatePlaybookManageMembers,
PermissionPrivatePlaybookManageRoles,
PermissionPrivatePlaybookView,
PermissionPrivatePlaybookMakePublic,
PermissionRunCreate,

View File

@@ -17,6 +17,7 @@ const (
PushTypeClear = "clear"
PushTypeUpdateBadge = "update_badge"
PushTypeSession = "session"
PushTypeTest = "test"
PushMessageV2 = "v2"
PushSoundNone = "none"

View File

@@ -836,8 +836,10 @@ func MakeDefaultRoles() map[string]*Role {
Description: "authentication.roles.playbook_admin.description",
Permissions: []string{
PermissionPublicPlaybookManageMembers.Id,
PermissionPublicPlaybookManageRoles.Id,
PermissionPublicPlaybookManageProperties.Id,
PermissionPrivatePlaybookManageMembers.Id,
PermissionPrivatePlaybookManageRoles.Id,
PermissionPrivatePlaybookManageProperties.Id,
PermissionPublicPlaybookMakePrivate.Id,
},

View File

@@ -24,6 +24,8 @@ const (
SessionPropUserAccessTokenId = "user_access_token_id"
SessionPropIsBot = "is_bot"
SessionPropIsBotValue = "true"
SessionPropOAuthAppID = "oauth_app_id"
SessionPropMattermostAppID = "mattermost_app_id"
SessionTypeUserAccessToken = "UserAccessToken"
SessionTypeCloudKey = "CloudKey"
SessionTypeRemoteclusterToken = "RemoteClusterToken"
@@ -218,3 +220,11 @@ func (s *Session) GetCSRF() string {
return s.Props["csrf"]
}
func (s *Session) CreateAt_() float64 {
return float64(s.CreateAt)
}
func (s *Session) ExpiresAt_() float64 {
return float64(s.ExpiresAt)
}

View File

@@ -79,6 +79,8 @@ type ServerBusyState struct {
type SupportPacket struct {
ServerOS string `yaml:"server_os"`
ServerArchitecture string `yaml:"server_architecture"`
ServerVersion string `yaml:"server_version"`
BuildHash string `yaml:"build_hash,omitempty"`
DatabaseType string `yaml:"database_type"`
DatabaseVersion string `yaml:"database_version"`
LdapVendorName string `yaml:"ldap_vendor_name,omitempty"`
@@ -173,3 +175,8 @@ type WarnMetricStatus struct {
type SendWarnMetricAck struct {
ForceAck bool `json:"forceAck"`
}
type AppliedMigration struct {
Version int `json:"version"`
Name string `json:"name"`
}

View File

@@ -251,3 +251,16 @@ func (o *Team) Patch(patch *TeamPatch) {
func (o *Team) IsGroupConstrained() bool {
return o.GroupConstrained != nil && *o.GroupConstrained
}
// The following are some GraphQL methods necessary to return the
// data in float64 type. The spec doesn't support 64 bit integers,
// so we have to pass the data in float64. The _ at the end is
// a hack to keep the attribute name same in GraphQL schema.
func (o *Team) UpdateAt_() float64 {
return float64(o.UpdateAt)
}
func (o *Team) LastTeamIconUpdate_() float64 {
return float64(o.LastTeamIconUpdate)
}

View File

@@ -13,6 +13,8 @@ import (
// It should be maintained in chronological order with most current
// release at the front of the list.
var versions = []string{
"6.6.1",
"6.6.0",
"6.5.0",
"6.4.0",
"6.3.0",

View File

@@ -35,6 +35,7 @@ type FileBackend interface {
FileModTime(path string) (time.Time, error)
ListDirectory(path string) ([]string, error)
ListDirectoryRecursively(path string) ([]string, error)
RemoveDirectory(path string) error
}

View File

@@ -188,19 +188,48 @@ func (b *LocalFileBackend) RemoveFile(path string) error {
return nil
}
func (b *LocalFileBackend) ListDirectory(path string) ([]string, error) {
var paths []string
fileInfos, err := ioutil.ReadDir(filepath.Join(b.directory, path))
// basePath: path to get to the file but won't be added to the end result
// path: basePath+path current directory we are looking at
// maxDepth: parameter to prevent infinite recursion, once this is reached we won't look any further
func appendRecursively(basePath, path string, maxDepth int) ([]string, error) {
results := []string{}
dirEntries, err := os.ReadDir(filepath.Join(basePath, path))
if err != nil {
if os.IsNotExist(err) {
return paths, nil
return results, nil
}
return nil, errors.Wrapf(err, "unable to list the directory %s", path)
return results, errors.Wrapf(err, "unable to list the directory %s", path)
}
for _, fileInfo := range fileInfos {
paths = append(paths, filepath.Join(path, fileInfo.Name()))
for _, dirEntry := range dirEntries {
entryName := dirEntry.Name()
entryPath := filepath.Join(path, entryName)
if entryName == "." || entryName == ".." || entryPath == path {
continue
}
if dirEntry.IsDir() {
if maxDepth <= 0 {
mlog.Warn("Max Depth reached", mlog.String("path", entryPath))
results = append(results, entryPath)
continue // we'll ignore it if max depth is reached.
}
nestedResults, err := appendRecursively(basePath, entryPath, maxDepth-1)
if err != nil {
return results, err
}
results = append(results, nestedResults...)
} else {
results = append(results, entryPath)
}
}
return paths, nil
return results, nil
}
func (b *LocalFileBackend) ListDirectory(path string) ([]string, error) {
return appendRecursively(b.directory, path, 0)
}
func (b *LocalFileBackend) ListDirectoryRecursively(path string) ([]string, error) {
return appendRecursively(b.directory, path, 10)
}
func (b *LocalFileBackend) RemoveDirectory(path string) error {

View File

@@ -396,7 +396,7 @@ func getPathsFromObjectInfos(in <-chan s3.ObjectInfo) <-chan s3.ObjectInfo {
return out
}
func (b *S3FileBackend) ListDirectory(path string) ([]string, error) {
func (b *S3FileBackend) listDirectory(path string, recursion bool) ([]string, error) {
path = filepath.Join(b.pathPrefix, path)
if !strings.HasSuffix(path, "/") && path != "" {
// s3Clnt returns only the path itself when "/" is not present
@@ -405,7 +405,8 @@ func (b *S3FileBackend) ListDirectory(path string) ([]string, error) {
}
opts := s3.ListObjectsOptions{
Prefix: path,
Prefix: path,
Recursive: recursion,
}
var paths []string
for object := range b.client.ListObjects(context.Background(), b.bucket, opts) {
@@ -424,6 +425,14 @@ func (b *S3FileBackend) ListDirectory(path string) ([]string, error) {
return paths, nil
}
func (b *S3FileBackend) ListDirectory(path string) ([]string, error) {
return b.listDirectory(path, false)
}
func (b *S3FileBackend) ListDirectoryRecursively(path string) ([]string, error) {
return b.listDirectory(path, true)
}
func (b *S3FileBackend) RemoveDirectory(path string) error {
opts := s3.ListObjectsOptions{
Prefix: filepath.Join(b.pathPrefix, path),

View File

@@ -14,7 +14,7 @@ var (
LvlInfo = logr.Info // ID = 4
LvlDebug = logr.Debug // ID = 5
LvlTrace = logr.Trace // ID = 6
StdAll = []Level{LvlPanic, LvlFatal, LvlError, LvlWarn, LvlInfo, LvlDebug, LvlTrace}
StdAll = []Level{LvlPanic, LvlFatal, LvlError, LvlWarn, LvlInfo, LvlDebug, LvlTrace, LvlStdLog}
// non-standard "critical" level
LvlCritical = Level{ID: 7, Name: "critical"}
// used by redirected standard logger

View File

@@ -214,14 +214,10 @@ The full API Reference is available here.
### Full Examples : File Object Operations
* [fputobject.go](https://github.com/minio/minio-go/blob/master/examples/s3/fputobject.go)
* [fgetobject.go](https://github.com/minio/minio-go/blob/master/examples/s3/fgetobject.go)
* [fputobject-context.go](https://github.com/minio/minio-go/blob/master/examples/s3/fputobject-context.go)
* [fgetobject-context.go](https://github.com/minio/minio-go/blob/master/examples/s3/fgetobject-context.go)
### Full Examples : Object Operations
* [putobject.go](https://github.com/minio/minio-go/blob/master/examples/s3/putobject.go)
* [getobject.go](https://github.com/minio/minio-go/blob/master/examples/s3/getobject.go)
* [putobject-context.go](https://github.com/minio/minio-go/blob/master/examples/s3/putobject-context.go)
* [getobject-context.go](https://github.com/minio/minio-go/blob/master/examples/s3/getobject-context.go)
* [statobject.go](https://github.com/minio/minio-go/blob/master/examples/s3/statobject.go)
* [copyobject.go](https://github.com/minio/minio-go/blob/master/examples/s3/copyobject.go)
* [removeobject.go](https://github.com/minio/minio-go/blob/master/examples/s3/removeobject.go)

View File

@@ -87,6 +87,11 @@ func (c *Client) removeBucketPolicy(ctx context.Context, bucketName string) erro
if err != nil {
return err
}
if resp.StatusCode != http.StatusNoContent {
return httpRespToErrorResponse(resp, bucketName, "")
}
return nil
}

View File

@@ -246,12 +246,42 @@ func (c *Client) resetBucketReplicationOnTarget(ctx context.Context, bucketName
if resp.StatusCode != http.StatusOK {
return rinfo, httpRespToErrorResponse(resp, bucketName, "")
}
respBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return rinfo, err
}
if err := json.Unmarshal(respBytes, &rinfo); err != nil {
if err = json.NewDecoder(resp.Body).Decode(&rinfo); err != nil {
return rinfo, err
}
return rinfo, nil
}
// GetBucketReplicationResyncStatus gets the status of replication resync
func (c *Client) GetBucketReplicationResyncStatus(ctx context.Context, bucketName, arn string) (rinfo replication.ResyncTargetsInfo, err error) {
// Input validation.
if err := s3utils.CheckValidBucketName(bucketName); err != nil {
return rinfo, err
}
// Get resources properly escaped and lined up before
// using them in http request.
urlValues := make(url.Values)
urlValues.Set("replication-reset-status", "")
if arn != "" {
urlValues.Set("arn", arn)
}
// Execute GET on bucket to get replication config.
resp, err := c.executeMethod(ctx, http.MethodGet, requestMetadata{
bucketName: bucketName,
queryValues: urlValues,
})
defer closeResponse(resp)
if err != nil {
return rinfo, err
}
if resp.StatusCode != http.StatusOK {
return rinfo, httpRespToErrorResponse(resp, bucketName, "")
}
if err = json.NewDecoder(resp.Body).Decode(&rinfo); err != nil {
return rinfo, err
}
return rinfo, nil

View File

@@ -175,7 +175,7 @@ func (c *Client) RestoreObject(ctx context.Context, bucketName, objectName, vers
if err != nil {
return err
}
if resp.StatusCode != http.StatusAccepted {
if resp.StatusCode != http.StatusAccepted && resp.StatusCode != http.StatusOK {
return httpRespToErrorResponse(resp, bucketName, "")
}
return nil

View File

@@ -111,7 +111,7 @@ type Options struct {
// Global constants.
const (
libraryName = "minio-go"
libraryVersion = "v7.0.21"
libraryVersion = "v7.0.23"
)
// User Agent should always following the below style.
@@ -875,10 +875,14 @@ func (c *Client) makeTargetURL(bucketName, objectName, bucketLocation string, is
if h, p, err := net.SplitHostPort(host); err == nil {
if scheme == "http" && p == "80" || scheme == "https" && p == "443" {
host = h
if ip := net.ParseIP(h); ip != nil && ip.To16() != nil {
host = "[" + h + "]"
}
}
}
urlStr := scheme + "://" + host + "/"
// Make URL only if bucketName is available, otherwise use the
// endpoint URL.
if bucketName != "" {

View File

@@ -8143,6 +8143,8 @@ func testDecryptedCopyObject() {
return
}
defer cleanupBucket(bucketName, c)
encryption := encrypt.DefaultPBKDF([]byte("correct horse battery staple"), []byte(bucketName+objectName))
_, err = c.PutObject(context.Background(), bucketName, objectName, bytes.NewReader(bytes.Repeat([]byte("a"), 1024*1024)), 1024*1024, minio.PutObjectOptions{
ServerSideEncryption: encryption,

View File

@@ -22,6 +22,7 @@ import (
"fmt"
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/rs/xid"
@@ -726,6 +727,21 @@ type ResyncTargetsInfo struct {
// ResyncTarget provides the replica resources and resetID to initiate resync replication.
type ResyncTarget struct {
Arn string `json:"arn"`
ResetID string `json:"resetid"`
Arn string `json:"arn"`
ResetID string `json:"resetid"`
StartTime time.Time `json:"startTime,omitempty"`
EndTime time.Time `json:"endTime,omitempty"`
// Status of resync operation
ResyncStatus string `json:"resyncStatus,omitempty"`
// Completed size in bytes
ReplicatedSize int64 `json:"completedReplicationSize,omitempty"`
// Failed size in bytes
FailedSize int64 `json:"failedReplicationSize,omitempty"`
// Total number of failed operations
FailedCount int64 `json:"failedReplicationCount,omitempty"`
// Total number of failed operations
ReplicatedCount int64 `json:"replicationCount,omitempty"`
// Last bucket/object replicated.
Bucket string `json:"bucket,omitempty"`
Object string `json:"object,omitempty"`
}

View File

@@ -517,11 +517,11 @@ var md5Pool = sync.Pool{New: func() interface{} { return md5.New() }}
var sha256Pool = sync.Pool{New: func() interface{} { return sha256.New() }}
func newMd5Hasher() md5simd.Hasher {
return hashWrapper{Hash: md5Pool.New().(hash.Hash), isMD5: true}
return hashWrapper{Hash: md5Pool.Get().(hash.Hash), isMD5: true}
}
func newSHA256Hasher() md5simd.Hasher {
return hashWrapper{Hash: sha256Pool.New().(hash.Hash), isSHA256: true}
return hashWrapper{Hash: sha256Pool.Get().(hash.Hash), isSHA256: true}
}
// hashWrapper implements the md5simd.Hasher interface.

1
vendor/github.com/rs/xid/README.md generated vendored
View File

@@ -69,6 +69,7 @@ References:
- Rust port by [Jérôme Renard](https://github.com/jeromer/): https://github.com/jeromer/libxid
- Ruby port by [Valar](https://github.com/valarpirai/): https://github.com/valarpirai/ruby_xid
- Java port by [0xShamil](https://github.com/0xShamil/): https://github.com/0xShamil/java-xid
- Dart port by [Peter Bwire](https://github.com/pitabwire): https://pub.dev/packages/xid
## Install

11
vendor/github.com/rs/xid/error.go generated vendored Normal file
View File

@@ -0,0 +1,11 @@
package xid
const (
// ErrInvalidID is returned when trying to unmarshal an invalid ID.
ErrInvalidID strErr = "xid: invalid ID"
)
// strErr allows declaring errors as constants.
type strErr string
func (err strErr) Error() string { return string(err) }

26
vendor/github.com/rs/xid/id.go generated vendored
View File

@@ -47,7 +47,6 @@ import (
"crypto/rand"
"database/sql/driver"
"encoding/binary"
"errors"
"fmt"
"hash/crc32"
"io/ioutil"
@@ -73,9 +72,6 @@ const (
)
var (
// ErrInvalidID is returned when trying to unmarshal an invalid ID
ErrInvalidID = errors.New("xid: invalid ID")
// objectIDCounter is atomically incremented when generating a new ObjectId
// using NewObjectId() function. It's used as a counter part of an id.
// This id is initialized with a random value.
@@ -242,7 +238,9 @@ func (id *ID) UnmarshalText(text []byte) error {
return ErrInvalidID
}
}
decode(id, text)
if !decode(id, text) {
return ErrInvalidID
}
return nil
}
@@ -253,11 +251,15 @@ func (id *ID) UnmarshalJSON(b []byte) error {
*id = nilID
return nil
}
// Check the slice length to prevent panic on passing it to UnmarshalText()
if len(b) < 2 {
return ErrInvalidID
}
return id.UnmarshalText(b[1 : len(b)-1])
}
// decode by unrolling the stdlib base32 algorithm + removing all safe checks
func decode(id *ID, src []byte) {
// decode by unrolling the stdlib base32 algorithm + customized safe check.
func decode(id *ID, src []byte) bool {
_ = src[19]
_ = id[11]
@@ -273,6 +275,16 @@ func decode(id *ID, src []byte) {
id[2] = dec[src[3]]<<4 | dec[src[4]]>>1
id[1] = dec[src[1]]<<6 | dec[src[2]]<<1 | dec[src[3]]>>4
id[0] = dec[src[0]]<<3 | dec[src[1]]>>2
// Validate that there are no discarer bits (padding) in src that would
// cause the string-encoded id not to equal src.
var check [4]byte
check[3] = encoding[(id[11]<<4)&0x1F]
check[2] = encoding[(id[11]>>1)&0x1F]
check[1] = encoding[(id[11]>>6)&0x1F|(id[10]<<2)&0x1F]
check[0] = encoding[id[10]>>3]
return bytes.Equal([]byte(src[16:20]), check[:])
}
// Time returns the timestamp part of the id.

View File

@@ -92,6 +92,7 @@ func (r *Ring) Dequeue() interface{} {
return nil
}
v := r.get(r.tail)
r.set(r.tail, nil)
if r.tail == r.head {
r.head = -1
r.tail = 0

View File

@@ -488,6 +488,7 @@ func (cli *Client) handlerQueueLoop(ctx context.Context) {
}
}
}
func (cli *Client) sendNode(node waBinary.Node) error {
cli.socketLock.RLock()
sock := cli.socket

View File

@@ -74,7 +74,7 @@ func (vc WAVersionContainer) ProtoAppVersion() *waProto.AppVersion {
}
// waVersion is the WhatsApp web client version
var waVersion = WAVersionContainer{2, 2214, 9}
var waVersion = WAVersionContainer{2, 2214, 12}
// waVersionHash is the md5 hash of a dot-separated waVersion
var waVersionHash [16]byte

View File

@@ -1,4 +1,4 @@
// Copyright (c) 2021 Tulir Asokan
// Copyright (c) 2022 Tulir Asokan
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
@@ -14,6 +14,8 @@ import (
"go.mau.fi/libsignal/serialize"
"go.mau.fi/libsignal/state/record"
"go.mau.fi/libsignal/state/store"
"go.mau.fi/whatsmeow/util/keys"
)
var SignalProtobufSerializer = serialize.NewProtoBufSerializer()
@@ -32,26 +34,33 @@ func (device *Device) GetLocalRegistrationId() uint32 {
}
func (device *Device) SaveIdentity(address *protocol.SignalAddress, identityKey *identity.Key) {
err := device.Identities.PutIdentity(address.String(), identityKey.PublicKey().PublicKey())
if err != nil {
device.Log.Errorf("Failed to save identity of %s: %v", address.String(), err)
for i := 0; ; i++ {
err := device.Identities.PutIdentity(address.String(), identityKey.PublicKey().PublicKey())
if err == nil || !device.handleDatabaseError(i, err, "save identity of %s", address.String()) {
break
}
}
}
func (device *Device) IsTrustedIdentity(address *protocol.SignalAddress, identityKey *identity.Key) bool {
isTrusted, err := device.Identities.IsTrustedIdentity(address.String(), identityKey.PublicKey().PublicKey())
if err != nil {
device.Log.Errorf("Failed to check if %s's identity is trusted: %v", address.String(), err)
for i := 0; ; i++ {
isTrusted, err := device.Identities.IsTrustedIdentity(address.String(), identityKey.PublicKey().PublicKey())
if err == nil || !device.handleDatabaseError(i, err, "check if %s's identity is trusted", address.String()) {
return isTrusted
}
}
return isTrusted
}
func (device *Device) LoadPreKey(id uint32) *record.PreKey {
preKey, err := device.PreKeys.GetPreKey(id)
if err != nil {
device.Log.Errorf("Failed to load prekey %d: %v", id, err)
return nil
} else if preKey == nil {
var preKey *keys.PreKey
for i := 0; ; i++ {
var err error
preKey, err = device.PreKeys.GetPreKey(id)
if err == nil || !device.handleDatabaseError(i, err, "load prekey %d", id) {
break
}
}
if preKey == nil {
return nil
}
return record.NewPreKey(preKey.KeyID, ecc.NewECKeyPair(
@@ -61,9 +70,11 @@ func (device *Device) LoadPreKey(id uint32) *record.PreKey {
}
func (device *Device) RemovePreKey(id uint32) {
err := device.PreKeys.RemovePreKey(id)
if err != nil {
device.Log.Errorf("Failed to remove prekey %d: %v", id, err)
for i := 0; ; i++ {
err := device.PreKeys.RemovePreKey(id)
if err == nil || !device.handleDatabaseError(i, err, "remove prekey %d", id) {
break
}
}
}
@@ -76,11 +87,15 @@ func (device *Device) ContainsPreKey(preKeyID uint32) bool {
}
func (device *Device) LoadSession(address *protocol.SignalAddress) *record.Session {
rawSess, err := device.Sessions.GetSession(address.String())
if err != nil {
device.Log.Errorf("Failed to load session with %s: %v", address.String(), err)
return record.NewSession(SignalProtobufSerializer.Session, SignalProtobufSerializer.State)
} else if rawSess == nil {
var rawSess []byte
for i := 0; ; i++ {
var err error
rawSess, err = device.Sessions.GetSession(address.String())
if err == nil || !device.handleDatabaseError(i, err, "load session with %s", address.String()) {
break
}
}
if rawSess == nil {
return record.NewSession(SignalProtobufSerializer.Session, SignalProtobufSerializer.State)
}
sess, err := record.NewSessionFromBytes(rawSess, SignalProtobufSerializer.Session, SignalProtobufSerializer.State)
@@ -96,18 +111,21 @@ func (device *Device) GetSubDeviceSessions(name string) []uint32 {
}
func (device *Device) StoreSession(address *protocol.SignalAddress, record *record.Session) {
err := device.Sessions.PutSession(address.String(), record.Serialize())
if err != nil {
device.Log.Errorf("Failed to store session with %s: %v", address.String(), err)
for i := 0; ; i++ {
err := device.Sessions.PutSession(address.String(), record.Serialize())
if err == nil || !device.handleDatabaseError(i, err, "store session with %s", address.String()) {
return
}
}
}
func (device *Device) ContainsSession(remoteAddress *protocol.SignalAddress) bool {
hasSession, err := device.Sessions.HasSession(remoteAddress.String())
if err != nil {
device.Log.Warnf("Failed to check if store has session for %s: %v", remoteAddress.String(), err)
for i := 0; ; i++ {
hasSession, err := device.Sessions.HasSession(remoteAddress.String())
if err == nil || !device.handleDatabaseError(i, err, "store has session for %s", remoteAddress.String()) {
return hasSession
}
}
return hasSession
}
func (device *Device) DeleteSession(remoteAddress *protocol.SignalAddress) {
@@ -145,18 +163,24 @@ func (device *Device) RemoveSignedPreKey(signedPreKeyID uint32) {
}
func (device *Device) StoreSenderKey(senderKeyName *protocol.SenderKeyName, keyRecord *groupRecord.SenderKey) {
err := device.SenderKeys.PutSenderKey(senderKeyName.GroupID(), senderKeyName.Sender().String(), keyRecord.Serialize())
if err != nil {
device.Log.Errorf("Failed to store sender key from %s for %s: %v", senderKeyName.Sender().String(), senderKeyName.GroupID(), err)
for i := 0; ; i++ {
err := device.SenderKeys.PutSenderKey(senderKeyName.GroupID(), senderKeyName.Sender().String(), keyRecord.Serialize())
if err == nil || !device.handleDatabaseError(i, err, "store sender key from %s", senderKeyName.Sender().String()) {
return
}
}
}
func (device *Device) LoadSenderKey(senderKeyName *protocol.SenderKeyName) *groupRecord.SenderKey {
rawKey, err := device.SenderKeys.GetSenderKey(senderKeyName.GroupID(), senderKeyName.Sender().String())
if err != nil {
device.Log.Errorf("Failed to load sender key from %s for %s: %v", senderKeyName.Sender().String(), senderKeyName.GroupID(), err)
return groupRecord.NewSenderKey(SignalProtobufSerializer.SenderKeyRecord, SignalProtobufSerializer.SenderKeyState)
} else if rawKey == nil {
var rawKey []byte
for i := 0; ; i++ {
var err error
rawKey, err = device.SenderKeys.GetSenderKey(senderKeyName.GroupID(), senderKeyName.Sender().String())
if err == nil || !device.handleDatabaseError(i, err, "load sender key from %s for %s", senderKeyName.Sender().String(), senderKeyName.GroupID()) {
break
}
}
if rawKey == nil {
return groupRecord.NewSenderKey(SignalProtobufSerializer.SenderKeyRecord, SignalProtobufSerializer.SenderKeyState)
}
key, err := groupRecord.NewSenderKeyFromBytes(rawKey, SignalProtobufSerializer.SenderKeyRecord, SignalProtobufSerializer.SenderKeyState)

View File

@@ -1,4 +1,4 @@
// Copyright (c) 2021 Tulir Asokan
// Copyright (c) 2022 Tulir Asokan
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
@@ -25,6 +25,8 @@ type Container struct {
db *sql.DB
dialect string
log waLog.Logger
DatabaseErrorHandler func(device *store.Device, action string, attemptIndex int, err error) (retry bool)
}
var _ store.DeviceContainer = (*Container)(nil)
@@ -89,6 +91,7 @@ type scannable interface {
func (c *Container) scanDevice(row scannable) (*store.Device, error) {
var device store.Device
device.DatabaseErrorHandler = c.DatabaseErrorHandler
device.Log = c.log
device.SignedPreKey = &keys.PreKey{}
var noisePriv, identityPriv, preKeyPriv, preKeySig []byte
@@ -192,6 +195,8 @@ func (c *Container) NewDevice() *store.Device {
Log: c.log,
Container: c,
DatabaseErrorHandler: c.DatabaseErrorHandler,
NoiseKey: keys.NewKeyPair(),
IdentityKey: keys.NewKeyPair(),
RegistrationID: mathRand.Uint32(),

View File

@@ -8,6 +8,7 @@
package store
import (
"fmt"
"time"
waProto "go.mau.fi/whatsmeow/binary/proto"
@@ -123,6 +124,16 @@ type Device struct {
Contacts ContactStore
ChatSettings ChatSettingsStore
Container DeviceContainer
DatabaseErrorHandler func(device *Device, action string, attemptIndex int, err error) (retry bool)
}
func (device *Device) handleDatabaseError(attemptIndex int, err error, action string, args ...interface{}) bool {
if device.DatabaseErrorHandler != nil {
return device.DatabaseErrorHandler(device, fmt.Sprintf(action, args...), attemptIndex, err)
}
device.Log.Errorf("Failed to %s: %v", fmt.Sprintf(action, args...), err)
return false
}
func (device *Device) Save() error {

View File

@@ -117,10 +117,10 @@ func (tb *TemporaryBan) String() string {
type ConnectFailureReason int
const (
ConnectFailureLoggedOut ConnectFailureReason = 401
ConnectFailureTempBanned ConnectFailureReason = 402
ConnectFailureBanned ConnectFailureReason = 403
ConnectFailureUnknownLogout ConnectFailureReason = 406
ConnectFailureLoggedOut ConnectFailureReason = 401
ConnectFailureTempBanned ConnectFailureReason = 402
ConnectFailureMainDeviceGone ConnectFailureReason = 403
ConnectFailureUnknownLogout ConnectFailureReason = 406
ConnectFailureClientOutdated ConnectFailureReason = 405
ConnectFailureBadUserAgent ConnectFailureReason = 409
@@ -131,7 +131,7 @@ const (
var connectFailureReasonMessage = map[ConnectFailureReason]string{
ConnectFailureLoggedOut: "logged out from another device",
ConnectFailureTempBanned: "account temporarily banned",
ConnectFailureBanned: "account banned from WhatsApp",
ConnectFailureMainDeviceGone: "primary device was logged out", // seems to happen for both bans and switching phones
ConnectFailureUnknownLogout: "logged out for unknown reason",
ConnectFailureClientOutdated: "client is out of date",
ConnectFailureBadUserAgent: "client user agent was rejected",
@@ -139,7 +139,7 @@ var connectFailureReasonMessage = map[ConnectFailureReason]string{
// IsLoggedOut returns true if the client should delete session data due to this connect failure.
func (cfr ConnectFailureReason) IsLoggedOut() bool {
return cfr == ConnectFailureLoggedOut || cfr == ConnectFailureBanned || cfr == ConnectFailureUnknownLogout
return cfr == ConnectFailureLoggedOut || cfr == ConnectFailureMainDeviceGone || cfr == ConnectFailureUnknownLogout
}
// String returns the reason code and a short human-readable description of the error.

View File

@@ -47,7 +47,7 @@ type UploadResponse struct {
// // you can also optionally add other fields like ContextInfo and JpegThumbnail here
//
// Url: &resp.URL,
// DirectPath: &uploaded.DirectPath,
// DirectPath: &resp.DirectPath,
// MediaKey: resp.MediaKey,
// FileEncSha256: resp.FileEncSHA256,
// FileSha256: resp.FileSha256,

26
vendor/modules.txt vendored
View File

@@ -77,8 +77,8 @@ github.com/dyatlov/go-opengraph/opengraph
# github.com/francoispqt/gojay v1.2.13
## explicit; go 1.12
github.com/francoispqt/gojay
# github.com/fsnotify/fsnotify v1.5.3
## explicit; go 1.13
# github.com/fsnotify/fsnotify v1.5.4
## explicit; go 1.16
github.com/fsnotify/fsnotify
# github.com/go-asn1-ber/asn1-ber v1.5.3
## explicit; go 1.13
@@ -93,7 +93,7 @@ github.com/golang-jwt/jwt
## explicit; go 1.9
github.com/golang/protobuf/proto
github.com/golang/protobuf/protoc-gen-go/descriptor
# github.com/gomarkdown/markdown v0.0.0-20220310201231-552c6011c0b8
# github.com/gomarkdown/markdown v0.0.0-20220419181919-412bcf14cd2e
## explicit; go 1.12
github.com/gomarkdown/markdown
github.com/gomarkdown/markdown/ast
@@ -207,8 +207,8 @@ github.com/labstack/gommon/bytes
github.com/labstack/gommon/color
github.com/labstack/gommon/log
github.com/labstack/gommon/random
# github.com/lrstanley/girc v0.0.0-20220410132120-49de39aea653
## explicit; go 1.12
# github.com/lrstanley/girc v0.0.0-20220429030656-4462c51ec0bc
## explicit; go 1.18
github.com/lrstanley/girc
# github.com/magiconair/properties v1.8.6
## explicit; go 1.13
@@ -230,7 +230,7 @@ github.com/matterbridge/gozulipbot
# github.com/matterbridge/logrus-prefixed-formatter v0.5.3-0.20200523233437-d971309a77ba
## explicit
github.com/matterbridge/logrus-prefixed-formatter
# github.com/matterbridge/matterclient v0.0.0-20211107234719-faca3cd42315
# github.com/matterbridge/matterclient v0.0.0-20220430213656-07aca2731bc9
## explicit; go 1.16
github.com/matterbridge/matterclient
# github.com/mattermost/go-i18n v1.11.1-0.20211013152124-5c415071e404
@@ -262,7 +262,7 @@ github.com/mattermost/mattermost-server/v5/shared/i18n
github.com/mattermost/mattermost-server/v5/shared/markdown
github.com/mattermost/mattermost-server/v5/shared/mlog
github.com/mattermost/mattermost-server/v5/utils/jsonutils
# github.com/mattermost/mattermost-server/v6 v6.5.0
# github.com/mattermost/mattermost-server/v6 v6.6.1
## explicit; go 1.16
github.com/mattermost/mattermost-server/v6/model
github.com/mattermost/mattermost-server/v6/services/timezones
@@ -292,7 +292,7 @@ github.com/mgutz/ansi
# github.com/minio/md5-simd v1.1.2
## explicit; go 1.14
github.com/minio/md5-simd
# github.com/minio/minio-go/v7 v7.0.21
# github.com/minio/minio-go/v7 v7.0.23
## explicit; go 1.17
github.com/minio/minio-go/v7
github.com/minio/minio-go/v7/pkg/credentials
@@ -329,8 +329,8 @@ github.com/mreiferson/go-httpclient
# github.com/mrexodia/wray v0.0.0-20160318003008-78a2c1f284ff
## explicit
github.com/mrexodia/wray
# github.com/nelsonken/gomf v0.0.0-20180504123937-a9dd2f9deae9
## explicit
# github.com/nelsonken/gomf v0.0.0-20190423072027-c65cc0469e94
## explicit; go 1.12
github.com/nelsonken/gomf
# github.com/opentracing/opentracing-go v1.2.0
## explicit; go 1.14
@@ -374,7 +374,7 @@ github.com/rickb777/plural
# github.com/rivo/uniseg v0.2.0
## explicit; go 1.12
github.com/rivo/uniseg
# github.com/rs/xid v1.3.0
# github.com/rs/xid v1.4.0
## explicit; go 1.12
github.com/rs/xid
# github.com/russross/blackfriday v1.6.0
@@ -482,7 +482,7 @@ github.com/writeas/go-strip-markdown
github.com/yaegashi/msgraph.go/beta
github.com/yaegashi/msgraph.go/jsonx
github.com/yaegashi/msgraph.go/msauth
# github.com/zfjagann/golang-ring v0.0.0-20210116075443-7c86fdb43134
# github.com/zfjagann/golang-ring v0.0.0-20220330170733-19bcea1b6289
## explicit
github.com/zfjagann/golang-ring
# go.mau.fi/libsignal v0.0.0-20220425070825-c40c839ee6a0
@@ -513,7 +513,7 @@ go.mau.fi/libsignal/util/errorhelper
go.mau.fi/libsignal/util/keyhelper
go.mau.fi/libsignal/util/medium
go.mau.fi/libsignal/util/optional
# go.mau.fi/whatsmeow v0.0.0-20220425142103-46b439456742
# go.mau.fi/whatsmeow v0.0.0-20220429163952-136d7f5726e9
## explicit; go 1.17
go.mau.fi/whatsmeow
go.mau.fi/whatsmeow/appstate