Skip to content

Commit

Permalink
Make plausible url configurable
Browse files Browse the repository at this point in the history
Fixes #22
  • Loading branch information
kurtmc committed Feb 1, 2022
1 parent 31eba8f commit 5f5b33c
Show file tree
Hide file tree
Showing 14 changed files with 263 additions and 127 deletions.
5 changes: 2 additions & 3 deletions .github/workflows/acctest.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,8 @@ jobs:
fail-fast: false
matrix:
terraform:
- '0.12.29'
- '0.13.5'
- '0.14.6'
- '0.13.7'
- '1.1.4'
steps:

- name: Set up Go
Expand Down
7 changes: 5 additions & 2 deletions docs/index.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "plausible Provider"
subcategory: ""
description: |-
Expand All @@ -11,9 +12,11 @@ description: |-



<!-- schema generated by tfplugindocs -->
## Schema

### Optional

- **password** (String, Optional) Plausible password. Can be specified with the `PLAUSIBLE_PASSWORD` environment variable.
- **username** (String, Optional) Plausible username. Can be specified with the `PLAUSIBLE_USERNAME` environment variable.
- **password** (String) Plausible password. Can be specified with the `PLAUSIBLE_PASSWORD` environment variable.
- **url** (String) Plausible URL. Can be specified with the `PLAUSIBLE_URL` environment variable.
- **username** (String) Plausible username. Can be specified with the `PLAUSIBLE_USERNAME` environment variable.
14 changes: 8 additions & 6 deletions docs/resources/goal.md
Original file line number Diff line number Diff line change
@@ -1,29 +1,31 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "plausible_goal Resource - terraform-provider-plausible"
subcategory: ""
description: |-
---

# Resource `plausible_goal`
# plausible_goal (Resource)





<!-- schema generated by tfplugindocs -->
## Schema

### Required

- **site_id** (String, Required) The domain of the site to create the goal for.
- **site_id** (String) The domain of the site to create the goal for.

### Optional

- **event_name** (String, Optional) Custom event E.g. `Signup`
- **page_path** (String, Optional) Page path event. E.g. `/success`
- **event_name** (String) Custom event E.g. `Signup`
- **page_path** (String) Page path event. E.g. `/success`

### Read-only
### Read-Only

- **id** (String, Read-only) The goal ID
- **id** (String) The goal ID


15 changes: 9 additions & 6 deletions docs/resources/shared_link.md
Original file line number Diff line number Diff line change
@@ -1,29 +1,32 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "plausible_shared_link Resource - terraform-provider-plausible"
subcategory: ""
description: |-
---

# Resource `plausible_shared_link`
# plausible_shared_link (Resource)





<!-- schema generated by tfplugindocs -->
## Schema

### Required

- **site_id** (String, Required) The domain of the site to create the shared link for.
- **name** (String) The name of the shared link to create.
- **site_id** (String) The domain of the site to create the shared link for.

### Optional

- **password** (String, Optional) Add a password or leave it blank so anyone with the link can see the stats.
- **password** (String) Add a password or leave it blank so anyone with the link can see the stats.

### Read-only
### Read-Only

- **id** (String, Read-only) The shared link ID
- **link** (String, Read-only) Shared link
- **id** (String) The shared link ID
- **link** (String) Shared link


14 changes: 8 additions & 6 deletions docs/resources/site.md
Original file line number Diff line number Diff line change
@@ -1,26 +1,28 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "plausible_site Resource - terraform-provider-plausible"
subcategory: ""
description: |-
---

# Resource `plausible_site`
# plausible_site (Resource)





<!-- schema generated by tfplugindocs -->
## Schema

### Required

- **domain** (String, Required)
- **timezone** (String, Required)
- **domain** (String)
- **timezone** (String)

### Read-only
### Read-Only

- **id** (String, Read-only) The site ID
- **javascript_snippet** (String, Read-only) Include this snippet in the <head> of your website.
- **id** (String) The site ID
- **javascript_snippet** (String) Include this snippet in the <head> of your website.


7 changes: 3 additions & 4 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ module github.com/mcalpinefree/terraform-provider-plausible
go 1.12

