plexwebhooks

package module
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 15, 2021 License: MIT Imports: 10 Imported by: 3

README

Plex Webhooks

Go Reference Go Report Card

Golang binding for Plex Webhooks.

This library provides:

  • Golang binding for webhook (JSON) payloads
  • Auto convert values to Golang types when possible (time, duration, IP, URL, etc...)
  • Multipart reader extractor which returns the hook payload and the thumbnail if present

Example

package main

import (
    "fmt"
    "net/http"
    "time"

    "github.com/hekmon/plexwebhooks"
)

func main() {
    http.HandleFunc("/", processHandler)
    http.ListenAndServe(":7095", http.DefaultServeMux)
}

func processHandler(w http.ResponseWriter, r *http.Request) {
    defer r.Body.Close()
    // Create the multi part reader
    multiPartReader, err := r.MultipartReader()
    if err != nil {
        // Detect error type for the http answer
        if err == http.ErrNotMultipart || err == http.ErrMissingBoundary {
            w.WriteHeader(http.StatusBadRequest)
        } else {
            w.WriteHeader(http.StatusInternalServerError)
        }
        // Try to write the error as http body
        _, wErr := w.Write([]byte(err.Error()))
        if wErr != nil {
            err = fmt.Errorf("request error: %v | write error: %v", err, wErr)
        }
        // Log the error
        fmt.Println("can't create a multipart reader from request:", err)
        return
    }
    // Use the multipart reader to parse the request body
    payload, thumb, err := plexwebhooks.Extract(multiPartReader)
    if err != nil {
        w.WriteHeader(http.StatusInternalServerError)
        // Try to write the error as http body
        _, wErr := w.Write([]byte(err.Error()))
        if wErr != nil {
            err = fmt.Errorf("request error: %v | write error: %v", err, wErr)
        }
        // Log the error
        fmt.Println("can't create a multipart reader from request:", err)
        return
    }
    // Do something
    fmt.Println()
    fmt.Println(time.Now())
    fmt.Printf("%+v\n", *payload)
    if thumb != nil {
        fmt.Printf("Name: %s | Size: %d\n", thumb.Filename, len(thumb.Data))
    }
    fmt.Println()
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Extract

func Extract(mpr *multipart.Reader) (payload *Payload, thumbnail *Thumbnail, err error)

Extract extracts the payload and the thumbnail (if present) from a multipart reader

Types

type Account

type Account struct {
	ID    int `json:"id"` // server relative id (owner is 1)
	Thumb *url.URL
	Title string `json:"title"` // username
}

Account represent the account which has generated the wehhook launch on the server

func (*Account) UnmarshalJSON

func (a *Account) UnmarshalJSON(data []byte) (err error)

UnmarshalJSON allows to convert json values to Go types

type EventType

type EventType string

EventType represent the webhook event type

const (
	// EventTypePause represents the play event
	EventTypePause EventType = "media.pause"
	// EventTypePlay represents the play event
	EventTypePlay EventType = "media.play"
	// EventTypeRate represents the rate event
	EventTypeRate EventType = "media.rate"
	// EventTypeResume represents the resume event
	EventTypeResume EventType = "media.resume"
	// EventTypeScrobble represents the scrobble event
	EventTypeScrobble EventType = "media.scrobble"
	// EventTypeStop represents the stop event
	EventTypeStop EventType = "media.stop"
)

type LibrarySection

type LibrarySection string

LibrarySection represents the of the library section

const (
	// LibrarySectionShow represents the shows library type
	LibrarySectionShow LibrarySection = "show"
	// LibrarySectionMusic represents the music library type
	LibrarySectionMusic LibrarySection = "artist"
	// LibrarySectionMovie represents the movies library type
	LibrarySectionMovie LibrarySection = "movie"
)

type MediaSubType added in v1.0.0

type MediaSubType string

MediaSubType represente the subtype of media related to the webhook event

const (
	// MediaSubTypeMovie represents the media sub type for a trailer
	MediaSubTypeMovie MediaSubType = "trailer"
	// MediaSubTypeBehindTheScenes represents the media sub type for a behind the scenes clip
	MediaSubTypeBehindTheScenes MediaSubType = "behindTheScenes"
)

type MediaType

type MediaType string

MediaType represente the type of media related to the webhook event

const (
	// MediaTypeMovie represents the media type for a movie
	MediaTypeMovie MediaType = "movie"
	// MediaTypeEpisode represents the media type for a show episode
	MediaTypeEpisode MediaType = "episode"
	// MediaTypeTrack represents the media type for an audio track
	MediaTypeTrack MediaType = "track"
	// MediaTypeClip represents the media type for a clip
	MediaTypeClip MediaType = "clip"
	// MediaTypePhoto represents the media type for a photo
	MediaTypePhoto MediaType = "photo"
)

type Metadata

type Metadata struct {
	AddedAt               time.Time           `json:"addedAt"`               // movie + show + music
	Art                   string              `json:"art"`                   // movie + show
	AudienceRating        float64             `json:"audienceRating"`        // movie
	AudienceRatingImage   string              `json:"audienceRatingImage"`   // movie
	Banner                *url.URL            `json:"banner"`                // movie
	Channel               []MetadataItem      `json:"Channel"`               // tv movie
	ChapterSource         string              `json:"chapterSource"`         // show (movie too ?)
	Collection            []MetadataItem      `json:"Collection"`            // movie
	ContentRating         string              `json:"contentRating"`         // movie + show
	Country               []MetadataItem      `json:"Country"`               // movie
	CreatedAtAccuracy     string              `json:"createdAtAccuracy"`     // photo
	CreatedAtTZOffset     string              `json:"createdAtTZOffset"`     // photo
	Director              []MetadataItem      `json:"Director"`              // movie + show
	Duration              time.Duration       `json:"duration"`              // movie
	Field                 []MetadataItemField `json:"Field"`                 // tv movie
	Genre                 []MetadataItem      `json:"Genre"`                 // movie
	GenuineMediaAnalysis  string              `json:"genuineMediaAnalysis"`  // show
	GrandparentArt        string              `json:"grandparentArt"`        // show
	GrandparentKey        string              `json:"grandparentKey"`        // music
	GrandparentRatingKey  string              `json:"grandparentRatingKey"`  // show + music
	GrandparentTheme      string              `json:"grandparentTheme"`      // show
	GrandparentThumb      string              `json:"grandparentThumb"`      // show + music
	GrandparentTitle      string              `json:"grandparentTitle"`      // music
	GUID                  *url.URL            `json:"guid"`                  // movie + show + music
	GUIDExternal          []*url.URL          `json:"Guid"`                  // movie + show
	Index                 int                 `json:"index"`                 // show + music
	Indirect              bool                `json:"indirect"`              // movie
	Key                   string              `json:"key"`                   // movie + show + music
	LastRatedAt           time.Time           `json:"lastRatedAt"`           // movie + show + music
	LastViewedAt          time.Time           `json:"lastViewedAt"`          // movie + show + music
	LibrarySectionID      int                 `json:"librarySectionID"`      // movie + show + music
	LibrarySectionKey     string              `json:"librarySectionKey"`     // movie + show + music
	LibrarySectionTitle   string              `json:"librarySectionTitle"`   // movie + show + music
	LibrarySectionType    LibrarySection      `json:"librarySectionType"`    // movie + show + music
	Live                  string              `json:"live"`                  // show
	Mood                  []MetadataItem      `json:"Mood"`                  // music
	OneShot               string              `json:"oneShot"`               // tv movie
	OriginallyAvailableAt time.Time           `json:"originallyAvailableAt"` // movie
	OriginalTitle         string              `json:"originalTitle"`         // music
	ParentArt             string              `json:"parentArt"`             // show
	ParentIndex           int                 `json:"parentIndex"`           // show + music
	ParentKey             string              `json:"parentKey"`             // music
	ParentRatingKey       string              `json:"parentRatingKey"`       // show + music
	ParentThumb           string              `json:"parentThumb"`           // show + music
	ParentTitle           string              `json:"parentTitle"`           // music
	ParentYear            int                 `json:"parentYear"`            // music
	PrimaryExtraKey       string              `json:"primaryExtraKey"`       // movie
	Producer              []MetadataItem      `json:"Producer"`              // movie
	Rating                float64             `json:"rating"`                // movie + show
	RatingCount           int                 `json:"ratingCount"`           // music
	RatingImage           string              `json:"ratingImage"`           // movie
	RatingKey             string              `json:"ratingKey"`             // movie + show + music
	Role                  []MetadataItemRole  `json:"Role"`                  // movie
	Similar               []MetadataItem      `json:"Similar"`               // movie
	Studio                string              `json:"studio"`                // movie
	SubType               MediaSubType        `json:"subtype"`               // clip
	Summary               string              `json:"summary"`               // movie + show + music
	Tagline               string              `json:"tagline"`               // movie
	Thumb                 string              `json:"thumb"`                 // movie + show + music
	Title                 string              `json:"title"`                 // movie + show + music
	TitleSort             string              `json:"titleSort"`             // show (should be movie too)
	Type                  MediaType           `json:"type"`                  // movie + show + music
	UpdatedAt             time.Time           `json:"updatedAt"`             // movie + show + music
	UserRating            float64             `json:"userRating"`            // movie
	ViewCount             int                 `json:"viewCount"`             // movie + show + music
	ViewOffset            int                 `json:"viewOffset"`            // movie
	Writer                []MetadataItem      `json:"Writer"`                // movie + show
	Year                  int                 `json:"year"`                  // movie + show
}

Metadata represents all the metadata associated with a media sent by the webhook

func (*Metadata) UnmarshalJSON

func (m *Metadata) UnmarshalJSON(data []byte) (err error)

UnmarshalJSON allows to convert json values to Go types

type MetadataGUID added in v1.1.0

type MetadataGUID struct {
	ID string `json:"id"`
}

MetadataGUID represents a ref to third-party ids, i.e. imdb and tmdb

type MetadataItem

type MetadataItem struct {
	ID     int    `json:"id"`
	Filter string `json:"filter"`
	Tag    string `json:"tag"`
	Count  int    `json:"count"`
}

MetadataItem represents a ref to an external entity

type MetadataItemField added in v1.0.0

type MetadataItemField struct {
	Locked bool   `json:"locked"`
	Name   string `json:"name"`
}

MetadataItemField represents a ref to a Metadata.Field entity

type MetadataItemRole

type MetadataItemRole struct {
	MetadataItem
	Role  string `json:"role"`
	Thumb *url.URL
}

MetadataItemRole is a specialisation for roles of MetadataItem

func (*MetadataItemRole) UnmarshalJSON

func (mir *MetadataItemRole) UnmarshalJSON(data []byte) (err error)

UnmarshalJSON allows to convert json values to Go types

type Payload

type Payload struct {
	Rating   int       // only present for Event == EventTypeRate
	Event    EventType `json:"event"`
	User     bool      `json:"user"`
	Owner    bool      `json:"owner"`
	Account  Account   `json:"Account"`
	Server   Server    `json:"Server"`
	Player   Player    `json:"Player"`
	Metadata Metadata  `json:"Metadata"`
}

Payload represents the base structure for all plex webhooks

func (*Payload) UnmarshalJSON

func (p *Payload) UnmarshalJSON(data []byte) (err error)

UnmarshalJSON allows to convert json values to Go types

type Player

type Player struct {
	Local         bool `json:"local"`
	PublicAddress net.IP
	Title         string `json:"title"`
	UUID          string `json:"uuid"`
}

Player holds informations about the user's player

func (*Player) UnmarshalJSON

func (p *Player) UnmarshalJSON(data []byte) (err error)

UnmarshalJSON allows to convert json values to Go types

type Server

type Server struct {
	Title string `json:"title"`
	UUID  string `json:"uuid"`
}

Server holds informations about the server which generated the webhook

type Thumbnail

type Thumbnail struct {
	Filename string
	Data     []byte
}

Thumbnail contains all the relevant data about the thumbnail file (if sended).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL