Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2fc2adadd1 | ||
|
|
b63055d435 |
@@ -6,6 +6,22 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.3.1] - 2026-04-24
|
||||
|
||||
### Added
|
||||
|
||||
- `AuthenticateContext(ctx)` — context-aware auth that honours cancellation and
|
||||
deadlines. Preferred entry point for long-running syncs (cron, watchers).
|
||||
- `InvalidateToken()` — clears the cached token to force re-auth on the next
|
||||
request. Use this to recover from a mid-sync 401 when the server has revoked
|
||||
the session while the local `Expires` timestamp still looks fresh.
|
||||
|
||||
### Notes
|
||||
|
||||
- Plain `Authenticate()` is unchanged and remains a convenience wrapper around
|
||||
`AuthenticateContext(context.Background())`.
|
||||
- No breaking changes; a patch release.
|
||||
|
||||
## [0.3.0] - 2026-04-24
|
||||
|
||||
### Added
|
||||
|
||||
@@ -566,6 +566,10 @@ the command reference.
|
||||
| Example | Description |
|
||||
|---|---|
|
||||
| [basic](examples/basic/) | List projects and users |
|
||||
| [calendar](examples/calendar/) | List calendars and events, create a new event |
|
||||
| [crm](examples/crm/) | List contacts and opportunities, add company/deal/history note |
|
||||
| [subtasks](examples/subtasks/) | Create a parent task and attach subtasks |
|
||||
| [applications](examples/applications/) | Job application folder tree → OnlyOffice CRM (library-level usage of the internal applications package) |
|
||||
| [`cmd/oo-cli`](cmd/oo-cli/) | Full-featured CLI using all modules |
|
||||
|
||||
## Related Libraries
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
// Package main shows how to drive the internal applications package — the same
|
||||
// logic that powers `oo-cli applications-sync` — directly from Go code.
|
||||
//
|
||||
// export ONLYOFFICE_URL="https://your-instance.onlyoffice.com"
|
||||
// export ONLYOFFICE_USER="admin@example.com"
|
||||
// export ONLYOFFICE_PASS="your-password"
|
||||
// go run ./examples/applications /path/to/cv/applications
|
||||
//
|
||||
// Without --apply equivalent, it prints a summary but performs no writes.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
onlyoffice "github.com/eslider/go-onlyoffice"
|
||||
"github.com/eslider/go-onlyoffice/internal/applications"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if len(os.Args) < 2 {
|
||||
fmt.Fprintln(os.Stderr, "usage: applications <applications-root>")
|
||||
os.Exit(2)
|
||||
}
|
||||
root := os.Args[1]
|
||||
|
||||
creds := onlyoffice.GetEnvironmentCredentials()
|
||||
if creds.Url == "" {
|
||||
fmt.Fprintln(os.Stderr, "ONLYOFFICE_URL is not set")
|
||||
os.Exit(1)
|
||||
}
|
||||
client := onlyoffice.NewClient(creds)
|
||||
|
||||
paths, err := applications.Discover(root)
|
||||
if err != nil {
|
||||
log.Fatalf("discover: %v", err)
|
||||
}
|
||||
fmt.Printf("discovered %d application READMEs under %s\n", len(paths), root)
|
||||
|
||||
var apps []applications.Data
|
||||
for _, p := range paths {
|
||||
d, err := applications.ParseReadme(p)
|
||||
if err != nil {
|
||||
log.Printf("parse %s: %v", p, err)
|
||||
continue
|
||||
}
|
||||
apps = append(apps, d)
|
||||
}
|
||||
|
||||
stats := applications.Sync(context.Background(), client, apps, true /*dryRun*/, true /*verbose*/)
|
||||
fmt.Printf("\ndry-run stats: %+v\n", stats)
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
// Package main shows how to list calendars and events, and create a new event
|
||||
// via the OnlyOffice Calendar API.
|
||||
//
|
||||
// export ONLYOFFICE_URL="https://your-instance.onlyoffice.com"
|
||||
// export ONLYOFFICE_USER="admin@example.com"
|
||||
// export ONLYOFFICE_PASS="your-password"
|
||||
// # optional: default calendar for AddEvent
|
||||
// export ONLYOFFICE_CALENDAR_ID="42"
|
||||
// go run ./examples/calendar
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
onlyoffice "github.com/eslider/go-onlyoffice"
|
||||
)
|
||||
|
||||
func main() {
|
||||
creds := onlyoffice.GetEnvironmentCredentials()
|
||||
if creds.Url == "" {
|
||||
fmt.Fprintln(os.Stderr, "ONLYOFFICE_URL is not set")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
client := onlyoffice.NewClient(creds)
|
||||
client.SetDefaults(onlyoffice.GetEnvironmentDefaults())
|
||||
|
||||
ctx := context.Background()
|
||||
start := time.Now().Format("2006-01-02")
|
||||
end := time.Now().AddDate(0, 1, 0).Format("2006-01-02")
|
||||
|
||||
calendars, err := client.ListCalendars(ctx, start, end)
|
||||
if err != nil {
|
||||
log.Fatalf("list calendars: %v", err)
|
||||
}
|
||||
fmt.Printf("Calendars (%d):\n", len(calendars))
|
||||
for _, cal := range calendars {
|
||||
fmt.Printf(" - id=%v title=%v\n", cal["objectId"], cal["title"])
|
||||
}
|
||||
|
||||
events, err := client.ListEvents(ctx, start, end)
|
||||
if err != nil {
|
||||
log.Fatalf("list events: %v", err)
|
||||
}
|
||||
fmt.Printf("\nEvents in [%s..%s]: %d\n", start, end, len(events))
|
||||
for _, e := range events {
|
||||
fmt.Printf(" - %v @ %v\n", e["title"], e["start"])
|
||||
}
|
||||
|
||||
// Create demo event — uncomment to exercise.
|
||||
// evStart := time.Now().Add(time.Hour).Format(time.RFC3339)
|
||||
// evEnd := time.Now().Add(2 * time.Hour).Format(time.RFC3339)
|
||||
// created, err := client.AddEvent(ctx, "", "Library demo", evStart, evEnd, "via examples/calendar", false)
|
||||
// if err != nil {
|
||||
// log.Fatalf("add event: %v", err)
|
||||
// }
|
||||
// fmt.Printf("created event id=%v\n", created["objectId"])
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
// Package main lists CRM contacts and opportunities, and shows how to create
|
||||
// and remove a demo company + opportunity + history note in OnlyOffice CRM.
|
||||
//
|
||||
// export ONLYOFFICE_URL="https://your-instance.onlyoffice.com"
|
||||
// export ONLYOFFICE_USER="admin@example.com"
|
||||
// export ONLYOFFICE_PASS="your-password"
|
||||
// go run ./examples/crm
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
onlyoffice "github.com/eslider/go-onlyoffice"
|
||||
)
|
||||
|
||||
func main() {
|
||||
creds := onlyoffice.GetEnvironmentCredentials()
|
||||
if creds.Url == "" {
|
||||
fmt.Fprintln(os.Stderr, "ONLYOFFICE_URL is not set")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
client := onlyoffice.NewClient(creds)
|
||||
ctx := context.Background()
|
||||
|
||||
contacts, total, err := client.ListContacts(ctx, 10, 0, "")
|
||||
if err != nil {
|
||||
log.Fatalf("list contacts: %v", err)
|
||||
}
|
||||
fmt.Printf("CRM contacts: %d (total=%d)\n", len(contacts), total)
|
||||
for _, c := range contacts {
|
||||
fmt.Printf(" - id=%v name=%v\n", c["id"], c["displayName"])
|
||||
}
|
||||
|
||||
opps, oppTotal, err := client.ListOpportunities(ctx, 10, 0)
|
||||
if err != nil {
|
||||
log.Fatalf("list opportunities: %v", err)
|
||||
}
|
||||
fmt.Printf("\nOpportunities: %d (total=%d)\n", len(opps), oppTotal)
|
||||
for _, o := range opps {
|
||||
fmt.Printf(" - id=%v title=%v\n", o["id"], o["title"])
|
||||
}
|
||||
|
||||
// Full create/attach/delete cycle — uncomment to exercise.
|
||||
// company, err := client.CreateCompany(ctx, "Demo GmbH")
|
||||
// if err != nil { log.Fatalf("create company: %v", err) }
|
||||
// cid := fmt.Sprint(company["id"])
|
||||
// defer client.DeleteContact(ctx, cid)
|
||||
//
|
||||
// stages, err := client.ListDealStages(ctx)
|
||||
// if err != nil || len(stages) == 0 { log.Fatalf("no deal stages: %v", err) }
|
||||
// stageID := int(stages[0]["id"].(float64))
|
||||
//
|
||||
// opp, err := client.CreateOpportunity(ctx, "Demo opp", stageID, "", "EUR", "from examples/crm", 0)
|
||||
// if err != nil { log.Fatalf("create opportunity: %v", err) }
|
||||
// oid := fmt.Sprint(opp["id"])
|
||||
// _, _ = client.AddOpportunityMember(ctx, oid, cid)
|
||||
// _, _ = client.AddHistoryNote(ctx, "opportunity", int(opp["id"].(float64)), "Touched via library example", 0)
|
||||
// _, _ = client.DeleteOpportunity(ctx, oid)
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// Package main creates a parent task and attaches two subtasks using the
|
||||
// project-tasks API (POST /api/2.0/project/task/{id}.json).
|
||||
//
|
||||
// export ONLYOFFICE_URL="https://your-instance.onlyoffice.com"
|
||||
// export ONLYOFFICE_USER="admin@example.com"
|
||||
// export ONLYOFFICE_PASS="your-password"
|
||||
// export ONLYOFFICE_PROJECT_ID="123"
|
||||
// go run ./examples/subtasks
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
onlyoffice "github.com/eslider/go-onlyoffice"
|
||||
)
|
||||
|
||||
func main() {
|
||||
creds := onlyoffice.GetEnvironmentCredentials()
|
||||
defaults := onlyoffice.GetEnvironmentDefaults()
|
||||
if creds.Url == "" || defaults.ProjectID == "" {
|
||||
fmt.Fprintln(os.Stderr, "ONLYOFFICE_URL and ONLYOFFICE_PROJECT_ID must be set")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
client := onlyoffice.NewClient(creds)
|
||||
client.SetDefaults(defaults)
|
||||
ctx := context.Background()
|
||||
|
||||
parent, err := client.AddTask(ctx, defaults.ProjectID, "Example parent", "Created by examples/subtasks", 0, "")
|
||||
if err != nil {
|
||||
log.Fatalf("add parent task: %v", err)
|
||||
}
|
||||
parentID := fmt.Sprint(parent["id"])
|
||||
fmt.Printf("parent task id=%s\n", parentID)
|
||||
|
||||
for _, title := range []string{"first subtask", "second subtask"} {
|
||||
st, err := client.AddSubtask(ctx, parentID, title)
|
||||
if err != nil {
|
||||
log.Fatalf("add subtask %q: %v", title, err)
|
||||
}
|
||||
fmt.Printf(" + subtask id=%v title=%v\n", st["id"], st["title"])
|
||||
}
|
||||
|
||||
// Cleanup — uncomment once you verified the subtasks in the OnlyOffice UI.
|
||||
// if _, err := client.DeleteTask(ctx, parentID); err != nil {
|
||||
// log.Printf("cleanup: %v", err)
|
||||
// }
|
||||
}
|
||||
@@ -45,8 +45,63 @@ func (c *Client) authHeader() (string, error) {
|
||||
// Authenticate validates credentials and primes the token. Library users may
|
||||
// call this eagerly to surface auth errors at startup; otherwise the token is
|
||||
// fetched lazily on the first request.
|
||||
//
|
||||
// Prefer AuthenticateContext in long-running jobs — it honours cancellation.
|
||||
func (c *Client) Authenticate() error { return c.ensureToken() }
|
||||
|
||||
// AuthenticateContext is the context-aware variant of Authenticate. If the
|
||||
// cached token is still valid it returns immediately; otherwise it performs a
|
||||
// POST to /api/2.0/authentication.json that is cancellable via ctx.
|
||||
//
|
||||
// This is the recommended entry point for long-running syncs (cron, watchers)
|
||||
// because it guarantees that a stalled auth call will not block the caller
|
||||
// past its deadline.
|
||||
func (c *Client) AuthenticateContext(ctx context.Context) error {
|
||||
if c.token != nil && !time.Time(c.token.Expires).Before(time.Now()) {
|
||||
return nil
|
||||
}
|
||||
body, err := json.Marshal(c.credentials)
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal credentials: %w", err)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL()+"/api/2.0/authentication.json", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
resp, err := c.client.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("auth request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.StatusCode >= 400 {
|
||||
return fmt.Errorf("auth: %d %s", resp.StatusCode, truncate(string(raw), 400))
|
||||
}
|
||||
var env struct {
|
||||
Response *Token `json:"response"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &env); err != nil {
|
||||
return fmt.Errorf("auth decode: %w", err)
|
||||
}
|
||||
if env.Response == nil || env.Response.Value == "" {
|
||||
return fmt.Errorf("auth: empty token in response")
|
||||
}
|
||||
c.token = env.Response
|
||||
return nil
|
||||
}
|
||||
|
||||
// InvalidateToken clears the cached authentication token. The next request
|
||||
// (or call to Authenticate / AuthenticateContext) will re-authenticate.
|
||||
//
|
||||
// Use this to recover from a mid-sync 401 when the server has revoked or
|
||||
// rotated the session while the Expires timestamp still looks fresh locally.
|
||||
func (c *Client) InvalidateToken() { c.token = nil }
|
||||
|
||||
// baseURL returns the configured base URL without trailing slash.
|
||||
func (c *Client) baseURL() string {
|
||||
return strings.TrimRight(c.credentials.Url, "/")
|
||||
|
||||
@@ -192,3 +192,79 @@ func TestResponseFieldMissing(t *testing.T) {
|
||||
t.Fatal("expected error on missing field")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthenticateContextUsesCacheWhenFresh(t *testing.T) {
|
||||
var authHits int
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/api/2.0/authentication.json", func(w http.ResponseWriter, r *http.Request) {
|
||||
authHits++
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = io.WriteString(w, `{"response":{"token":"FRESH_TOKEN","expires":"2099-01-01T00:00:00.0000000-00:00"}}`)
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
defer srv.Close()
|
||||
c := NewClient(Credentials{Url: srv.URL, User: "u", Password: "p"})
|
||||
|
||||
if err := c.AuthenticateContext(context.Background()); err != nil {
|
||||
t.Fatalf("first AuthenticateContext: %v", err)
|
||||
}
|
||||
if authHits != 1 {
|
||||
t.Errorf("expected 1 auth hit after first call, got %d", authHits)
|
||||
}
|
||||
if c.token == nil || c.token.Value != "FRESH_TOKEN" {
|
||||
t.Errorf("token not cached: %+v", c.token)
|
||||
}
|
||||
if err := c.AuthenticateContext(context.Background()); err != nil {
|
||||
t.Fatalf("second AuthenticateContext: %v", err)
|
||||
}
|
||||
if authHits != 1 {
|
||||
t.Errorf("cache bypassed: expected 1 auth hit, got %d", authHits)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidateTokenForcesReauth(t *testing.T) {
|
||||
var authHits int
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/api/2.0/authentication.json", func(w http.ResponseWriter, r *http.Request) {
|
||||
authHits++
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = io.WriteString(w, `{"response":{"token":"T","expires":"2099-01-01T00:00:00.0000000-00:00"}}`)
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
defer srv.Close()
|
||||
c := NewClient(Credentials{Url: srv.URL, User: "u", Password: "p"})
|
||||
|
||||
if err := c.AuthenticateContext(context.Background()); err != nil {
|
||||
t.Fatalf("auth: %v", err)
|
||||
}
|
||||
c.InvalidateToken()
|
||||
if c.token != nil {
|
||||
t.Fatalf("token still cached after Invalidate: %+v", c.token)
|
||||
}
|
||||
if err := c.AuthenticateContext(context.Background()); err != nil {
|
||||
t.Fatalf("re-auth: %v", err)
|
||||
}
|
||||
if authHits != 2 {
|
||||
t.Errorf("expected 2 auth hits after invalidate, got %d", authHits)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthenticateContextRespectsCancellation(t *testing.T) {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/api/2.0/authentication.json", func(w http.ResponseWriter, r *http.Request) {
|
||||
select {
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
case <-time.After(2 * time.Second):
|
||||
_, _ = io.WriteString(w, `{"response":{"token":"T","expires":"2099-01-01T00:00:00.0000000-00:00"}}`)
|
||||
}
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
defer srv.Close()
|
||||
c := NewClient(Credentials{Url: srv.URL, User: "u", Password: "p"})
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
|
||||
defer cancel()
|
||||
if err := c.AuthenticateContext(ctx); err == nil {
|
||||
t.Fatal("expected error on context timeout")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user