require (
github.com/PuerkitoBio/goquery v1.6.0
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
github.com/hashicorp/terraform-plugin-sdk/v2 v2.2.0
github.com/zclconf/go-cty v1.4.1 // indirect
github.com/PuerkitoBio/goquery v1.8.0
github.com/hashicorp/go-retryablehttp v0.7.0
github.com/hashicorp/terraform-plugin-sdk/v2 v2.10.1
)
207 changes: 138 additions & 69 deletions go.sum

Large diffs are not rendered by default.

9 changes: 8 additions & 1 deletion internal/provider/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ func New(version string) func() *schema.Provider {
return func() *schema.Provider {
p := &schema.Provider{
Schema: map[string]*schema.Schema{
"url": {
Description: "Plausible URL. Can be specified with the `PLAUSIBLE_URL` environment variable.",
Type: schema.TypeString,
Required: true,
DefaultFunc: schema.EnvDefaultFunc("PLAUSIBLE_URL", "https://plausible.io"),
},
"username": {
Description: "Plausible username. Can be specified with the `PLAUSIBLE_USERNAME` environment variable.",
Type: schema.TypeString,
Expand Down Expand Up @@ -53,9 +59,10 @@ func configure(version string, p *schema.Provider) func(context.Context, *schema
// Setup a User-Agent for your API client (replace the provider name for yours):
// userAgent := p.UserAgent("terraform-provider-plausible", version)
// TODO: myClient.UserAgent = userAgent
url := d.Get("url").(string)
username := d.Get("username").(string)
password := d.Get("password").(string)
c := plausibleclient.NewClient(username, password)
c := plausibleclient.NewClient(url, username, password)
return &apiClient{plausibleClient: c}, nil
}
}
9 changes: 8 additions & 1 deletion internal/provider/resource_shared_link.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ func resourceSharedLink() *schema.Resource {
Required: true,
ForceNew: true,
},
"name": {
Description: "The name of the shared link to create.",
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"password": {
Description: "Add a password or leave it blank so anyone with the link can see the stats.",
Type: schema.TypeString,
Expand All @@ -41,8 +47,9 @@ func resourceSharedLink() *schema.Resource {
func resourceSharedLinkCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*apiClient)
domain := d.Get("site_id").(string)
name := d.Get("name").(string)
password := d.Get("password").(string)
sharedLink, err := client.plausibleClient.CreateSharedLink(domain, password)
sharedLink, err := client.plausibleClient.CreateSharedLink(domain, name, password)
if err != nil {
return err
}
Expand Down
1 change: 1 addition & 0 deletions internal/provider/resource_shared_link_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ resource "plausible_site" "testacc" {
resource "plausible_shared_link" "testacc" {
site_id = plausible_site.testacc.id
name = "abc"
}
`, domain)
}
73 changes: 55 additions & 18 deletions plausibleclient/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,23 @@ package plausibleclient

import (
"fmt"
"math"
"net/http"
"net/http/cookiejar"
"net/url"
"time"

"github.com/PuerkitoBio/goquery"
)

type Client struct {
httpClient *http.Client
username string
password string
loggedIn bool
mutexkv *MutexKV
baseURL string
httpClient *http.Client
username string
password string
loggedIn bool
mutexkv *MutexKV
baseURL string
maxAttempts int
}

func (c *Client) login() error {
Expand All @@ -37,7 +40,7 @@ func (c *Client) login() error {
values.Add("_csrf_token", csrfToken)
values.Add("email", c.username)
values.Add("password", c.password)
resp, err := c.httpClient.PostForm("https://plausible.io/login", values)
resp, err := c.postForm(c.baseURL+"/login", values)
if err != nil {
return err
}
Expand All @@ -50,11 +53,12 @@ func (c *Client) login() error {
return nil
}

func NewClient(username, password string) *Client {
func NewClient(url, username, password string) *Client {
c := Client{}
c.username = username
c.password = password
c.baseURL = "https://plausible.io"
c.baseURL = url
c.maxAttempts = 10

jar, err := cookiejar.New(nil)
if err != nil {
Expand All @@ -76,16 +80,49 @@ func (c *Client) getDocument(path string) (*goquery.Document, error) {
return nil, err
}

resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
attempts := 1
for {
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()

if resp.StatusCode == http.StatusTooManyRequests {
if attempts > c.maxAttempts {
return nil, fmt.Errorf("request failed after %d attempts with status: %s", c.maxAttempts, resp.Status)
}
time.Sleep(time.Duration(math.Pow(1.5, float64(attempts))) * time.Second)
attempts++
continue
}

doc, err := goquery.NewDocumentFromReader(resp.Body)
if err != nil {
return nil, err
}

return doc, nil
}
defer resp.Body.Close()
}

doc, err := goquery.NewDocumentFromReader(resp.Body)
if err != nil {
return nil, err
}
func (c *Client) postForm(url string, values url.Values) (*http.Response, error) {
attempts := 1
for {
resp, err := c.httpClient.PostForm(url, values)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusTooManyRequests {
if attempts > c.maxAttempts {
return nil, fmt.Errorf("request failed after %d attempts with status: %s", c.maxAttempts, resp.Status)
}
time.Sleep(time.Duration(math.Pow(1.5, float64(attempts))) * time.Second)
attempts++
continue
}
return resp, err

return doc, nil
}
}
6 changes: 3 additions & 3 deletions plausibleclient/goal.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ func (c *Client) CreateGoal(domain string, goalType GoalType, goal string) (*Goa
return nil, err
}

_, err = c.httpClient.PostForm("https://plausible.io/"+domain+"/goals", values)
_, err = c.postForm(c.baseURL+"/"+domain+"/goals", values)
if err != nil {
return nil, err
}
Expand All @@ -85,7 +85,7 @@ func (c *Client) CreateGoal(domain string, goalType GoalType, goal string) (*Goa
}

if len(before.Goals) != (len(after.Goals) - 1) {
return nil, fmt.Errorf("expected there to be one more goal after requesting to create a new one, but the count went from %d to %d", len(before.SharedLinks), len(after.SharedLinks))
return nil, fmt.Errorf("expected there to be one more goal after requesting to create a new one, but the count went from %d to %d", len(before.Goals), len(after.Goals))
}

AFTER:
Expand Down Expand Up @@ -168,6 +168,6 @@ func (c *Client) DeleteGoal(domain string, id int) error {
values := url.Values{}
values.Add("_csrf_token", csrfToken)
values.Add("_method", "delete")
_, err = c.httpClient.PostForm(fmt.Sprintf("https://plausible.io/%s/goals/%d", domain, id), values)
_, err = c.postForm(fmt.Sprintf(c.baseURL+"/%s/goals/%d", domain, id), values)
return err
}
7 changes: 4 additions & 3 deletions plausibleclient/shared_link.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ type SharedLink struct {
Link string
}

func (c *Client) CreateSharedLink(domain, password string) (*SharedLink, error) {
func (c *Client) CreateSharedLink(domain, name, password string) (*SharedLink, error) {
if !c.loggedIn {
err := c.login()
if err != nil {
Expand Down Expand Up @@ -53,8 +53,9 @@ func (c *Client) CreateSharedLink(domain, password string) (*SharedLink, error)

values := url.Values{}
values.Add("_csrf_token", csrfToken)
values.Add("shared_link[name]", name)
values.Add("shared_link[password]", password)
_, err = c.httpClient.PostForm("https://plausible.io/sites/"+domain+"/shared-links", values)
_, err = c.postForm(c.baseURL+"/sites/"+domain+"/shared-links", values)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -122,6 +123,6 @@ func (c *Client) DeleteSharedLink(domain, id string) error {
values := url.Values{}
values.Add("_csrf_token", csrfToken)
values.Add("_method", "delete")
_, err = c.httpClient.PostForm("https://plausible.io/sites/"+domain+"/shared-links/"+id, values)
_, err = c.postForm(c.baseURL+"/sites/"+domain+"/shared-links/"+id, values)
return err
}
Loading

0 comments on commit 5f5b33c

Please sign in to comment.