update.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Copyright (c) 2024 Tulir Asokan
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this
  5. // file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6. package whatsmeow
  7. import (
  8. "context"
  9. "fmt"
  10. "io"
  11. "net/http"
  12. "regexp"
  13. "strconv"
  14. "git.bobomao.top/joey/testwh/socket"
  15. "git.bobomao.top/joey/testwh/store"
  16. )
  17. var clientVersionRegex = regexp.MustCompile(`"client_revision":(\d+),`)
  18. // GetLatestVersion returns the latest version number from web.whatsapp.com.
  19. //
  20. // After fetching, you can update the version to use using store.SetWAVersion, e.g.
  21. //
  22. // latestVer, err := GetLatestVersion(nil)
  23. // if err != nil {
  24. // return err
  25. // }
  26. // store.SetWAVersion(*latestVer)
  27. func GetLatestVersion(ctx context.Context, httpClient *http.Client) (*store.WAVersionContainer, error) {
  28. req, err := http.NewRequestWithContext(ctx, http.MethodGet, socket.Origin, nil)
  29. if err != nil {
  30. return nil, fmt.Errorf("failed to prepare request: %w", err)
  31. }
  32. req.Header.Set("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36")
  33. req.Header.Set("Sec-Fetch-Dest", "document")
  34. req.Header.Set("Sec-Fetch-Mode", "navigate")
  35. req.Header.Set("Sec-Fetch-Site", "none")
  36. req.Header.Set("Sec-Fetch-User", "?1")
  37. req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7")
  38. req.Header.Set("Accept-Language", "en-US,en;q=0.9")
  39. if httpClient == nil {
  40. httpClient = http.DefaultClient
  41. }
  42. resp, err := httpClient.Do(req)
  43. if err != nil {
  44. return nil, fmt.Errorf("failed to send request: %w", err)
  45. }
  46. data, err := io.ReadAll(resp.Body)
  47. _ = resp.Body.Close()
  48. if err != nil {
  49. return nil, fmt.Errorf("failed to read response: %w", err)
  50. } else if resp.StatusCode != 200 {
  51. return nil, fmt.Errorf("unexpected response with status %d: %s", resp.StatusCode, data)
  52. } else if match := clientVersionRegex.FindSubmatch(data); len(match) == 0 {
  53. return nil, fmt.Errorf("version number not found")
  54. } else if parsedVer, err := strconv.ParseInt(string(match[1]), 10, 64); err != nil {
  55. return nil, fmt.Errorf("failed to parse version number: %w", err)
  56. } else {
  57. return &store.WAVersionContainer{2, 3000, uint32(parsedVer)}, nil
  58. }
  59. }