file_path
stringlengths
3
280
file_language
stringclasses
66 values
content
stringlengths
1
1.04M
repo_name
stringlengths
5
92
repo_stars
int64
0
154k
repo_description
stringlengths
0
402
repo_primary_language
stringclasses
108 values
developer_username
stringlengths
1
25
developer_name
stringlengths
0
30
developer_company
stringlengths
0
82
tests/karma.conf.js
JavaScript
module.exports = function(config) { config.set({ frameworks: ['qunit'], basePath: '.', files: [ '../index.js', '../tests/tests.js' ], singleRun: false, }); };
zloirock/dtf
42
Date formatting
JavaScript
zloirock
Denis Pushkarev
tests/tests.html
HTML
<!DOCTYPE html> <meta charset='UTF-8'> <title>dtf</title> <link rel='stylesheet' href='https://code.jquery.com/qunit/qunit-1.16.0.css'> <div id='qunit'></div> <div id='qunit-fixture'></div> <script src='https://code.jquery.com/qunit/qunit-1.16.0.js'></script> <script src='../index.js'></script> <script src='./tests.js'></script>
zloirock/dtf
42
Date formatting
JavaScript
zloirock
Denis Pushkarev
tests/tests.js
JavaScript
var date = new Date(1, 2, 3, 4, 5, 6, 7); function isFunction(it){ return {}.toString.call(it).slice(8, -1) === 'Function'; } QUnit.test('dtf.locale', function(assert){ assert.ok(isFunction(dtf.locale), 'Is function'); dtf.locale('en'); assert.strictEqual(dtf.locale(), 'en', '.locale() is "en"'); assert.strictEqual(dtf.locale('ru'), 'ru', '.locale("ru") is "ru"'); assert.strictEqual(dtf.locale(), 'ru', '.locale() is "ru"'); assert.strictEqual(dtf.locale('xx'), 'ru', '.locale("xx") is "ru"'); }); QUnit.test('dtf.addLocale', function(assert){ assert.ok(isFunction(dtf.addLocale), 'Is function'); assert.strictEqual(dtf.locale('en'), 'en'); assert.strictEqual(dtf.locale('zz'), 'en'); dtf.addLocale('zz', { weekdays: 'Воскресенье,Понедельник,Вторник,Среда,Четверг,Пятница,Суббота', months: 'Январ:я|ь,Феврал:я|ь,Март:а|,Апрел:я|ь,Ма:я|й,Июн:я|ь,Июл:я|ь,Август:а|,Сентябр:я|ь,Октябр:я|ь,Ноябр:я|ь,Декабр:я|ь' }); assert.strictEqual(dtf.locale('zz'), 'zz'); assert.strictEqual(dtf.format(new Date(1, 2, 3, 4, 5, 6, 7), 'W, D MM Y'), 'Воскресенье, 3 Марта 1901'); }); QUnit.test('dtf.format', function(assert){ assert.ok(isFunction(dtf.format), 'Is function'); assert.strictEqual(dtf.format(date, 'DD.NN.Y'), '03.03.1901', 'Works basic'); dtf.locale('en'); assert.strictEqual(dtf.format(date, 's ss m mm h hh D DD W N NN M MM YY foo Y'), '6 06 5 05 4 04 3 03 Sunday 3 03 March March 01 foo 1901', 'Works with defaut locale'); dtf.locale('ru'); assert.strictEqual(dtf.format(date, 's ss m mm h hh D DD W N NN M MM YY foo Y'), '6 06 5 05 4 04 3 03 Воскресенье 3 03 Март Марта 01 foo 1901', 'Works with set in Date.locale locale'); }); QUnit.test('dtf.formatUTC', function(assert){ assert.ok(isFunction(dtf.formatUTC), 'Is function'); assert.strictEqual(dtf.formatUTC(date, 'h'), '' + date.getUTCHours(), 'Works'); }); QUnit.test('dtf.extend', function(assert){ assert.ok(isFunction(dtf.extend), 'Is function'); assert.ok(!isFunction(Date.prototype.format), 'Before dtf.extend() Date.prototype.format is absent'); assert.ok(!isFunction(Date.prototype.formatUTC), 'Before dtf.extend() Date.prototype.formatUTC is absent'); dtf.extend(); assert.ok(isFunction(Date.prototype.format), 'Before dtf.extend() Date.prototype.format is present'); assert.ok(isFunction(Date.prototype.formatUTC), 'Before dtf.extend() Date.prototype.formatUTC is present'); }); QUnit.test('Date#format', function(assert){ assert.ok(isFunction(Date.prototype.format), 'Is function'); assert.strictEqual(date.format('DD.NN.Y'), '03.03.1901', 'Works basic'); dtf.locale('en'); assert.strictEqual(date.format('s ss m mm h hh D DD W N NN M MM YY foo Y'), '6 06 5 05 4 04 3 03 Sunday 3 03 March March 01 foo 1901', 'Works with defaut locale'); dtf.locale('ru'); assert.strictEqual(date.format('s ss m mm h hh D DD W N NN M MM YY foo Y'), '6 06 5 05 4 04 3 03 Воскресенье 3 03 Март Марта 01 foo 1901', 'Works with set in Date.locale locale'); }); QUnit.test('Date#formatUTC', function(assert){ assert.ok(isFunction(Date.prototype.formatUTC), 'Is function'); assert.strictEqual(date.formatUTC('h'), '' + date.getUTCHours(), 'Works'); });
zloirock/dtf
42
Date formatting
JavaScript
zloirock
Denis Pushkarev
index.mjs
JavaScript
import { basename } from 'node:path'; const meta = { type: 'layout', docs: { description: 'ensure that filenames match a convention', }, messages: { noMatch: 'Filename `{{name}}` does not match {{value}}', }, fixable: false, schema: false, }; function create(context) { return { Program(node) { const filename = basename(context.filename); const [regex] = context.options; if (!regex.test(filename)) { context.report({ node, messageId: 'noMatch', data: { name: filename, value: String(regex), }, }); } }, }; } export default { rules: { match: { meta, create, } }, };
zloirock/eslint-plugin-name
0
JavaScript
zloirock
Denis Pushkarev
lib/components/godoc-panel-view.js
JavaScript
/** @babel */ /** @jsx etch.dom */ import etch from 'etch' export default class GodocPanelView { constructor (props) { if (props.model) { props.model.view = this } this.props = props etch.initialize(this) etch.setScheduler(atom.views) } update (props) { let oldProps = this.props this.props = Object.assign({}, oldProps, props) return etch.update(this) } dispose () { this.destroy() } destroy () { etch.destroy(this) } render () { return ( <div> <span tabindex='0' className='godoc-panel'>{this.props.model.doc}</span> </div> ) } }
zmb3/godoc
3
Deprecated - use https://atom.io/packages/go-plus instead
JavaScript
zmb3
Zac Bergquist
gravitational
lib/godoc-panel.js
JavaScript
'use babel' import {CompositeDisposable} from 'atom' export default class GodocPanel { constructor (goconfigFunc) { this.key = 'reference' this.subscriptions = new CompositeDisposable() let keymap = 'alt-d' let bindings = atom.keymaps.findKeyBindings({command: 'golang:showdoc'}) if (bindings && bindings.length) { keymap = bindings[0].keystrokes } this.doc = `Place the cursor on a symbol and run the "golang:showdoc" command (bound to ${keymap})...` } dispose () { if (this.subscriptions) { this.subscriptions.dispose() } this.subscriptions = null } updateContent (doc) { this.doc = doc if (!doc) { return } if (this.requestFocus) { this.requestFocus() } if (this.view) { this.view.update() } } }
zmb3/godoc
3
Deprecated - use https://atom.io/packages/go-plus instead
JavaScript
zmb3
Zac Bergquist
gravitational
lib/godoc.js
JavaScript
'use babel' import path from 'path' import {CompositeDisposable, Point} from 'atom' import GodocPanel from './godoc-panel' class Godoc { constructor (goconfigFunc, gogetFunc) { this.goconfig = goconfigFunc this.goget = gogetFunc this.subscriptions = new CompositeDisposable() this.panelModel = new GodocPanel() this.subscriptions.add(this.panelModel) this.subscriptions.add(atom.commands.add( 'atom-text-editor', 'golang:showdoc', () => this.commandInvoked())) } commandInvoked () { let editor = atom.workspace.getActiveTextEditor() if (!this.isValidEditor(editor)) { return } return this.checkForTool(editor).then((cmd) => { if (!cmd) { // TODO: notification? return {success: false, result: null} } let file = editor.getBuffer().getPath() let cwd = path.dirname(file) let offset = this.editorByteOffset(editor) // package up unsaved buffers in the Guru archive format let archive = '' for (let e of atom.workspace.getTextEditors()) { if (e.isModified() && this.isValidEditor(e)) { archive += e.getTitle() + '\n' archive += Buffer.byteLength(e.getText(), 'utf8') + '\n' archive += e.getText() } } return this.getDoc(file, offset, cwd, cmd, archive) }) } checkForTool (editor) { if (!this.goconfig || !this.goconfig()) { return Promise.resolve(false) } let config = this.goconfig() let options = {} if (editor && editor.getPath()) { options.file = editor.getPath() options.directory = path.dirname(options.file) } if (!options.directory && atom.project.getPaths().length > 0) { options.directory = atom.project.getPaths()[0] } return config.locator.findTool('gogetdoc', options).then((cmd) => { if (cmd) { return cmd } // first check for Go 1.6+, if we don't have that, don't even offer to // 'go get', since it will definitely fail return config.locator.runtime(options).then((runtime) => { if (!runtime) { return false } let components = runtime.semver.split('.') if (!components || components.length < 2) { return false } let minor = parseInt(components[1], 10) if (minor < 6) { atom.notifications.addError('godoc requires Go 1.6 or later', { detail: 'The godoc package uses the `gogetdoc` tool, which requires Go 1.6 or later; please update your Go installation to use this package.', dismissable: true }) return false } if (!this.goget || !this.goget()) { return false } let get = this.goget() return get.get({ name: 'gogetdoc', packageName: 'gogetdoc', packagePath: 'github.com/zmb3/gogetdoc', type: 'missing' }).then((r) => { if (r.success) { return config.locator.findTool('gogetdoc', options) } console.log('gogetdoc is not available and could not be installed via "go get -u github.com/zmb3/gogetdoc"; please manually install it to enable doc functionality') return false }).catch((e) => { console.log(e) }) }) }) } dispose () { this.subscriptions.dispose() this.subscriptions = null this.goconfig = null this.panelModel = null } getDoc (file, offset, cwd, cmd, stdin) { let config = this.goconfig() if (!config || !config.executor) { return {success: false, result: null} } // use a large line length because Atom will wrap the paragraphs automatically let args = ['-pos', `${file}:#${offset}`, '-linelength', '999'] let options = {cwd: cwd} if (stdin && stdin !== '') { args.push('-modified') options.input = stdin console.log(stdin) } this.panelModel.updateContent('Generating documentation...') return config.executor.exec(cmd, args, options).then((r) => { if (r.error) { if (r.error.code === 'ENOENT') { atom.notifications.addError('Missing Tool', { detail: 'Missing the `gogetdoc` tool.', dismissable: true }) } else { atom.notifications.addError('Error', { detail: r.error.message, dismissable: true }) } return {success: false, result: r} } let message = r.stdout.trim() if (message) { this.panelModel.updateContent(message) } if (r.exitcode !== 0 || r.stderr && r.stderr.trim() !== '') { // TODO: notification? return {success: false, result: r} } return {success: true, result: r} }) } isValidEditor (editor) { if (!editor) { return false } let grammar = editor.getGrammar() return grammar && grammar.scopeName === 'source.go' } editorByteOffset (editor) { let cursor = editor.getLastCursor() let range = cursor.getCurrentWordBufferRange() let middle = new Point(range.start.row, Math.floor((range.start.column + range.end.column) / 2)) let charOffset = editor.buffer.characterIndexForPosition(middle) let text = editor.getText().substring(0, charOffset) return Buffer.byteLength(text, 'utf8') } getPanel () { return this.panelModel } } export {Godoc}
zmb3/godoc
3
Deprecated - use https://atom.io/packages/go-plus instead
JavaScript
zmb3
Zac Bergquist
gravitational
lib/main.js
JavaScript
'use babel' import {CompositeDisposable} from 'atom' import {Godoc} from './godoc' import GodocPanelView from './components/godoc-panel-view' export default { subscriptions: null, dependenciesInstalled: null, goconfig: null, goget: null, godoc: null, toolRegistered: null, activate () { this.godoc = new Godoc( () => { return this.getGoconfig() }, () => { return this.getGoget() } ) this.subscriptions = new CompositeDisposable() require('atom-package-deps').install('godoc').then(() => { this.dependenciesInstalled = true }).catch((e) => { console.log(e) }) }, deactivate () { if (this.subscriptions) { this.subscriptions.dispose() } this.subscriptions = null this.godoc = null this.goconfig = null this.goget = null this.dependenciesInstalled = null }, getGoconfig () { if (this.goconfig) { return this.goconfig } return false }, consumeGoconfig (service) { this.goconfig = service }, getGoget () { if (this.goget) { return this.goget } return false }, consumeGoget (service) { this.goget = service this.registerTool() }, registerTool () { if (this.toolRegistered || !this.goget || !this.goget.register) { return } this.subscriptions.add(this.goget.register('github.com/zmb3/gogetdoc')) this.toolRegistered = true }, provideGoPlusView () { return { view: GodocPanelView, model: this.godoc.getPanel() } } }
zmb3/godoc
3
Deprecated - use https://atom.io/packages/go-plus instead
JavaScript
zmb3
Zac Bergquist
gravitational
spec/fixtures/main.go
Go
package main import ( "fmt" "io" "os" "strings" ) // Foo has a message. type Foo struct { // Message is a test message. Message string } // ChangeMessage changes the Foo's message. func (f *Foo) ChangeMessage(msg string) { f.Message = msg } func main() { fmt.Println("Hello, World") f := &Foo{"This is a test\n"} io.Copy(os.Stdout, strings.NewReader(f.Message)) f.ChangeMessage("This is the new message\n") }
zmb3/godoc
3
Deprecated - use https://atom.io/packages/go-plus instead
JavaScript
zmb3
Zac Bergquist
gravitational
spec/godoc-spec.js
JavaScript
'use babel' /* eslint-env jasmine */ import temp from 'temp' import path from 'path' import fs from 'fs-plus' describe('godoc', () => { temp.track() let mainModule = null let godoc = null let editor = null let gopath = null let oldGopath = null let source = null let target = null beforeEach(() => { runs(() => { if (process.env.GOPATH) { oldGopath = process.env.GOPATH } gopath = fs.realpathSync(temp.mkdirSync('gopath-')) process.env.GOPATH = gopath }) waitsForPromise(() => { return atom.packages.activatePackage('language-go').then(() => { return atom.packages.activatePackage('go-config').then(() => { return atom.packages.activatePackage('godoc').then((pack) => { mainModule = pack.mainModule godoc = mainModule.godoc return }) }) }) }) waitsFor(() => { return mainModule.getGoconfig() !== false }) }) afterEach(() => { if (oldGopath) { process.env.GOPATH = oldGopath } else { delete process.env.GOPATH } }) describe('when the godoc command is invoked on a valid go file', () => { beforeEach(() => { runs(() => { source = path.join(__dirname, 'fixtures') target = path.join(gopath, 'src', 'godoctest') fs.copySync(source, target) }) waitsForPromise(() => { return atom.workspace.open(path.join(target, 'main.go')).then((e) => { editor = e return }) }) }) it('gets the correct documentation', () => { let result = false editor.setCursorBufferPosition([24, 10]) waitsForPromise(() => { return godoc.commandInvoked().then((r) => { result = r }) }) runs(() => { expect(result).toBeTruthy() expect(result.success).toBe(true) expect(result.result.exitcode).toBe(0) }) }) }) describe('when the godoc command is invoked on an unsaved go file', () => { beforeEach(() => { runs(() => { source = path.join(__dirname, 'fixtures') target = path.join(gopath, 'src', 'godoctest') fs.copySync(source, target) }) waitsForPromise(() => { return atom.workspace.open(path.join(target, 'main.go')).then((e) => { e.setCursorBufferPosition([25, 46]) e.selectLinesContainingCursors() e.insertText('fmt.Printf("this line has been modified\n")') expect(e.isModified()).toBe(true) editor = e return }) }) }) it('gets the correct documentation', () => { let result = false editor.setCursorBufferPosition([25, 7]) waitsForPromise(() => { return godoc.commandInvoked().then((r) => { result = r }) }) runs(() => { expect(result).toBeTruthy() expect(result.success).toBe(true) expect(result.result.exitcode).toBe(0) expect(result.result.stdout).toBeTruthy() expect(result.result.stdout.startsWith('import "fmt"')).toBe(true) }) }) }) })
zmb3/godoc
3
Deprecated - use https://atom.io/packages/go-plus instead
JavaScript
zmb3
Zac Bergquist
gravitational
spec/main-spec.js
JavaScript
'use babel' /* eslint-env jasmine */ describe('godoc', () => { let mainModule = null beforeEach(() => { waitsForPromise(() => { return atom.packages.activatePackage('go-config').then(() => { return atom.packages.activatePackage('godoc') }).then((pack) => { mainModule = pack.mainModule }) }) waitsFor(() => { return mainModule.getGoconfig() !== false }) }) describe('when the godoc package is activated', () => { it('activates successfully', () => { expect(mainModule).toBeDefined() expect(mainModule).toBeTruthy() expect(mainModule.getGoconfig).toBeDefined() expect(mainModule.consumeGoconfig).toBeDefined() expect(mainModule.getGoconfig()).toBeTruthy() }) }) })
zmb3/godoc
3
Deprecated - use https://atom.io/packages/go-plus instead
JavaScript
zmb3
Zac Bergquist
gravitational
styles/godoc.less
LESS
.godoc-panel { white-space: pre-wrap; }
zmb3/godoc
3
Deprecated - use https://atom.io/packages/go-plus instead
JavaScript
zmb3
Zac Bergquist
gravitational
builtin.go
Go
package main import ( "go/ast" "go/doc" "go/parser" "go/token" "go/types" "log" "golang.org/x/tools/go/packages" ) func builtinPackage() *doc.Package { pkgs, err := packages.Load(&packages.Config{Mode: packages.LoadFiles}, "builtin") if err != nil { log.Fatalf("error getting metadata of builtin: %v", err) } pkg := pkgs[0] fs := token.NewFileSet() fileMap := make(map[string]*ast.File) for _, filename := range pkg.GoFiles { file, err := parser.ParseFile(fs, filename, nil, parser.ParseComments) if err != nil { log.Fatal(err) } fileMap[filename] = file } astPkg := &ast.Package{ Name: pkg.Name, Files: fileMap, } return doc.New(astPkg, "builtin", doc.AllDecls) } // findInBuiltin searches for an identifier in the builtin package. // It searches in the following order: funcs, constants and variables, // and finally types. func findInBuiltin(name string, obj types.Object, prog *packages.Package) (docstring, decl string) { pkg := builtinPackage() consts := make([]*doc.Value, 0, 2*len(pkg.Consts)) vars := make([]*doc.Value, 0, 2*len(pkg.Vars)) funcs := make([]*doc.Func, 0, 2*len(pkg.Funcs)) consts = append(consts, pkg.Consts...) vars = append(vars, pkg.Vars...) funcs = append(funcs, pkg.Funcs...) for _, t := range pkg.Types { funcs = append(funcs, t.Funcs...) consts = append(consts, t.Consts...) vars = append(vars, t.Vars...) } // funcs for _, f := range funcs { if f.Name == name { return f.Doc, formatNode(f.Decl, obj, prog) } } // consts/vars for _, v := range consts { for _, n := range v.Names { if n == name { return v.Doc, "" } } } for _, v := range vars { for _, n := range v.Names { if n == name { return v.Doc, "" } } } // types for _, t := range pkg.Types { if t.Name == name { return t.Doc, formatNode(t.Decl, obj, prog) } } return "", "" }
zmb3/gogetdoc
185
Gets documentation for items in Go source code.
Go
zmb3
Zac Bergquist
gravitational
doc.go
Go
package main import ( "bytes" "fmt" "go/doc" ) const ( indent = "" preIndent = " " ) // Doc holds the resulting documentation for a particular item. type Doc struct { Name string `json:"name"` Import string `json:"import"` Pkg string `json:"pkg"` Decl string `json:"decl"` Doc string `json:"doc"` Pos string `json:"pos"` } func (d *Doc) String() string { buf := &bytes.Buffer{} if d.Import != "" { fmt.Fprintf(buf, "import \"%s\"\n\n", d.Import) } fmt.Fprintf(buf, "%s\n\n", d.Decl) if d.Doc == "" { d.Doc = "Undocumented." } doc.ToText(buf, d.Doc, indent, preIndent, *linelength) return buf.String() }
zmb3/gogetdoc
185
Gets documentation for items in Go source code.
Go
zmb3
Zac Bergquist
gravitational
ident.go
Go
package main import ( "bytes" "fmt" "go/ast" "go/printer" "go/token" "go/types" "strings" "golang.org/x/tools/go/ast/astutil" "golang.org/x/tools/go/packages" ) func findTypeSpec(decl *ast.GenDecl, pos token.Pos) *ast.TypeSpec { for _, spec := range decl.Specs { typeSpec := spec.(*ast.TypeSpec) if typeSpec.Pos() == pos { return typeSpec } } return nil } func findVarSpec(decl *ast.GenDecl, pos token.Pos) *ast.ValueSpec { for _, spec := range decl.Specs { varSpec := spec.(*ast.ValueSpec) for _, ident := range varSpec.Names { if ident.Pos() == pos { return varSpec } } } return nil } func formatNode(n ast.Node, obj types.Object, prog *packages.Package) string { // fmt.Printf("formatting %T node\n", n) qual := func(p *types.Package) string { return "" } // We'd like to use types.ObjectString(obj, qual) where we can, // but there are several cases where we must render a copy of the AST // node with no documentation (we emit that ourselves). // 1) FuncDecl: ObjectString won't give us the decl for builtins // 2) TypeSpec: ObjectString does not allow us to trim unexported fields // 3) GenDecl: we need to find the inner {Type|Var}Spec var nc ast.Node switch n := n.(type) { case *ast.FuncDecl: cp := *n cp.Doc = nil cp.Body = nil // Don't print the whole function body nc = &cp case *ast.TypeSpec: specCp := *n if !*showUnexportedFields { trimUnexportedElems(&specCp) } specCp.Doc = nil typeSpec := ast.GenDecl{ Tok: token.TYPE, Specs: []ast.Spec{&specCp}, } nc = &typeSpec case *ast.GenDecl: cp := *n cp.Doc = nil if len(n.Specs) > 0 { // Only print this one type, not all the types in the gendecl switch n.Specs[0].(type) { case *ast.TypeSpec: spec := findTypeSpec(n, obj.Pos()) if spec != nil { specCp := *spec if !*showUnexportedFields { trimUnexportedElems(&specCp) } specCp.Doc = nil cp.Specs = []ast.Spec{&specCp} } cp.Lparen = 0 cp.Rparen = 0 case *ast.ValueSpec: spec := findVarSpec(n, obj.Pos()) if spec != nil { specCp := *spec specCp.Doc = nil cp.Specs = []ast.Spec{&specCp} } cp.Lparen = 0 cp.Rparen = 0 } } nc = &cp case *ast.Field: return types.ObjectString(obj, qual) default: return types.ObjectString(obj, qual) } buf := &bytes.Buffer{} cfg := printer.Config{Mode: printer.UseSpaces | printer.TabIndent, Tabwidth: 8} err := cfg.Fprint(buf, prog.Fset, nc) if err != nil { return obj.String() } return stripVendorFromImportPath(buf.String()) } // IdentDoc attempts to get the documentation for a *ast.Ident. func IdentDoc(id *ast.Ident, info *types.Info, pkg *packages.Package) (*Doc, error) { // get definition of identifier obj := info.ObjectOf(id) // for anonymous fields, we want the type definition, not the field if v, ok := obj.(*types.Var); ok && v.Anonymous() { obj = info.Uses[id] } var pos string if p := obj.Pos(); p.IsValid() { pos = pkg.Fset.Position(p).String() } pkgPath, pkgName := "", "" if op := obj.Pkg(); op != nil { pkgPath = op.Path() pkgName = op.Name() } // handle packages imported under a different name if p, ok := obj.(*types.PkgName); ok { return PackageDoc(pkg, p.Imported().Path()) } nodes := pathEnclosingInterval(pkg, obj.Pos(), obj.Pos()) if len(nodes) == 0 { // special case - builtins doc, decl := findInBuiltin(obj.Name(), obj, pkg) if doc != "" { return &Doc{ Import: "builtin", Pkg: "builtin", Name: obj.Name(), Doc: doc, Decl: decl, Pos: pos, }, nil } return nil, fmt.Errorf("no documentation found for %s", obj.Name()) } var doc *Doc for _, node := range nodes { switch node.(type) { case *ast.Ident: // continue ascending AST (searching for parent node of the identifier) continue case *ast.FuncDecl, *ast.GenDecl, *ast.Field, *ast.TypeSpec, *ast.ValueSpec: // found the parent node default: break } doc = &Doc{ Import: stripVendorFromImportPath(pkgPath), Pkg: pkgName, Name: obj.Name(), Decl: formatNode(node, obj, pkg), Pos: pos, } break } if doc == nil { // This shouldn't happen return nil, fmt.Errorf("no documentation found for %s", obj.Name()) } for _, node := range nodes { //fmt.Printf("for %s: found %T\n%#v\n", id.Name, node, node) switch n := node.(type) { case *ast.Ident: continue case *ast.FuncDecl: doc.Doc = n.Doc.Text() return doc, nil case *ast.Field: if n.Doc != nil { doc.Doc = n.Doc.Text() } else if n.Comment != nil { doc.Doc = n.Comment.Text() } return doc, nil case *ast.TypeSpec: if n.Doc != nil { doc.Doc = n.Doc.Text() return doc, nil } if n.Comment != nil { doc.Doc = n.Comment.Text() return doc, nil } case *ast.ValueSpec: if n.Doc != nil { doc.Doc = n.Doc.Text() return doc, nil } if n.Comment != nil { doc.Doc = n.Comment.Text() return doc, nil } case *ast.GenDecl: constValue := "" if c, ok := obj.(*types.Const); ok { constValue = c.Val().ExactString() } if doc.Doc == "" && n.Doc != nil { doc.Doc = n.Doc.Text() } if constValue != "" { doc.Doc += fmt.Sprintf("\nConstant Value: %s", constValue) } return doc, nil default: return doc, nil } } return doc, nil } // pathEnclosingInterval returns ast.Node of the package that // contain source interval [start, end), and all the node's ancestors // up to the AST root. It searches the ast.Files of initPkg and // the packages it imports recursively until something is found. // // Modified from golang.org/x/tools/go/loader. func pathEnclosingInterval(initPkg *packages.Package, start, end token.Pos) []ast.Node { for _, f := range initPkg.Syntax { if f.Pos() == token.NoPos { // This can happen if the parser saw // too many errors and bailed out. // (Use parser.AllErrors to prevent that.) continue } if !tokenFileContainsPos(initPkg.Fset.File(f.Pos()), start) { continue } if path, _ := astutil.PathEnclosingInterval(f, start, end); path != nil { return path } } for _, p := range initPkg.Imports { if path := pathEnclosingInterval(p, start, end); path != nil { return path } } return nil } func tokenFileContainsPos(f *token.File, pos token.Pos) bool { p := int(pos) base := f.Base() return base <= p && p < base+f.Size() } func stripVendorFromImportPath(ip string) string { vendor := "/vendor/" l := len(vendor) if i := strings.LastIndex(ip, vendor); i != -1 { return ip[i+l:] } return ip }
zmb3/gogetdoc
185
Gets documentation for items in Go source code.
Go
zmb3
Zac Bergquist
gravitational
ident_test.go
Go
package main import ( "go/token" "path/filepath" "runtime" "strings" "testing" "golang.org/x/tools/go/packages/packagestest" ) func TestIdent(t *testing.T) { dir := filepath.Join(".", "testdata", "package") mods := []packagestest.Module{ {Name: "somepkg", Files: packagestest.MustCopyFileTree(dir)}, } packagestest.TestAll(t, func(t *testing.T, exporter packagestest.Exporter) { if exporter == packagestest.Modules && !modulesSupported() { t.Skip("Skipping modules test on", runtime.Version()) } exported := packagestest.Export(t, exporter, mods) defer exported.Cleanup() teardown := setup(exported.Config) defer teardown() getDoc := func(p token.Position) *Doc { t.Helper() doc, docErr := Run(p.Filename, p.Offset, nil) if docErr != nil { t.Fatal(docErr) } return doc } pcmp := func(want, got string) { t.Helper() if !strings.HasPrefix(got, want) { if len(got) > 64 { got = got[:64] } t.Errorf("expected prefix %q in %q", want, got) } } cmp := func(want, got string) { t.Helper() if got != want { t.Errorf("want %q, got %q", want, got) } } if expectErr := exported.Expect(map[string]interface{}{ "doc": func(p token.Position, doc string) { pcmp(doc, getDoc(p).Doc) }, "pkg": func(p token.Position, pkg string) { cmp(pkg, getDoc(p).Pkg) }, "decl": func(p token.Position, decl string) { cmp(decl, getDoc(p).Decl) }, "const": func(p token.Position, val string) { d := getDoc(p) needle := "Constant Value: " + val if !strings.Contains(d.Doc, needle) { t.Errorf("Expected %q in %q", needle, d.Doc) } }, "exported": func(p token.Position) { for _, showUnexported := range []bool{true, false} { *showUnexportedFields = showUnexported d := getDoc(p) hasUnexportedField := strings.Contains(d.Decl, "notVisible") if hasUnexportedField != *showUnexportedFields { t.Errorf("show unexported fields is %v, but got %q", showUnexported, d.Decl) } } }, }); expectErr != nil { t.Fatal(expectErr) } }) } func TestVendoredCode(t *testing.T) { dir := filepath.Join(".", "testdata", "withvendor") mods := []packagestest.Module{ {Name: "main", Files: packagestest.MustCopyFileTree(dir)}, } exported := packagestest.Export(t, packagestest.GOPATH, mods) defer exported.Cleanup() teardown := setup(exported.Config) defer teardown() filename := exported.File("main", "main.go") getDoc := func(p token.Position) *Doc { t.Helper() doc, docErr := Run(filename, p.Offset, nil) if docErr != nil { t.Fatal(docErr) } return doc } compare := func(want, got string) { if want != got { t.Errorf("want %q, got %q", want, got) } } if expectErr := exported.Expect(map[string]interface{}{ "import": func(p token.Position, path string) { compare(path, getDoc(p).Import) }, "decl": func(p token.Position, decl string) { compare(decl, getDoc(p).Decl) }, "doc": func(p token.Position, doc string) { compare(doc, getDoc(p).Doc) }, }); expectErr != nil { t.Fatal(expectErr) } }
zmb3/gogetdoc
185
Gets documentation for items in Go source code.
Go
zmb3
Zac Bergquist
gravitational
main.go
Go
// gogetdoc gets documentation for Go objects given their locations in the source code package main import ( "encoding/json" "errors" "flag" "fmt" "go/ast" "go/build" "go/parser" "go/token" "io" "io/ioutil" "log" "os" "runtime/debug" "runtime/pprof" "strconv" "strings" "golang.org/x/tools/go/ast/astutil" "golang.org/x/tools/go/buildutil" "golang.org/x/tools/go/packages" ) var ( cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file") pos = flag.String("pos", "", "Filename and byte offset of item to document, e.g. foo.go:#123") modified = flag.Bool("modified", false, "read an archive of modified files from standard input") linelength = flag.Int("linelength", 80, "maximum length of a line in the output (in Unicode code points)") jsonOutput = flag.Bool("json", false, "enable extended JSON output") showUnexportedFields = flag.Bool("u", false, "show unexported fields") ) var archiveReader io.Reader = os.Stdin const modifiedUsage = ` The archive format for the -modified flag consists of the file name, followed by a newline, the decimal file size, another newline, and the contents of the file. This allows editors to supply gogetdoc with the contents of their unsaved buffers. ` const debugAST = false func fatal(args ...interface{}) { fmt.Fprintln(os.Stderr, args...) os.Exit(1) } func main() { // disable GC as gogetdoc is a short-lived program debug.SetGCPercent(-1) log.SetOutput(ioutil.Discard) flag.Var((*buildutil.TagsFlag)(&build.Default.BuildTags), "tags", buildutil.TagsFlagDoc) flag.Usage = func() { fmt.Fprintf(os.Stderr, "Usage of %s\n", os.Args[0]) flag.PrintDefaults() fmt.Fprintf(os.Stderr, modifiedUsage) } flag.Parse() if *cpuprofile != "" { f, err := os.Create(*cpuprofile) if err != nil { fatal(err) } if err := pprof.StartCPUProfile(f); err != nil { fatal(err) } defer pprof.StopCPUProfile() } filename, offset, err := parsePos(*pos) if err != nil { fatal(err) } var overlay map[string][]byte if *modified { overlay, err = buildutil.ParseOverlayArchive(archiveReader) if err != nil { fatal(fmt.Errorf("invalid archive: %v", err)) } } d, err := Run(filename, offset, overlay) if err != nil { fatal(err) } if *jsonOutput { json.NewEncoder(os.Stdout).Encode(d) } else { fmt.Println(d.String()) } } // Load loads the package containing the specified file and returns the AST file // containing the search position. It can optionally load modified files from // an overlay archive. func Load(filename string, offset int, overlay map[string][]byte) (*packages.Package, []ast.Node, error) { type result struct { nodes []ast.Node err error } ch := make(chan result, 1) // Adapted from: https://github.com/ianthehat/godef fstat, fstatErr := os.Stat(filename) parseFile := func(fset *token.FileSet, fname string, src []byte) (*ast.File, error) { var ( err error s os.FileInfo ) isInputFile := false if filename == fname { isInputFile = true } else if fstatErr != nil { isInputFile = false } else if s, err = os.Stat(fname); err == nil { isInputFile = os.SameFile(fstat, s) } mode := parser.ParseComments if isInputFile && debugAST { mode |= parser.Trace } file, err := parser.ParseFile(fset, fname, src, mode) if file == nil { if isInputFile { ch <- result{nil, err} } return nil, err } var keepFunc *ast.FuncDecl if isInputFile { // find the start of the file (which may be before file.Pos() if there are // comments before the package clause) start := file.Pos() if len(file.Comments) > 0 && file.Comments[0].Pos() < start { start = file.Comments[0].Pos() } pos := start + token.Pos(offset) if pos > file.End() { err := fmt.Errorf("cursor %d is beyond end of file %s (%d)", offset, fname, file.End()-file.Pos()) ch <- result{nil, err} return file, err } path, _ := astutil.PathEnclosingInterval(file, pos, pos) if len(path) < 1 { err := fmt.Errorf("offset was not a valid token") ch <- result{nil, err} return nil, err } // if we are inside a function, we need to retain that function body // start from the top not the bottom for i := len(path) - 1; i >= 0; i-- { if f, ok := path[i].(*ast.FuncDecl); ok { keepFunc = f break } } ch <- result{path, nil} } // and drop all function bodies that are not relevant so they don't get // type checked for _, decl := range file.Decls { if f, ok := decl.(*ast.FuncDecl); ok && f != keepFunc { f.Body = nil } } return file, err } cfg := &packages.Config{ Overlay: overlay, Mode: packages.LoadAllSyntax, ParseFile: parseFile, Tests: strings.HasSuffix(filename, "_test.go"), } pkgs, err := packages.Load(cfg, fmt.Sprintf("file=%s", filename)) if err != nil { return nil, nil, fmt.Errorf("cannot load package containing %s: %v", filename, err) } if len(pkgs) == 0 { return nil, nil, fmt.Errorf("no package containing file %s", filename) } // Arbitrarily return the first package if there are multiple. // TODO: should the user be able to specify which one? if len(pkgs) > 1 { log.Printf("packages not processed: %v\n", pkgs[1:]) } r := <-ch if r.err != nil { return nil, nil, err } return pkgs[0], r.nodes, nil } // Run is a wrapper for the gogetdoc command. It is broken out of main for easier testing. func Run(filename string, offset int, overlay map[string][]byte) (*Doc, error) { pkg, nodes, err := Load(filename, offset, overlay) if err != nil { return nil, err } return DocFromNodes(pkg, nodes) } // DocFromNodes gets the documentation from the AST node(s) in the specified package. func DocFromNodes(pkg *packages.Package, nodes []ast.Node) (*Doc, error) { for _, node := range nodes { // log.Printf("node is a %T\n", node) switch node := node.(type) { case *ast.ImportSpec: return PackageDoc(pkg, ImportPath(node)) case *ast.Ident: // if we can't find the object denoted by the identifier, keep searching) if obj := pkg.TypesInfo.ObjectOf(node); obj == nil { continue } return IdentDoc(node, pkg.TypesInfo, pkg) default: break } } return nil, errors.New("gogetdoc: no documentation found") } // parsePos parses the search position as provided on the command line. // It should be of the form: foo.go:#123 func parsePos(p string) (filename string, offset int, err error) { if p == "" { return "", 0, errors.New("missing required -pos flag") } sep := strings.LastIndex(p, ":") // need at least 2 characters after the ':' // (the # sign and the offset) if sep == -1 || sep > len(p)-2 || p[sep+1] != '#' { return "", 0, fmt.Errorf("invalid option: -pos=%s", p) } filename = p[:sep] off, err := strconv.ParseInt(p[sep+2:], 10, 32) return filename, int(off), err }
zmb3/gogetdoc
185
Gets documentation for items in Go source code.
Go
zmb3
Zac Bergquist
gravitational
main_test.go
Go
package main import ( "go/token" "os" "path/filepath" "runtime" "strconv" "strings" "testing" "golang.org/x/tools/go/packages" "golang.org/x/tools/go/packages/packagestest" ) func TestParseValidPos(t *testing.T) { fname, offset, err := parsePos("foo.go:#123") if fname != "foo.go" { t.Errorf("want foo.go, got %v", fname) } if offset != 123 { t.Errorf("want 123, got %v", 123) } if err != nil { t.Error(err) } } func TestParseEmptyPos(t *testing.T) { _, _, err := parsePos("") if err == nil { t.Error("expected error") } } func TestParseInvalidPos(t *testing.T) { for _, input := range []string{ "foo.go:123", "foo.go#123", "foo.go#:123", "123", "foo.go::123", "foo.go##123", "#:123", } { if _, _, err := parsePos(input); err == nil { t.Errorf("expected %v to be invalid", input) } } } func TestRunInvalidPos(t *testing.T) { dir := filepath.Join(".", "testdata", "package") mods := []packagestest.Module{ {Name: "somepkg", Files: packagestest.MustCopyFileTree(dir)}, } packagestest.TestAll(t, func(t *testing.T, exporter packagestest.Exporter) { if exporter == packagestest.Modules && !modulesSupported() { t.Skip("Skipping modules test on", runtime.Version()) } exported := packagestest.Export(t, exporter, mods) defer exported.Cleanup() teardown := setup(exported.Config) defer teardown() filename := exported.File("somepkg", "idents.go") _, err := Run(filename, 5000, nil) if err == nil { t.Fatal("expected invalid pos error") } }) } // github.com/zmb3/gogetdoc/issues/44 func TestInterfaceDecls(t *testing.T) { mods := []packagestest.Module{ { Name: "rabbit", Files: packagestest.MustCopyFileTree(filepath.Join(".", "testdata", "interface-decls")), }, } // TODO: convert to packagestest.TestAll exported := packagestest.Export(t, packagestest.GOPATH, mods) defer exported.Cleanup() teardown := setup(exported.Config) defer teardown() filename := exported.File("rabbit", "rabbit.go") if expectErr := exported.Expect(map[string]interface{}{ "decl": func(p token.Position, decl string) { doc, err := Run(filename, p.Offset, nil) if err != nil { t.Error(err) } if doc.Decl != decl { t.Errorf("bad decl, want %q, got %q", decl, doc.Decl) } }, }); expectErr != nil { t.Fatal(expectErr) } } func modulesSupported() bool { v := strings.TrimPrefix(runtime.Version(), "go") parts := strings.Split(v, ".") if len(parts) < 2 { return false } minor, err := strconv.Atoi(parts[1]) if err != nil { return false } return minor >= 11 } func setup(cfg *packages.Config) func() { originalDir, err := os.Getwd() if err != nil { panic(err) } err = os.Chdir(cfg.Dir) if err != nil { panic(err) } setEnv := func(env []string) { for _, assignment := range env { if i := strings.Index(assignment, "="); i > 0 { os.Setenv(assignment[:i], assignment[i+1:]) } } } originalEnv := os.Environ() setEnv(cfg.Env) os.Setenv("PWD", cfg.Dir) // https://go-review.googlesource.com/c/tools/+/143517/ return func() { os.Chdir(originalDir) setEnv(originalEnv) } } func TestIssue52(t *testing.T) { dir := filepath.Join(".", "testdata", "issue52") mods := []packagestest.Module{ {Name: "issue52", Files: packagestest.MustCopyFileTree(dir)}, } packagestest.TestAll(t, func(t *testing.T, exporter packagestest.Exporter) { if exporter == packagestest.Modules && !modulesSupported() { t.Skip("Skipping modules test on", runtime.Version()) } exported := packagestest.Export(t, exporter, mods) defer exported.Cleanup() teardown := setup(exported.Config) defer teardown() filename := exported.File("issue52", "main.go") for _, test := range []struct { Pos int Doc string }{ {64, "V this works\n"}, {66, "Foo this doesn't work but should\n"}, } { doc, err := Run(filename, test.Pos, nil) if err != nil { t.Fatalf("issue52, pos %d: %v", test.Pos, err) } if doc.Doc != test.Doc { t.Errorf("issue52, pos %d, invalid decl: want %q, got %q", test.Pos, test.Doc, doc.Doc) } } }) }
zmb3/gogetdoc
185
Gets documentation for items in Go source code.
Go
zmb3
Zac Bergquist
gravitational
modified_test.go
Go
package main import ( "fmt" "path/filepath" "runtime" "strings" "testing" "golang.org/x/tools/go/buildutil" "golang.org/x/tools/go/packages/packagestest" ) const contents = `package somepkg import "fmt" const ( Zero = iota One Two ) const Three = 3 func main() { fmt.Println(Zero, Three, Two, Three) } ` func TestModified(t *testing.T) { dir := filepath.Join(".", "testdata", "package") mods := []packagestest.Module{ {Name: "somepkg", Files: packagestest.MustCopyFileTree(dir)}, } packagestest.TestAll(t, func(t *testing.T, exporter packagestest.Exporter) { if exporter == packagestest.Modules && !modulesSupported() { t.Skip("Skipping modules test on", runtime.Version()) } exported := packagestest.Export(t, exporter, mods) defer exported.Cleanup() teardown := setup(exported.Config) defer teardown() path := exported.File("somepkg", "const.go") archive := fmt.Sprintf("%s\n%d\n%s", path, len(contents), contents) overlay, err := buildutil.ParseOverlayArchive(strings.NewReader(archive)) if err != nil { t.Fatalf("couldn't parse overlay: %v", err) } d, err := Run(path, 114, overlay) if err != nil { t.Fatal(err) } if n := d.Name; n != "Three" { t.Errorf("got const %s, want Three", n) } }) }
zmb3/gogetdoc
185
Gets documentation for items in Go source code.
Go
zmb3
Zac Bergquist
gravitational
pkg.go
Go
package main import ( "errors" "fmt" "go/ast" "go/doc" "golang.org/x/tools/go/packages" ) // ImportPath gets the import path from an ImportSpec. func ImportPath(is *ast.ImportSpec) string { s := is.Path.Value l := len(s) // trim the quotation marks return s[1 : l-1] } // PackageDoc gets the documentation for the package with the specified import // path and writes it to out. func PackageDoc(from *packages.Package, importPath string) (*Doc, error) { pkg := from.Imports[importPath] if pkg == nil { return nil, fmt.Errorf("package %s not in import map of packages %v", importPath, from) } if len(pkg.Syntax) == 0 { return nil, errors.New("no documentation found for " + pkg.Name) } fileMap := make(map[string]*ast.File) for _, file := range pkg.Syntax { fileMap[pkg.Fset.File(file.Pos()).Name()] = file } astPkg := &ast.Package{ Name: pkg.Name, Files: fileMap, } docPkg := doc.New(astPkg, importPath, 0) // TODO: we could also include package-level constants, vars, and functions (like the go doc command) return &Doc{ Name: pkg.Name, Decl: "package " + pkg.Name, Doc: docPkg.Doc, Import: importPath, Pkg: docPkg.Name, }, nil }
zmb3/gogetdoc
185
Gets documentation for items in Go source code.
Go
zmb3
Zac Bergquist
gravitational
pkg_test.go
Go
package main import ( "go/token" "path/filepath" "runtime" "strings" "testing" "golang.org/x/tools/go/packages/packagestest" ) func TestPackageDoc(t *testing.T) { dir := filepath.Join(".", "testdata", "package-doc") mods := []packagestest.Module{ {Name: "pkgdoc", Files: packagestest.MustCopyFileTree(dir)}, } packagestest.TestAll(t, func(t *testing.T, exporter packagestest.Exporter) { if exporter == packagestest.Modules && !modulesSupported() { t.Skip("Skipping modules test on", runtime.Version()) } exported := packagestest.Export(t, exporter, mods) defer exported.Cleanup() teardown := setup(exported.Config) defer teardown() filename := exported.File("pkgdoc", "main.go") if expectErr := exported.Expect(map[string]interface{}{ "pkgdoc": func(p token.Position, doc string) { d, err := Run(filename, p.Offset, nil) if err != nil { t.Error(err) } if !strings.HasPrefix(d.Doc, doc) { t.Errorf("expected %q, got %q", doc, d.Doc) } if !strings.HasPrefix(d.Decl, "package") { t.Errorf("expected %q to begin with 'package'", d.Decl) } }, }); expectErr != nil { t.Fatal(expectErr) } }) }
zmb3/gogetdoc
185
Gets documentation for items in Go source code.
Go
zmb3
Zac Bergquist
gravitational
testdata/interface-decls/rabbit.go
Go
package rabbit type Thing interface { Do(s Stuff) Stuff //@decl("Do", "func (Thing).Do(s Stuff) Stuff") DoWithError(s Stuff) (Stuff, error) //@decl("hError", "func (Thing).DoWithError(s Stuff) (Stuff, error)") DoWithNoArgs() //@decl("WithNoArgs", "func (Thing).DoWithNoArgs()") NamedReturns() (s string, err error) //@decl("medReturns", "func (Thing).NamedReturns() (s string, err error)") SameTypeParams(x, y string) //@decl("TypeParams", "func (Thing).SameTypeParams(x string, y string)") } type Stuff struct{} type ThingImplemented struct{} func (ti *ThingImplemented) Do(s Stuff) Stuff { //@decl("tuff", "type Stuff struct{}") return s }
zmb3/gogetdoc
185
Gets documentation for items in Go source code.
Go
zmb3
Zac Bergquist
gravitational
testdata/issue52/first/first.go
Go
package first import "issue52/first/second" //V this works var V second.T
zmb3/gogetdoc
185
Gets documentation for items in Go source code.
Go
zmb3
Zac Bergquist
gravitational
testdata/issue52/first/second/second.go
Go
package second type T struct{} //Foo this doesn't work but should func (t T) Foo() {}
zmb3/gogetdoc
185
Gets documentation for items in Go source code.
Go
zmb3
Zac Bergquist
gravitational
testdata/issue52/main.go
Go
package main import ( "issue52/first" ) func main() { first.V.Foo() }
zmb3/gogetdoc
185
Gets documentation for items in Go source code.
Go
zmb3
Zac Bergquist
gravitational
testdata/package-doc/main.go
Go
// LICENSE TEXT // Package main is an example package. package main // superfluous comment import ( "fmt" mth "math" //@pkgdoc("th", "Package math provides"), pkgdoc("ath", "Package math provides") ) func main() { fmt.Println(mth.IsNaN(1.23)) //@pkgdoc("th.IsNaN", "Package math provides") fmt.Println("Goodbye") //@pkgdoc("mt.", "\tPackage fmt implements formatted I/O") }
zmb3/gogetdoc
185
Gets documentation for items in Go source code.
Go
zmb3
Zac Bergquist
gravitational
testdata/package/const.go
Go
package somepkg import "fmt" const ( Zero = iota One Two ) const Three = 3 func main() { fmt.Println(Zero, One, Two, Three) //@const("Zero", "0"), const("One", "1"), const("Three", "3") }
zmb3/gogetdoc
185
Gets documentation for items in Go source code.
Go
zmb3
Zac Bergquist
gravitational
testdata/package/embed.go
Go
package somepkg // foo doc type foo struct { i int } type bar1 struct { foo //@doc("foo", "foo doc"), pkg("foo", "somepkg") f1 foo } type bar2 struct { *foo //@doc("foo", "foo doc"), pkg("foo", "somepkg") f1 *foo //@doc("foo", "foo doc"), pkg("foo", "somepkg") }
zmb3/gogetdoc
185
Gets documentation for items in Go source code.
Go
zmb3
Zac Bergquist
gravitational
testdata/package/idents.go
Go
package somepkg import ( "fmt" mth "math" ) type X struct{} // SayHello says hello. func (X) SayHello() { fmt.Println("Hello, World", mth.IsNaN(1.23)) //@doc("IsNaN", "IsNaN reports whether f") } func Baz() { var x X //@decl("X", "type X struct{}") x.SayHello() //@decl("ayHello", "func (X) SayHello()") SayGoodbye() //@doc("ayGood", "SayGoodbye says goodbye."), decl("ayGood", "func SayGoodbye() (string, error)") } // SayGoodbye says goodbye. func SayGoodbye() (string, error) { fmt.Println("Goodbye") fmt.Println(Message, fmt.Sprintf("The answer is %d", Answer)) //@const("Answer", "42"), doc("printf", "Sprintf formats according to a"), doc("Message", "Message is a message."), decl("Message", "var Message string") return "", nil } // Message is a message. var Message = "This is a test." // Answer is the answer to life the universe and everything. const Answer = 42 type Foo struct { // FieldA has doc FieldA string FieldB string // FieldB has a comment } func (f Foo) Print() { fmt.Println(f.FieldA, f.FieldB) //@doc("FieldA", "FieldA has doc"), doc("FieldB", "FieldB has a comment"), decl("FieldA", "field FieldA string") } var slice = []int{0, 1, 2} func addInt(i int) { slice = append(slice, i) //@doc("append", "The append built-in function appends elements") if f := float32(i); f > 42 { //@doc("loat32", "float32 is the set of all IEEE-754 32-bit") fmt.Println("foo") } } const ( A = iota //@doc("iota", "iota is a predeclared identifier representing the untyped integer ordinal") B C ) var slice2 = []*Foo{nil, nil, nil} //@doc("nil", "nil is a predeclared identifier representing the zero") func test() { c := make(chan int) if l := len(slice2); l > 0 { //@doc("len", "The len built-in function returns") c <- l } close(c) //@doc("close", "The close built-in function closes") } func test2() error { //@doc("rror", "The error built-in interface type is the conventional") return nil } var ( // Alpha doc Alpha = 0 //@decl("lpha", "var Alpha int") Bravo = 1 // Bravo comment Charlie = 2 Delta = Bravo //@doc("ravo", "Bravo comment"), decl("ravo", "var Bravo int") ) type HasUnexported struct { //@exported("Unexported") Visible string // Visible is an exported field notVisible string // notVisible is an unexported field } type NewString string var ns NewString //@decl("String", "type NewString string")
zmb3/gogetdoc
185
Gets documentation for items in Go source code.
Go
zmb3
Zac Bergquist
gravitational
testdata/package/issue20.go
Go
package somepkg import "fmt" // Foo is a test function. func Foo() { words := []string{} for _, word := range words { //@decl("rds", "var words []string") fmt.Println(word) } } func Bar() { tests := []struct { Name string args string }{ {"Test1", "a b c"}, {"Test2", "a b c"}, } for _, test := range tests { //@decl("tests", "var tests []struct{Name string; args string}") fmt.Println(test.Name) } }
zmb3/gogetdoc
185
Gets documentation for items in Go source code.
Go
zmb3
Zac Bergquist
gravitational
testdata/withvendor/main.go
Go
package main import ( "fmt" "github.com/zmb3/vp" //@import(".com", "github.com/zmb3/vp"), decl(".com", "package vp") ) func main() { vp.Hello() //@import("ello", "github.com/zmb3/vp"), doc("ello", "Hello says hello.\n") fmt.Println(vp.Foo) //@decl("Foo", "const Foo untyped string") }
zmb3/gogetdoc
185
Gets documentation for items in Go source code.
Go
zmb3
Zac Bergquist
gravitational
unexported.go
Go
package main import ( "fmt" "go/ast" "log" "unicode" "unicode/utf8" ) // Note: the code in this file is borrowed from the Go project. // It is licensed under a BSD-style license that is available // at https://golang.org/LICENSE. // // Copyright 2015 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. // trimUnexportedElems modifies spec in place to elide unexported fields from // structs and methods from interfaces (unless the unexported flag is set). func trimUnexportedElems(spec *ast.TypeSpec) { switch typ := spec.Type.(type) { case *ast.StructType: typ.Fields = trimUnexportedFields(typ.Fields, false) case *ast.InterfaceType: typ.Methods = trimUnexportedFields(typ.Methods, true) } } // trimUnexportedFields returns the field list trimmed of unexported fields. func trimUnexportedFields(fields *ast.FieldList, isInterface bool) *ast.FieldList { what := "methods" if !isInterface { what = "fields" } trimmed := false list := make([]*ast.Field, 0, len(fields.List)) for _, field := range fields.List { names := field.Names if len(names) == 0 { // Embedded type. Use the name of the type. It must be of type ident or *ident. // Nothing else is allowed. switch ident := field.Type.(type) { case *ast.Ident: if isInterface && ident.Name == "error" && ident.Obj == nil { // For documentation purposes, we consider the builtin error // type special when embedded in an interface, such that it // always gets shown publicly. list = append(list, field) continue } names = []*ast.Ident{ident} case *ast.StarExpr: // Must have the form *identifier. // This is only valid on embedded types in structs. if ident, ok := ident.X.(*ast.Ident); ok && !isInterface { names = []*ast.Ident{ident} } case *ast.SelectorExpr: // An embedded type may refer to a type in another package. names = []*ast.Ident{ident.Sel} } if names == nil { // Can only happen if AST is incorrect. Safe to continue with a nil list. log.Print("invalid program: unexpected type for embedded field") } } // Trims if any is unexported. Good enough in practice. ok := true for _, name := range names { if !isUpper(name.Name) { trimmed = true ok = false break } } if ok { list = append(list, field) } } if !trimmed { return fields } unexportedField := &ast.Field{ Type: &ast.Ident{ // Hack: printer will treat this as a field with a named type. // Setting Name and NamePos to ("", fields.Closing-1) ensures that // when Pos and End are called on this field, they return the // position right before closing '}' character. Name: "", NamePos: fields.Closing - 1, }, Comment: &ast.CommentGroup{ List: []*ast.Comment{{Text: fmt.Sprintf("// Has unexported %s.\n", what)}}, }, } return &ast.FieldList{ Opening: fields.Opening, List: append(list, unexportedField), Closing: fields.Closing, } } // isUpper reports whether the name starts with an upper case letter. func isUpper(name string) bool { ch, _ := utf8.DecodeRuneInString(name) return unicode.IsUpper(ch) }
zmb3/gogetdoc
185
Gets documentation for items in Go source code.
Go
zmb3
Zac Bergquist
gravitational
Hexdump.hpp
C++ Header
#ifndef HEXDUMP_HPP #define HEXDUMP_HPP #include <cctype> #include <iomanip> #include <ostream> template <unsigned RowSize, bool ShowAscii> struct CustomHexdump { CustomHexdump(const void* data, unsigned length) : mData(static_cast<const unsigned char*>(data)), mLength(length) { } const unsigned char* mData; const unsigned mLength; }; template <unsigned RowSize, bool ShowAscii> std::ostream& operator<<(std::ostream& out, const CustomHexdump<RowSize, ShowAscii>& dump) { out.fill('0'); for (int i = 0; i < dump.mLength; i += RowSize) { out << "0x" << std::setw(6) << std::hex << i << ": "; for (int j = 0; j < RowSize; ++j) { if (i + j < dump.mLength) { out << std::hex << std::setw(2) << static_cast<int>(dump.mData[i + j]) << " "; } else { out << " "; } } out << " "; if (ShowAscii) { for (int j = 0; j < RowSize; ++j) { if (i + j < dump.mLength) { if (std::isprint(dump.mData[i + j])) { out << static_cast<char>(dump.mData[i + j]); } else { out << "."; } } } } out << std::endl; } return out; } typedef CustomHexdump<16, true> Hexdump; #endif // HEXDUMP_HPP
zmb3/hexdump
63
A header-only utility for writing hexdump-formatted data to C++ streams.
C++
zmb3
Zac Bergquist
gravitational
example.cpp
C++
#include "Hexdump.hpp" #include <iostream> int main() { unsigned char data[150]; unsigned char c = 0; for (auto& val : data) { val = c++; } std::cout << Hexdump(data, sizeof(data)) << std::endl; std::cout << CustomHexdump<8, true>(data, sizeof(data)) << std::endl; std::cout << CustomHexdump<32, false>(data, sizeof(data)) << std::endl; }
zmb3/hexdump
63
A header-only utility for writing hexdump-formatted data to C++ streams.
C++
zmb3
Zac Bergquist
gravitational
cmd/client/client.go
Go
// Command client is used to test the behavior of a TCP // load balancer. It assumes that the load balancer fronts // one or more TCP echo servers, like the ones found in // commmand upstreams. package main import ( "bytes" "crypto/tls" "crypto/x509" "errors" "flag" "fmt" "log" "math/rand" "net" "os" "strconv" ) func main() { port := flag.Int("p", 0, "port to connect to") cert := flag.String("cert", "", "path to client certificate (leave blank to disable TLS)") key := flag.String("key", "", "path to private key (leave blank to disable TLS)") ca := flag.String("ca", "", "path to load balancer's certificate authority") oneshot := flag.Bool("oneshot", false, "make a single connection and verify that the output is correct") // TODO: // number of worker routines // timing info (hold connections open longer) flag.Parse() if *port == 0 { log.Fatal("missing required port argument") } hasCert := len(*cert) > 0 hasKey := len(*key) > 0 if hasCert != hasKey { log.Fatal("to enable TLS, specify both -cert and -key") } if *oneshot { if err := runOnce(*port, *cert, *key, *ca); err != nil { log.Fatal(err) } return } // TODO: run a bunch of times.. } func dial(port int, cert, key, ca string) (conn net.Conn, err error) { useTLS := len(cert) > 0 && len(key) > 0 if useTLS { tlsCert, err := tls.LoadX509KeyPair(cert, key) if err != nil { return nil, err } var pool *x509.CertPool if len(ca) > 0 { caCert, err := os.ReadFile(ca) if err != nil { return nil, err } pool = x509.NewCertPool() pool.AppendCertsFromPEM(caCert) } else { pool, err = x509.SystemCertPool() if err != nil { return nil, err } } cfg := &tls.Config{ RootCAs: pool, Certificates: []tls.Certificate{tlsCert}, } tconn, err := tls.Dial("tcp", "127.0.0.1:"+strconv.Itoa(port), cfg) if err != nil { return nil, err } return tconn, nil } conn, err = net.Dial("tcp", "127.0.0.1:"+strconv.Itoa(port)) if err != nil { return nil, err } return conn, nil } // runOnce writes a random number of arbitrary data to the // specified TCP port and verifies that the same data is // echoed back func runOnce(port int, cert, key, ca string) error { conn, err := dial(port, cert, key, ca) if err != nil { return err } defer conn.Close() data := make([]byte, 128+rand.Intn(1024)) rand.Read(data) n, err := conn.Write(data) if err != nil { return err } if n != len(data) { return fmt.Errorf("could not write all %d bytes", len(data)) } recv := make([]byte, n) if _, err := conn.Read(recv); err != nil { return err } if !bytes.Equal(data, recv) { return errors.New("data did not match") } return nil }
zmb3/lbtest
0
Go
zmb3
Zac Bergquist
gravitational
cmd/upstreams/upstreams.go
Go
// Command upstreams runs one or more "upstreams" that // can sit behind a load balancer, and tracks the number // connections each has received. package main import ( "context" "flag" "fmt" "io" "log" "net" "os" "os/signal" "sync/atomic" ) func main() { count := flag.Int("n", 1, "the number of upstreams to run") startPort := flag.Int("p", 8888, "the port for the first upstream to use") flag.Parse() ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt) defer cancel() upstreams := make([]echoUpstream, *count) for i := 0; i < *count; i++ { upstreams[i] = echoUpstream{ port: *startPort + i, } ii := i go upstreams[ii].run(ctx) } // TODO: add signal to print current number of connections per upstream fmt.Printf("running %d listeners starting at port %d...\n", *count, *startPort) fmt.Printf("press ctrl-c to quit and print stats\n") <-ctx.Done() fmt.Println() for i := range upstreams { fmt.Printf("Upstream %d: served %d total connections\n", i, atomic.LoadInt64(&upstreams[i].count)) } } // echoUpstream listens on a particular port and echos all input // back to the client type echoUpstream struct { count int64 port int l *net.TCPListener } func (e *echoUpstream) run(ctx context.Context) error { l, err := net.Listen("tcp", fmt.Sprintf(":%d", e.port)) if err != nil { return err } defer l.Close() go func() { <-ctx.Done() l.Close() }() for { conn, err := l.Accept() if err != nil { return err } atomic.AddInt64(&e.count, 1) go func() { defer conn.Close() if _, err := io.Copy(conn, conn); err != nil && err != io.EOF { log.Fatal(err) } }() } }
zmb3/lbtest
0
Go
zmb3
Zac Bergquist
gravitational
album.go
Go
package spotify import ( "context" "errors" "fmt" "strconv" "strings" "time" ) // SimpleAlbum contains basic data about an album. type SimpleAlbum struct { // The name of the album. Name string `json:"name"` // A slice of [SimpleArtist]. Artists []SimpleArtist `json:"artists"` // The field is present when getting an artist’s // albums. Possible values are “album”, “single”, // “compilation”, “appears_on”. Compare to album_type // this field represents relationship between the artist // and the album. AlbumGroup string `json:"album_group"` // The type of the album: one of "album", // "single", or "compilation". AlbumType string `json:"album_type"` // The [Spotify ID] for the album. // // [Spotify ID]: https://developer.spotify.com/documentation/web-api/concepts/spotify-uris-ids ID ID `json:"id"` // The [Spotify URI] for the album. // // [Spotify URI]: https://developer.spotify.com/documentation/web-api/concepts/spotify-uris-ids URI URI `json:"uri"` // The markets in which the album is available, identified using // [ISO 3166-1 alpha-2] country codes. Note that an album is considered // available in a market when at least 1 of its tracks is available in that // market. // // [ISO 3166-1 alpha-2]: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 AvailableMarkets []string `json:"available_markets"` // A link to the Web API endpoint providing full // details of the album. Endpoint string `json:"href"` // The cover art for the album in various sizes, // widest first. Images []Image `json:"images"` // Known external URLs for this album. ExternalURLs map[string]string `json:"external_urls"` // The date the album was first released. For example, "1981-12-15". // Depending on the ReleaseDatePrecision, it might be shown as // "1981" or "1981-12". You can use [SimpleAlbum.ReleaseDateTime] to convert // this to a [time.Time] value. ReleaseDate string `json:"release_date"` // The precision with which ReleaseDate value is known: "year", "month", or "day" ReleaseDatePrecision string `json:"release_date_precision"` // The number of tracks on the album. TotalTracks Numeric `json:"total_tracks"` } // ReleaseDateTime converts [SimpleAlbum.ReleaseDate] to a [time.Time]. // All of the fields in the result may not be valid. For example, if // [SimpleAlbum.ReleaseDatePrecision] is "month", then only the month and year // (but not the day) of the result are valid. func (s *SimpleAlbum) ReleaseDateTime() time.Time { if s.ReleaseDatePrecision == "day" { result, _ := time.Parse(DateLayout, s.ReleaseDate) return result } if s.ReleaseDatePrecision == "month" { ym := strings.Split(s.ReleaseDate, "-") year, _ := strconv.Atoi(ym[0]) month, _ := strconv.Atoi(ym[1]) return time.Date(year, time.Month(month), 1, 0, 0, 0, 0, time.UTC) } year, _ := strconv.Atoi(s.ReleaseDate) return time.Date(year, 1, 1, 0, 0, 0, 0, time.UTC) } // Copyright contains the copyright statement associated with an album. type Copyright struct { // The copyright text for the album. Text string `json:"text"` // The type of copyright. Type string `json:"type"` } // FullAlbum provides extra album data in addition to the data provided by [SimpleAlbum]. type FullAlbum struct { SimpleAlbum Copyrights []Copyright `json:"copyrights"` Genres []string `json:"genres"` // The popularity of the album, represented as an integer between 0 and 100, // with 100 being the most popular. Popularity of an album is calculated // from the popularity of the album's individual tracks. Popularity Numeric `json:"popularity"` Tracks SimpleTrackPage `json:"tracks"` ExternalIDs map[string]string `json:"external_ids"` } // SavedAlbum provides info about an album saved to a user's account. type SavedAlbum struct { // The date and time the track was saved, represented as an ISO // 8601 UTC timestamp with a zero offset (YYYY-MM-DDTHH:MM:SSZ). // You can use [TimestampLayout] to convert this to a [time.Time] value. AddedAt string `json:"added_at"` FullAlbum `json:"album"` } // GetAlbum gets Spotify catalog information for a single album, given its // [Spotify ID]. Supported options: [Market]. // // [Spotify ID]: https://developer.spotify.com/documentation/web-api/concepts/spotify-uris-ids func (c *Client) GetAlbum(ctx context.Context, id ID, opts ...RequestOption) (*FullAlbum, error) { spotifyURL := fmt.Sprintf("%salbums/%s", c.baseURL, id) if params := processOptions(opts...).urlParams.Encode(); params != "" { spotifyURL += "?" + params } var a FullAlbum err := c.get(ctx, spotifyURL, &a) if err != nil { return nil, err } return &a, nil } func toStringSlice(ids []ID) []string { result := make([]string, len(ids)) for i, str := range ids { result[i] = str.String() } return result } // GetAlbums gets Spotify Catalog information for [multiple albums], given their // [Spotify ID]s. It supports up to 20 IDs in a single call. Albums are returned // in the order requested. If an album is not found, that position in the // result slice will be nil. // // Supported options: [Market]. // // [multiple albums]: https://developer.spotify.com/documentation/web-api/reference/get-multiple-albums // [Spotify ID]: https://developer.spotify.com/documentation/web-api/concepts/spotify-uris-ids func (c *Client) GetAlbums(ctx context.Context, ids []ID, opts ...RequestOption) ([]*FullAlbum, error) { if len(ids) > 20 { return nil, errors.New("spotify: exceeded maximum number of albums") } params := processOptions(opts...).urlParams params.Set("ids", strings.Join(toStringSlice(ids), ",")) spotifyURL := fmt.Sprintf("%salbums?%s", c.baseURL, params.Encode()) var a struct { Albums []*FullAlbum `json:"albums"` } err := c.get(ctx, spotifyURL, &a) if err != nil { return nil, err } return a.Albums, nil } // AlbumType represents the type of an album. It can be used to filter // results when searching for albums. type AlbumType int // AlbumType values that can be used to filter which types of albums are // searched for. These are flags that can be bitwise OR'd together // to search for multiple types of albums simultaneously. const ( AlbumTypeAlbum AlbumType = 1 << iota AlbumTypeSingle AlbumTypeAppearsOn AlbumTypeCompilation ) func (at AlbumType) encode() string { types := []string{} if at&AlbumTypeAlbum != 0 { types = append(types, "album") } if at&AlbumTypeSingle != 0 { types = append(types, "single") } if at&AlbumTypeAppearsOn != 0 { types = append(types, "appears_on") } if at&AlbumTypeCompilation != 0 { types = append(types, "compilation") } return strings.Join(types, ",") } // GetAlbumTracks gets the [tracks] for a particular album. // If you only care about the tracks, this call is more efficient // than [GetAlbum]. // // Supported Options: [Market], [Limit], [Offset]. // // [tracks]: https://developer.spotify.com/documentation/web-api/reference/get-an-albums-tracks func (c *Client) GetAlbumTracks(ctx context.Context, id ID, opts ...RequestOption) (*SimpleTrackPage, error) { spotifyURL := fmt.Sprintf("%salbums/%s/tracks", c.baseURL, id) if params := processOptions(opts...).urlParams.Encode(); params != "" { spotifyURL += "?" + params } var result SimpleTrackPage err := c.get(ctx, spotifyURL, &result) if err != nil { return nil, err } return &result, nil }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
album_test.go
Go
package spotify import ( "context" "net/http" "testing" ) // The example from https://developer.spotify.com/web-api/get-album/ func TestFindAlbum(t *testing.T) { client, server := testClientFile(http.StatusOK, "test_data/find_album.txt") defer server.Close() album, err := client.GetAlbum(context.Background(), ID("0sNOF9WDwhWunNAHPD3Baj")) if err != nil { t.Fatal(err) } if album == nil { t.Fatal("Got nil album") } if album.Name != "She's So Unusual" { t.Error("Got wrong album") } released := album.ReleaseDateTime() if released.Year() != 1983 { t.Errorf("Expected release date 1983, got %d\n", released.Year()) } } func TestFindAlbumBadID(t *testing.T) { client, server := testClientString(http.StatusNotFound, `{ "error": { "status": 404, "message": "non existing id" } }`) defer server.Close() album, err := client.GetAlbum(context.Background(), ID("asdf")) if album != nil { t.Fatal("Expected nil album, got", album.Name) } se, ok := err.(Error) if !ok { t.Error("Expected spotify error, got", err) } if se.Status != 404 { t.Errorf("Expected HTTP 404, got %d. ", se.Status) } if se.Message != "non existing id" { t.Error("Unexpected error message: ", se.Message) } } // The example from https://developer.spotify.com/web-api/get-several-albums/ func TestFindAlbums(t *testing.T) { client, server := testClientFile(http.StatusOK, "test_data/find_albums.txt") defer server.Close() res, err := client.GetAlbums(context.Background(), []ID{"41MnTivkwTO3UUJ8DrqEJJ", "6JWc4iAiJ9FjyK0B59ABb4", "6UXCm6bOO4gFlDQZV5yL37", "0X8vBD8h1Ga9eLT8jx9VCC"}) if err != nil { t.Fatal(err) } if len(res) != 4 { t.Fatalf("Expected 4 albums, got %d", len(res)) } expectedAlbums := []string{ "The Best Of Keane (Deluxe Edition)", "Strangeland", "Night Train", "Mirrored", } for i, name := range expectedAlbums { if res[i].Name != name { t.Error("Expected album", name, "but got", res[i].Name) } } release := res[0].ReleaseDateTime() if release.Year() != 2013 || release.Month() != 11 || release.Day() != 8 { t.Errorf("Expected release 2013-11-08, got %d-%02d-%02d\n", release.Year(), release.Month(), release.Day()) } releaseMonthPrecision := res[3].ReleaseDateTime() if releaseMonthPrecision.Year() != 2007 || releaseMonthPrecision.Month() != 3 || releaseMonthPrecision.Day() != 1 { t.Errorf("Expected release 2007-03-01, got %d-%02d-%02d\n", releaseMonthPrecision.Year(), releaseMonthPrecision.Month(), releaseMonthPrecision.Day()) } } func TestFindAlbumTracks(t *testing.T) { client, server := testClientFile(http.StatusOK, "test_data/find_album_tracks.txt") defer server.Close() res, err := client.GetAlbumTracks(context.Background(), ID("0sNOF9WDwhWunNAHPD3Baj"), Limit(1)) if err != nil { t.Fatal(err) } if res.Total != 13 { t.Fatal("Got", res.Total, "results, want 13") } if len(res.Tracks) == 1 { if res.Tracks[0].Name != "Money Changes Everything" { t.Error("Expected track 'Money Changes Everything', got", res.Tracks[0].Name) } } else { t.Error("Expected 1 track, got", len(res.Tracks)) } }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
artist.go
Go
package spotify import ( "context" "fmt" "strings" ) // SimpleArtist contains basic info about an artist. type SimpleArtist struct { Name string `json:"name"` ID ID `json:"id"` // The Spotify URI for the artist. URI URI `json:"uri"` // A link to the Web API endpoint providing full details of the artist. Endpoint string `json:"href"` ExternalURLs map[string]string `json:"external_urls"` } // FullArtist provides extra artist data in addition to what is provided by [SimpleArtist]. type FullArtist struct { SimpleArtist // The popularity of the artist, expressed as an integer between 0 and 100. // The artist's popularity is calculated from the popularity of the artist's tracks. Popularity Numeric `json:"popularity"` // A list of genres the artist is associated with. For example, "Prog Rock" // or "Post-Grunge". If not yet classified, the slice is empty. Genres []string `json:"genres"` Followers Followers `json:"followers"` // Images of the artist in various sizes, widest first. Images []Image `json:"images"` } // GetArtist gets Spotify catalog information for a single artist, given its Spotify ID. func (c *Client) GetArtist(ctx context.Context, id ID) (*FullArtist, error) { spotifyURL := fmt.Sprintf("%sartists/%s", c.baseURL, id) var a FullArtist err := c.get(ctx, spotifyURL, &a) if err != nil { return nil, err } return &a, nil } // GetArtists gets spotify catalog information for several artists based on their // Spotify IDs. It supports up to 50 artists in a single call. Artists are // returned in the order requested. If an artist is not found, that position // in the result will be nil. Duplicate IDs will result in duplicate artists // in the result. func (c *Client) GetArtists(ctx context.Context, ids ...ID) ([]*FullArtist, error) { spotifyURL := fmt.Sprintf("%sartists?ids=%s", c.baseURL, strings.Join(toStringSlice(ids), ",")) var a struct { Artists []*FullArtist } err := c.get(ctx, spotifyURL, &a) if err != nil { return nil, err } return a.Artists, nil } // GetArtistsTopTracks gets Spotify catalog information about an artist's top // tracks in a particular country. It returns a maximum of 10 tracks. The // country is specified as an [ISO 3166-1 alpha-2] country code. // // [ISO 3166-1 alpha-2]: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 func (c *Client) GetArtistsTopTracks(ctx context.Context, artistID ID, country string) ([]FullTrack, error) { spotifyURL := fmt.Sprintf("%sartists/%s/top-tracks?country=%s", c.baseURL, artistID, country) var t struct { Tracks []FullTrack `json:"tracks"` } err := c.get(ctx, spotifyURL, &t) if err != nil { return nil, err } return t.Tracks, nil } // GetRelatedArtists gets Spotify catalog information about artists similar to a // given artist. Similarity is based on analysis of the Spotify community's // listening history. This function returns up to 20 artists that are considered // related to the specified artist. func (c *Client) GetRelatedArtists(ctx context.Context, id ID) ([]FullArtist, error) { spotifyURL := fmt.Sprintf("%sartists/%s/related-artists", c.baseURL, id) var a struct { Artists []FullArtist `json:"artists"` } err := c.get(ctx, spotifyURL, &a) if err != nil { return nil, err } return a.Artists, nil } // GetArtistAlbums gets Spotify catalog information about an artist's albums. // It is equivalent to GetArtistAlbumsOpt(artistID, nil). // // The AlbumType argument can be used to find a particular types of album. // If the Market is not specified, Spotify will likely return a lot // of duplicates (one for each market in which the album is available // // Supported options: [Market]. func (c *Client) GetArtistAlbums(ctx context.Context, artistID ID, ts []AlbumType, opts ...RequestOption) (*SimpleAlbumPage, error) { spotifyURL := fmt.Sprintf("%sartists/%s/albums", c.baseURL, artistID) // add optional query string if options were specified values := processOptions(opts...).urlParams if ts != nil { types := make([]string, len(ts)) for i := range ts { types[i] = ts[i].encode() } values.Set("include_groups", strings.Join(types, ",")) } if query := values.Encode(); query != "" { spotifyURL += "?" + query } var p SimpleAlbumPage err := c.get(ctx, spotifyURL, &p) if err != nil { return nil, err } return &p, nil }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
artist_test.go
Go
// Copyright 2014, 2015 Zac Bergquist // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package spotify import ( "context" "net/http" "testing" ) const albumsResponse = ` { "href" : "https://api.spotify.com/v1/artists/1vCWHaC5f2uS3yhpwWbIA6/albums?offset=0&limit=2&album_type=single", "items" : [ { "album_type" : "single", "available_markets" : [ "AD", "AR", "AT", "AU", "BE", "BG", "BO", "BR", "CH", "CL", "CO", "CR", "CY", "CZ", "DE", "DK", "DO", "EC", "EE", "ES", "FI", "FR", "GR", "GT", "HK", "HN", "HU", "IE", "IS", "IT", "LI", "LT", "LU", "LV", "MC", "MT", "MY", "NI", "NL", "NO", "NZ", "PA", "PE", "PH", "PL", "PT", "PY", "RO", "SE", "SG", "SI", "SK", "SV", "TR", "TW", "UY" ], "external_urls" : { "spotify" : "https://open.spotify.com/album/3ckwyt0bTOcDbXovWbweMp" }, "href" : "https://api.spotify.com/v1/albums/3ckwyt0bTOcDbXovWbweMp", "id" : "3ckwyt0bTOcDbXovWbweMp", "images" : [ { "height" : 640, "url" : "https://i.scdn.co/image/144ac57ad073741e99b5243c59abebe1500ada0a", "width" : 640 }, { "height" : 300, "url" : "https://i.scdn.co/image/4680e5f3af02219fd9e79ce432c1b18f97af6426", "width" : 300 }, { "height" : 64, "url" : "https://i.scdn.co/image/8c803d6cb612b6f2b37a7276deb2ff05f5a77097", "width" : 64 } ], "name" : "The Days / Nights", "type" : "album", "uri" : "spotify:album:3ckwyt0bTOcDbXovWbweMp" }, { "album_type" : "single", "available_markets" : [ "CA", "MX", "US" ], "external_urls" : { "spotify" : "https://open.spotify.com/album/1WXM7DYQRT7QX8AKBJRfK9" }, "href" : "https://api.spotify.com/v1/albums/1WXM7DYQRT7QX8AKBJRfK9", "id" : "1WXM7DYQRT7QX8AKBJRfK9", "images" : [ { "height" : 640.0, "url" : "https://i.scdn.co/image/590dbe5504d2898c120b942bee2b699404783896", "width" : 640.0 }, { "height" : 300.0, "url" : "https://i.scdn.co/image/9a4db24b1930e8683b4dfd19c7bd2a40672c6718", "width" : 300.0 }, { "height" : 64.0, "url" : "https://i.scdn.co/image/d5cfc167e03ed328ae7dfa9b56d3628d81b6831b", "width" : 64.0 } ], "name" : "The Days / Nights", "type" : "album", "uri" : "spotify:album:1WXM7DYQRT7QX8AKBJRfK9" } ], "limit" : 2, "next" : "https://api.spotify.com/v1/artists/1vCWHaC5f2uS3yhpwWbIA6/albums?offset=2&limit=2&album_type=single", "offset" : 0, "previous" : null, "total" : 157 }` func TestFindArtist(t *testing.T) { client, server := testClientFile(http.StatusOK, "test_data/find_artist.txt") defer server.Close() artist, err := client.GetArtist(context.Background(), ID("0TnOYISbd1XYRBk9myaseg")) if err != nil { t.Fatal(err) } if followers := artist.Followers.Count; followers != 2265279 { t.Errorf("Got %d followers, want 2265279\n", followers) } if artist.Name != "Pitbull" { t.Error("Got ", artist.Name, ", wanted Pitbull") } } func TestArtistTopTracks(t *testing.T) { client, server := testClientFile(http.StatusOK, "test_data/artist_top_tracks.txt") defer server.Close() tracks, err := client.GetArtistsTopTracks(context.Background(), ID("43ZHCT0cAZBISjO8DG9PnE"), "SE") if err != nil { t.Fatal(err) } if l := len(tracks); l != 10 { t.Fatalf("Got %d tracks, expected 10\n", l) } track := tracks[9] if track.Name != "(You're The) Devil in Disguise" { t.Error("Incorrect track name") } if track.TrackNumber != 24 { t.Errorf("Track number was %d, expected 24\n", track.TrackNumber) } } func TestRelatedArtists(t *testing.T) { client, server := testClientFile(http.StatusOK, "test_data/related_artists.txt") defer server.Close() artists, err := client.GetRelatedArtists(context.Background(), ID("43ZHCT0cAZBISjO8DG9PnE")) if err != nil { t.Fatal(err) } if count := len(artists); count != 20 { t.Fatalf("Got %d artists, wanted 20\n", count) } a2 := artists[2] if a2.Name != "Carl Perkins" { t.Error("Expected Carl Perkins, got ", a2.Name) } if a2.Popularity != 54 { t.Errorf("Expected popularity 54, got %d\n", a2.Popularity) } } func TestRelatedArtistsWithFloats(t *testing.T) { client, server := testClientFile(http.StatusOK, "test_data/related_artists_with_floats.txt") defer server.Close() artists, err := client.GetRelatedArtists(context.Background(), ID("43ZHCT0cAZBISjO8DG9PnE")) if err != nil { t.Fatal(err) } if count := len(artists); count != 20 { t.Fatalf("Got %d artists, wanted 20\n", count) } a2 := artists[2] if a2.Name != "Carl Perkins" { t.Error("Expected Carl Perkins, got ", a2.Name) } if a2.Popularity != 54 { t.Errorf("Expected popularity 54, got %d\n", a2.Popularity) } } func TestArtistAlbumsFiltered(t *testing.T) { client, server := testClientString(http.StatusOK, albumsResponse) defer server.Close() albums, err := client.GetArtistAlbums(context.Background(), "1vCWHaC5f2uS3yhpwWbIA6", []AlbumType{AlbumTypeSingle}, Limit(2)) if err != nil { t.Fatal(err) } if albums == nil { t.Fatal("Result is nil") } // since we didn't specify a country, we got duplicate albums // (the album has a different ID in different regions) if l := len(albums.Albums); l != 2 { t.Fatalf("Expected 2 albums, got %d\n", l) } if albums.Albums[0].Name != "The Days / Nights" { t.Error("Expected 'The Days / Nights', got ", albums.Albums[0].Name) } url := "https://open.spotify.com/album/3ckwyt0bTOcDbXovWbweMp" spotifyURL, ok := albums.Albums[0].ExternalURLs["spotify"] if !ok { t.Error("Missing Spotify external URL") } if spotifyURL != url { t.Errorf("Wrong Spotify external URL: want %s, got %s\n", url, spotifyURL) } }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
audio_analysis.go
Go
package spotify import ( "context" "fmt" ) // AudioAnalysis contains a [detailed audio analysis] for a single track // identified by its unique [Spotify ID]. // // [detailed audio analysis]: https://developer.spotify.com/documentation/web-api/reference/get-audio-analysis // [Spotify ID]: https://developer.spotify.com/documentation/web-api/#spotify-uris-and-ids type AudioAnalysis struct { Bars []Marker `json:"bars"` Beats []Marker `json:"beats"` Meta AnalysisMeta `json:"meta"` Sections []Section `json:"sections"` Segments []Segment `json:"segments"` Tatums []Marker `json:"tatums"` Track AnalysisTrack `json:"track"` } // Marker represents beats, bars, tatums and are used in segment and section // descriptions. type Marker struct { Start float64 `json:"start"` Duration float64 `json:"duration"` Confidence float64 `json:"confidence"` } // AnalysisMeta describes details about Spotify's audio analysis of the track type AnalysisMeta struct { AnalyzerVersion string `json:"analyzer_version"` Platform string `json:"platform"` DetailedStatus string `json:"detailed_status"` StatusCode int `json:"status"` Timestamp int64 `json:"timestamp"` AnalysisTime float64 `json:"analysis_time"` InputProcess string `json:"input_process"` } // Section represents a large variation in rhythm or timbre, e.g. chorus, verse, // bridge, guitar solo, etc. Each section contains its own descriptions of // tempo, key, mode, time_signature, and loudness. type Section struct { Marker Loudness float64 `json:"loudness"` Tempo float64 `json:"tempo"` TempoConfidence float64 `json:"tempo_confidence"` Key Key `json:"key"` KeyConfidence float64 `json:"key_confidence"` Mode Mode `json:"mode"` ModeConfidence float64 `json:"mode_confidence"` TimeSignature Numeric `json:"time_signature"` TimeSignatureConfidence float64 `json:"time_signature_confidence"` } // Segment is characterized by it's perceptual onset and duration in seconds, // loudness (dB), pitch and timbral content. type Segment struct { Marker LoudnessStart float64 `json:"loudness_start"` LoudnessMaxTime float64 `json:"loudness_max_time"` LoudnessMax float64 `json:"loudness_max"` LoudnessEnd float64 `json:"loudness_end"` Pitches []float64 `json:"pitches"` Timbre []float64 `json:"timbre"` } // AnalysisTrack contains audio analysis data about the track as a whole type AnalysisTrack struct { NumSamples int64 `json:"num_samples"` Duration float64 `json:"duration"` SampleMD5 string `json:"sample_md5"` OffsetSeconds Numeric `json:"offset_seconds"` WindowSeconds Numeric `json:"window_seconds"` AnalysisSampleRate int64 `json:"analysis_sample_rate"` AnalysisChannels Numeric `json:"analysis_channels"` EndOfFadeIn float64 `json:"end_of_fade_in"` StartOfFadeOut float64 `json:"start_of_fade_out"` Loudness float64 `json:"loudness"` Tempo float64 `json:"tempo"` TempoConfidence float64 `json:"tempo_confidence"` TimeSignature Numeric `json:"time_signature"` TimeSignatureConfidence float64 `json:"time_signature_confidence"` Key Key `json:"key"` KeyConfidence float64 `json:"key_confidence"` Mode Mode `json:"mode"` ModeConfidence float64 `json:"mode_confidence"` CodeString string `json:"codestring"` CodeVersion float64 `json:"code_version"` EchoprintString string `json:"echoprintstring"` EchoprintVersion float64 `json:"echoprint_version"` SynchString string `json:"synchstring"` SynchVersion float64 `json:"synch_version"` RhythmString string `json:"rhythmstring"` RhythmVersion float64 `json:"rhythm_version"` } // GetAudioAnalysis queries the Spotify web API for an [audio analysis] of a // single track. // // [audio analysis]: https://developer.spotify.com/documentation/web-api/reference/get-audio-analysis func (c *Client) GetAudioAnalysis(ctx context.Context, id ID) (*AudioAnalysis, error) { url := fmt.Sprintf("%saudio-analysis/%s", c.baseURL, id) temp := AudioAnalysis{} err := c.get(ctx, url, &temp) if err != nil { return nil, err } return &temp, nil }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
audio_analysis_test.go
Go
package spotify import ( "context" "net/http" "reflect" "testing" ) const fieldsDifferTemplate = "Actual response is not the same as expected response on field %s" var expected = AudioAnalysis{ Bars: []Marker{ { Start: 251.98282, Duration: 0.29765, Confidence: 0.652, }, }, Beats: []Marker{ { Start: 251.98282, Duration: 0.29765, Confidence: 0.652, }, }, Meta: AnalysisMeta{ AnalyzerVersion: "4.0.0", Platform: "Linux", DetailedStatus: "OK", StatusCode: 0, Timestamp: 1456010389, AnalysisTime: 9.1394, InputProcess: "libvorbisfile L+R 44100->22050", }, Sections: []Section{ { Marker: Marker{ Start: 237.02356, Duration: 18.32542, Confidence: 1, }, Loudness: -20.074, Tempo: 98.253, TempoConfidence: 0.767, Key: 5, KeyConfidence: 0.327, Mode: 1, ModeConfidence: 0.566, TimeSignature: 4, TimeSignatureConfidence: 1, }, }, Segments: []Segment{ { Marker: Marker{ Start: 252.15601, Duration: 3.19297, Confidence: 0.522, }, LoudnessStart: -23.356, LoudnessMaxTime: 0.06971, LoudnessMax: -18.121, LoudnessEnd: -60, Pitches: []float64{0.709, 0.092, 0.196, 0.084, 0.352, 0.134, 0.161, 1, 0.17, 0.161, 0.211, 0.15}, Timbre: []float64{23.312, -7.374, -45.719, 294.874, 51.869, -79.384, -89.048, 143.322, -4.676, -51.303, -33.274, -19.037}, }, }, Tatums: []Marker{ { Start: 251.98282, Duration: 0.29765, Confidence: 0.652, }, }, Track: AnalysisTrack{ NumSamples: 100, Duration: 255.34898, SampleMD5: "", OffsetSeconds: 0, WindowSeconds: 0, AnalysisSampleRate: 22050, AnalysisChannels: 1, EndOfFadeIn: 0, StartOfFadeOut: 251.73333, Loudness: -11.84, Tempo: 98.002, TempoConfidence: 0.423, TimeSignature: 4, TimeSignatureConfidence: 1, Key: 5, KeyConfidence: 0.36, Mode: 0, ModeConfidence: 0.414, CodeString: "eJxVnAmS5DgOBL-ST-B9_P9j4x7M6qoxW9tpsZQSCeI...", CodeVersion: 3.15, EchoprintString: "eJzlvQmSHDmStHslxw4cB-v9j_A-tahhVKV0IH9...", EchoprintVersion: 4.12, SynchString: "eJx1mIlx7ToORFNRCCK455_YoE9Dtt-vmrKsK3EBsTY...", SynchVersion: 1, RhythmString: "eJyNXAmOLT2r28pZQuZh_xv7g21Iqu_3pCd160xV...", RhythmVersion: 1, }, } func TestAudioAnalysis(t *testing.T) { c, s := testClientFile(http.StatusOK, "test_data/get_audio_analysis.txt") defer s.Close() analysis, err := c.GetAudioAnalysis(context.Background(), "foo") if err != nil { t.Error(err) } if !reflect.DeepEqual(analysis.Bars, expected.Bars) { t.Errorf(fieldsDifferTemplate, "Bars") } if !reflect.DeepEqual(analysis.Beats, expected.Beats) { t.Errorf(fieldsDifferTemplate, "Beats") } if !reflect.DeepEqual(analysis.Meta, expected.Meta) { t.Errorf(fieldsDifferTemplate, "Meta") } if !reflect.DeepEqual(analysis.Sections, expected.Sections) { t.Errorf(fieldsDifferTemplate, "Sections") } if !reflect.DeepEqual(analysis.Segments, expected.Segments) { t.Errorf(fieldsDifferTemplate, "Segments") } if !reflect.DeepEqual(analysis.Track, expected.Track) { t.Errorf(fieldsDifferTemplate, "Track") } if !reflect.DeepEqual(analysis.Tatums, expected.Tatums) { t.Errorf(fieldsDifferTemplate, "Tatums") } }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
audio_features.go
Go
package spotify import ( "context" "fmt" "strings" ) // AudioFeatures contains various high-level acoustic attributes // for a particular track. type AudioFeatures struct { // Acousticness is a confidence measure from 0.0 to 1.0 of whether // the track is acoustic. A value of 1.0 represents high confidence // that the track is acoustic. Acousticness float32 `json:"acousticness"` // An HTTP URL to access the full audio analysis of the track. // The URL is cryptographically signed and configured to expire // after roughly 10 minutes. Do not store these URLs for later use. AnalysisURL string `json:"analysis_url"` // Danceability describes how suitable a track is for dancing based // on a combination of musical elements including tempo, rhythm stability, // beat strength, and overall regularity. A value of 0.0 is least danceable // and 1.0 is most danceable. Danceability float32 `json:"danceability"` // The length of the track in milliseconds. Duration Numeric `json:"duration_ms"` // Energy is a measure from 0.0 to 1.0 and represents a perceptual measure // of intensity and activity. Typically, energetic tracks feel fast, loud, // and noisy. Energy float32 `json:"energy"` // The Spotify ID for the track. ID ID `json:"id"` // Predicts whether a track contains no vocals. "Ooh" and "aah" sounds are // treated as instrumental in this context. Rap or spoken words are clearly // "vocal". The closer the Instrumentalness value is to 1.0, the greater // likelihood the track contains no vocal content. Values above 0.5 are // intended to represent instrumental tracks, but confidence is higher as the // value approaches 1.0. Instrumentalness float32 `json:"instrumentalness"` // The key the track is in. Integers map to pitches using standard // [Pitch Class] notation. // // [Pitch Class]: https://en.wikipedia.org/wiki/Pitch_class Key Numeric `json:"key"` // Detects the presence of an audience in the recording. Higher liveness // values represent an increased probability that the track was performed live. // A value above 0.8 provides strong likelihood that the track is live. Liveness float32 `json:"liveness"` // The overall loudness of a track in decibels (dB). Loudness values are // averaged across the entire track and are useful for comparing the relative // loudness of tracks. Typical values range between -60 and 0 dB. Loudness float32 `json:"loudness"` // Mode indicates the modality (major or minor) of a track. Mode Numeric `json:"mode"` // Detects the presence of spoken words in a track. The more exclusively // speech-like the recording, the closer to 1.0 the speechiness will be. // Values above 0.66 describe tracks that are probably made entirely of // spoken words. Values between 0.33 and 0.66 describe tracks that may // contain both music and speech, including such cases as rap music. // Values below 0.33 most likely represent music and other non-speech-like tracks. Speechiness float32 `json:"speechiness"` // The overall estimated tempo of the track in beats per minute (BPM). Tempo float32 `json:"tempo"` // An estimated overall time signature of a track. The time signature (meter) // is a notational convention to specify how many beats are in each bar (or measure). TimeSignature Numeric `json:"time_signature"` // A link to the Web API endpoint providing full details of the track. TrackURL string `json:"track_href"` // The Spotify URI for the track. URI URI `json:"uri"` // A measure from 0.0 to 1.0 describing the musical positiveness conveyed // by a track. Tracks with high valence sound more positive (e.g. happy, // cheerful, euphoric), while tracks with low valence sound more negative // (e.g. sad, depressed, angry). Valence float32 `json:"valence"` } // Key represents a pitch using [Pitch Class] notation. // // [Pitch Class]: https://en.wikipedia.org/wiki/Pitch_class type Key int const ( C Key = iota CSharp D DSharp E F FSharp G GSharp A ASharp B DFlat = CSharp EFlat = DSharp GFlat = FSharp AFlat = GSharp BFlat = ASharp ) // Mode indicates the modality (major or minor) of a track. type Mode int const ( Minor Mode = iota Major ) // GetAudioFeatures queries the Spotify Web API for various // high-level acoustic attributes of audio tracks. // Objects are returned in the order requested. If an object // is not found, a nil value is returned in the appropriate position. func (c *Client) GetAudioFeatures(ctx context.Context, ids ...ID) ([]*AudioFeatures, error) { url := fmt.Sprintf("%saudio-features?ids=%s", c.baseURL, strings.Join(toStringSlice(ids), ",")) temp := struct { F []*AudioFeatures `json:"audio_features"` }{} err := c.get(ctx, url, &temp) if err != nil { return nil, err } return temp.F, nil }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
audio_features_test.go
Go
package spotify import ( "context" "net/http" "testing" ) var response = ` { "audio_features" : [ { "danceability" : 0.808, "energy" : 0.626, "key" : 7, "loudness" : -12.733, "mode" : 1, "speechiness" : 0.168, "acousticness" : 0.00187, "instrumentalness" : 0.159, "liveness" : 0.376, "valence" : 0.369, "tempo" : 123.990, "type" : "audio_features", "id" : "4JpKVNYnVcJ8tuMKjAj50A", "uri" : "spotify:track:4JpKVNYnVcJ8tuMKjAj50A", "track_href" : "https://api.spotify.com/v1/tracks/4JpKVNYnVcJ8tuMKjAj50A", "analysis_url" : "http://echonest-analysis.s3.amazonaws.com/TR/WhpYUARk1kNJ_qP0AdKGcDDFKOQTTgsOoINrqyPQjkUnbteuuBiyj_u94iFCSGzdxGiwqQ6d77f4QLL_8=/3/full.json?AWSAccessKeyId=AKIAJRDFEY23UEVW42BQ&Expires=1459290544&Signature=4P03WGLL1a/%2BXp90jcsLGMfFC3Y%3D", "duration_ms" : 535223, "time_signature" : 4 }, { "danceability" : 0.457, "energy" : 0.815, "key" : 1, "loudness" : -7.199, "mode" : 1, "speechiness" : 0.0340, "acousticness" : 0.102, "instrumentalness" : 0.0319, "liveness" : 0.103, "valence" : 0.382, "tempo" : 96.083, "type" : "audio_features", "id" : "2NRANZE9UCmPAS5XVbXL40", "uri" : "spotify:track:2NRANZE9UCmPAS5XVbXL40", "track_href" : "https://api.spotify.com/v1/tracks/2NRANZE9UCmPAS5XVbXL40", "analysis_url" : "http://echonest-analysis.s3.amazonaws.com/TR/WhuQhwPDhmEg5TO4JjbJu0my-awIhk3eaXkRd1ofoJ7tXogPnMtbxkTyLOeHXu5Jke0FCIt52saKJyfPM=/3/full.json?AWSAccessKeyId=AKIAJRDFEY23UEVW42BQ&Expires=1459290544&Signature=Jsg/GexxC7v06Tq70coL/d2x7kI%3D", "duration_ms" : 187800, "time_signature" : 4 }, null, { "danceability" : 0.281, "energy" : 0.402, "key" : 4, "loudness" : -17.921, "mode" : 1, "speechiness" : 0.0291, "acousticness" : 0.0734, "instrumentalness" : 0.830, "liveness" : 0.0593, "valence" : 0.0748, "tempo" : 115.700, "type" : "audio_features", "id" : "24JygzOLM0EmRQeGtFcIcG", "uri" : "spotify:track:24JygzOLM0EmRQeGtFcIcG", "track_href" : "https://api.spotify.com/v1/tracks/24JygzOLM0EmRQeGtFcIcG", "analysis_url" : "http://echonest-analysis.s3.amazonaws.com/TR/ehbkMg05Ck-FN7p3lV7vd8TUdBCvM6z5mgDiZRv6iSlw8P_b8GYBZ4PRAlOgTl3e5rS34_l3dZGDeYzH4=/3/full.json?AWSAccessKeyId=AKIAJRDFEY23UEVW42BQ&Expires=1459290544&Signature=09T3QyRucjrOMoMutRmdJKLJ7hI%3D", "duration_ms" : 497493, "time_signature" : 3 } ] } ` func TestAudioFeatures(t *testing.T) { c, s := testClientString(http.StatusOK, response) defer s.Close() ids := []ID{ "4JpKVNYnVcJ8tuMKjAj50A", "2NRANZE9UCmPAS5XVbXL40", "abc", // intentionally throw a bad one in "24JygzOLM0EmRQeGtFcIcG", } features, err := c.GetAudioFeatures(context.Background()) if err != nil { t.Error(err) } if len(features) != len(ids) { t.Errorf("Want %d results, got %d\n", len(ids), len(features)) } if features[2] != nil { t.Errorf("Want nil result, got #%v\n", features[2]) } if Key(features[0].Key) != G { t.Errorf("Want key G, got %v\n", features[0].Key) } }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
auth/auth.go
Go
package spotifyauth import ( "context" "errors" "net/http" "os" "golang.org/x/oauth2" ) const ( // AuthURL is the URL to Spotify Accounts Service's OAuth2 endpoint. AuthURL = "https://accounts.spotify.com/authorize" // TokenURL is the URL to the Spotify Accounts Service's OAuth2 // token endpoint. TokenURL = "https://accounts.spotify.com/api/token" ) // Scopes let you specify exactly which types of data your application wants to access. // The set of scopes you pass in your authentication request determines what access the // permissions the user is asked to grant. // // [Scopes] are needed when implementing some of the authorization grant types. Make // sure you have read the [Authorization guide] to understand the basics. // // [Scopes]: https://developer.spotify.com/documentation/web-api/concepts/scopes // [Authorization guide]: https://developer.spotify.com/documentation/web-api/concepts/authorization const ( // ScopeImageUpload seeks permission to upload images to Spotify on your behalf. ScopeImageUpload = "ugc-image-upload" // ScopePlaylistReadPrivate seeks permission to read // a user's private playlists. ScopePlaylistReadPrivate = "playlist-read-private" // ScopePlaylistModifyPublic seeks write access // to a user's public playlists. ScopePlaylistModifyPublic = "playlist-modify-public" // ScopePlaylistModifyPrivate seeks write access to // a user's private playlists. ScopePlaylistModifyPrivate = "playlist-modify-private" // ScopePlaylistReadCollaborative seeks permission to // access a user's collaborative playlists. ScopePlaylistReadCollaborative = "playlist-read-collaborative" // ScopeUserFollowModify seeks write/delete access to // the list of artists and other users that a user follows. ScopeUserFollowModify = "user-follow-modify" // ScopeUserFollowRead seeks read access to the list of // artists and other users that a user follows. ScopeUserFollowRead = "user-follow-read" // ScopeUserLibraryModify seeks write/delete access to a // user's "Your Music" library. ScopeUserLibraryModify = "user-library-modify" // ScopeUserLibraryRead seeks read access to a user's "Your Music" library. ScopeUserLibraryRead = "user-library-read" // ScopeUserReadPrivate seeks read access to a user's // subscription details (type of user account). ScopeUserReadPrivate = "user-read-private" // ScopeUserReadEmail seeks read access to a user's email address. ScopeUserReadEmail = "user-read-email" // ScopeUserReadCurrentlyPlaying seeks read access to a user's currently playing track ScopeUserReadCurrentlyPlaying = "user-read-currently-playing" // ScopeUserReadPlaybackState seeks read access to the user's current playback state ScopeUserReadPlaybackState = "user-read-playback-state" // ScopeUserModifyPlaybackState seeks write access to the user's current playback state ScopeUserModifyPlaybackState = "user-modify-playback-state" // ScopeUserReadRecentlyPlayed allows access to a user's recently-played songs ScopeUserReadRecentlyPlayed = "user-read-recently-played" // ScopeUserTopRead seeks read access to a user's top tracks and artists ScopeUserTopRead = "user-top-read" // ScopeStreaming seeks permission to play music and control playback on your other devices. ScopeStreaming = "streaming" ) // Authenticator provides convenience functions for implementing the OAuth2 flow. // You should always use [New] to make them. // // Example: // // a := spotifyauth.New(redirectURL, spotify.ScopeUserLibraryRead, spotify.ScopeUserFollowRead) // // direct user to Spotify to log in // http.Redirect(w, r, a.AuthURL("state-string"), http.StatusFound) // // // then, in redirect handler: // token, err := a.Token(state, r) // client := a.Client(token) type Authenticator struct { config *oauth2.Config } type AuthenticatorOption func(a *Authenticator) // WithClientID allows a client ID to be specified. Without this the value of the SPOTIFY_ID environment // variable will be used. func WithClientID(id string) AuthenticatorOption { return func(a *Authenticator) { a.config.ClientID = id } } // WithClientSecret allows a client secret to be specified. Without this the value of the SPOTIFY_SECRET environment // variable will be used. func WithClientSecret(secret string) AuthenticatorOption { return func(a *Authenticator) { a.config.ClientSecret = secret } } // WithScopes configures the oauth scopes that the client should request. func WithScopes(scopes ...string) AuthenticatorOption { return func(a *Authenticator) { a.config.Scopes = scopes } } // WithRedirectURL configures a redirect url for oauth flows. It must exactly match one of the // URLs specified in your Spotify developer account. func WithRedirectURL(url string) AuthenticatorOption { return func(a *Authenticator) { a.config.RedirectURL = url } } // New creates an authenticator which is used to implement the OAuth2 authorization flow. // // By default, it pulls your client ID and secret key from the SPOTIFY_ID and SPOTIFY_SECRET environment variables. func New(opts ...AuthenticatorOption) *Authenticator { cfg := &oauth2.Config{ ClientID: os.Getenv("SPOTIFY_ID"), ClientSecret: os.Getenv("SPOTIFY_SECRET"), Endpoint: oauth2.Endpoint{ AuthURL: AuthURL, TokenURL: TokenURL, }, } a := &Authenticator{ config: cfg, } for _, opt := range opts { opt(a) } return a } // ShowDialog forces the user to approve the app, even if they have already done so. // Without this, users who have already approved the app are immediately redirected // to the redirect URL. var ShowDialog = oauth2.SetAuthURLParam("show_dialog", "true") // AuthURL returns a URL to the Spotify Accounts Service's OAuth2 endpoint. // // State is a token to protect the user from CSRF attacks. You should pass the // same state to `Token`, where it will be validated. For more info, refer to // http://tools.ietf.org/html/rfc6749#section-10.12. func (a Authenticator) AuthURL(state string, opts ...oauth2.AuthCodeOption) string { return a.config.AuthCodeURL(state, opts...) } // Token pulls an authorization code from an HTTP request and attempts to exchange // it for an access token. The standard use case is to call Token from the handler // that handles requests to your application's redirect URL. func (a Authenticator) Token(ctx context.Context, state string, r *http.Request, opts ...oauth2.AuthCodeOption) (*oauth2.Token, error) { values := r.URL.Query() if e := values.Get("error"); e != "" { return nil, errors.New("spotify: auth failed - " + e) } code := values.Get("code") if code == "" { return nil, errors.New("spotify: didn't get access code") } actualState := values.Get("state") if actualState != state { return nil, errors.New("spotify: redirect state parameter doesn't match") } return a.config.Exchange(ctx, code, opts...) } // RefreshToken returns a new token if an access token has expired. // If it has not expired, return the existing token. func (a Authenticator) RefreshToken(ctx context.Context, token *oauth2.Token) (*oauth2.Token, error) { src := a.config.TokenSource(ctx, token) return src.Token() } // Exchange is like [Token], except it allows you to manually specify the access // code instead of pulling it out of an HTTP request. func (a Authenticator) Exchange(ctx context.Context, code string, opts ...oauth2.AuthCodeOption) (*oauth2.Token, error) { return a.config.Exchange(ctx, code, opts...) } // Client creates a [net/http.Client] that will use the specified access token // for its API requests. You will typically pass this to [github.com/zmb3/spotify.New]. func (a Authenticator) Client(ctx context.Context, token *oauth2.Token) *http.Client { return a.config.Client(ctx, token) }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
category.go
Go
package spotify import ( "context" "fmt" ) // Category is used by Spotify to tag items in. For example, on the Spotify // player's "Browse" tab. type Category struct { // A link to the Web API endpoint returning full details of the category Endpoint string `json:"href"` // The category icon, in various sizes Icons []Image `json:"icons"` // The Spotify category ID. This isn't a base-62 Spotify ID, its just // a short string that describes and identifies the category (ie "party"). ID string `json:"id"` // The name of the category Name string `json:"name"` } // GetCategory gets a single category used to tag items in Spotify. // // Supported options: [Country], [Locale]. func (c *Client) GetCategory(ctx context.Context, id string, opts ...RequestOption) (Category, error) { cat := Category{} spotifyURL := fmt.Sprintf("%sbrowse/categories/%s", c.baseURL, id) if params := processOptions(opts...).urlParams.Encode(); params != "" { spotifyURL += "?" + params } err := c.get(ctx, spotifyURL, &cat) return cat, err } // GetCategoryPlaylists gets a list of Spotify playlists tagged with a particular category. // // Supported options: [Country], [Limit], [Offset]. func (c *Client) GetCategoryPlaylists(ctx context.Context, catID string, opts ...RequestOption) (*SimplePlaylistPage, error) { spotifyURL := fmt.Sprintf("%sbrowse/categories/%s/playlists", c.baseURL, catID) if params := processOptions(opts...).urlParams.Encode(); params != "" { spotifyURL += "?" + params } wrapper := struct { Playlists SimplePlaylistPage `json:"playlists"` }{} err := c.get(ctx, spotifyURL, &wrapper) if err != nil { return nil, err } return &wrapper.Playlists, nil } // GetCategories gets a list of categories used to tag items in Spotify // // Supported options: [Country], [Locale], [Limit], [Offset]. func (c *Client) GetCategories(ctx context.Context, opts ...RequestOption) (*CategoryPage, error) { spotifyURL := c.baseURL + "browse/categories" if query := processOptions(opts...).urlParams.Encode(); query != "" { spotifyURL += "?" + query } wrapper := struct { Categories CategoryPage `json:"categories"` }{} err := c.get(ctx, spotifyURL, &wrapper) if err != nil { return nil, err } return &wrapper.Categories, nil }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
category_test.go
Go
package spotify import ( "context" "net/http" "testing" ) func TestGetCategories(t *testing.T) { client, server := testClientString(http.StatusOK, getCategories) defer server.Close() page, err := client.GetCategories(context.Background()) if err != nil { t.Fatal(err) } if l := len(page.Categories); l != 2 { t.Fatalf("Expected 2 categories, got %d\n", l) } if name := page.Categories[1].Name; name != "Mood" { t.Errorf("Expected 'Mood', got '%s'", name) } } func TestGetCategory(t *testing.T) { client, server := testClientString(http.StatusOK, getCategory) defer server.Close() cat, err := client.GetCategory(context.Background(), "dinner") if err != nil { t.Fatal(err) } if cat.ID != "dinner" || cat.Name != "Dinner" { t.Errorf("Invalid name/id (%s, %s)\n", cat.Name, cat.ID) } } func TestGetCategoryPlaylists(t *testing.T) { client, server := testClientString(http.StatusOK, getCategoryPlaylists) defer server.Close() page, err := client.GetCategoryPlaylists(context.Background(), "dinner") if err != nil { t.Fatal(err) } if l := len(page.Playlists); l != 2 { t.Fatalf("Expected 2 playlists, got %d\n", l) } if name := page.Playlists[0].Name; name != "Dinner with Friends" { t.Errorf("Expected 'Dinner with Friends', got '%s'\n", name) } if tracks := page.Playlists[1].Tracks.Total; tracks != 91 { t.Errorf("Expected 'Dinner Music' to have 91 tracks, but got %d\n", tracks) } if page.Total != 36 { t.Errorf("Expected 26 playlists in category 'dinner' - got %d\n", page.Total) } } func TestGetCategoryOpt(t *testing.T) { client, server := testClientString(http.StatusNotFound, "", func(r *http.Request) { // verify that the optional parameters were included in the request values := r.URL.Query() if c := values.Get("country"); c != CountryBrazil { t.Errorf("Expected country '%s', got '%s'\n", CountryBrazil, c) } if l := values.Get("locale"); l != "es_MX" { t.Errorf("Expected locale 'es_MX', got '%s'\n", l) } }) defer server.Close() _, err := client.GetCategory(context.Background(), "id", Country(CountryBrazil), Locale("es_MX")) if err == nil { t.Fatal("Expected error") } } func TestGetCategoryPlaylistsOpt(t *testing.T) { client, server := testClientString(http.StatusNotFound, "", func(r *http.Request) { values := r.URL.Query() if c := values.Get("country"); c != "" { t.Errorf("Country should not have been set, got %s\n", c) } if l := values.Get("limit"); l != "5" { t.Errorf("Expected limit 5, got %s\n", l) } if o := values.Get("offset"); o != "10" { t.Errorf("Expected offset 10, got %s\n", o) } }) defer server.Close() _, err := client.GetCategoryPlaylists(context.Background(), "id", Limit(5), Offset(10)) if want := "spotify: Not Found [404]"; err == nil || err.Error() != want { t.Errorf("Expected error: want %v, got %v", want, err) } } func TestGetCategoriesInvalidToken(t *testing.T) { client, server := testClientString(http.StatusUnauthorized, invalidToken) defer server.Close() _, err := client.GetCategories(context.Background()) if err == nil { t.Fatal("Expected error but didn't get one") } serr, ok := err.(Error) if !ok { t.Fatal("Expected a 'spotify.Error'") } if serr.Status != http.StatusUnauthorized { t.Error("Error didn't have status code 401") } } var getCategories = ` { "categories" : { "href" : "https://api.spotify.com/v1/browse/categories?country=CA&offset=0&limit=2", "items" : [ { "href" : "https://api.spotify.com/v1/browse/categories/toplists", "icons" : [ { "height" : 275, "url" : "https://datsnxq1rwndn.cloudfront.net/media/derived/toplists_11160599e6a04ac5d6f2757f5511778f_0_0_275_275.jpg", "width" : 275 } ], "id" : "toplists", "name" : "Top Lists" }, { "href" : "https://api.spotify.com/v1/browse/categories/mood", "icons" : [ { "height" : 274, "url" : "https://datsnxq1rwndn.cloudfront.net/media/original/mood-274x274_976986a31ac8c49794cbdc7246fd5ad7_274x274.jpg", "width" : 274 } ], "id" : "mood", "name" : "Mood" } ], "limit" : 2, "next" : "https://api.spotify.com/v1/browse/categories?country=CA&offset=2&limit=2", "offset" : 0, "previous" : null, "total" : 31 } }` var getCategory = ` { "href" : "https://api.spotify.com/v1/browse/categories/dinner", "icons" : [ { "height" : 274, "url" : "https://datsnxq1rwndn.cloudfront.net/media/original/dinner_1b6506abba0ba52c54e6d695c8571078_274x274.jpg", "width" : 274 } ], "id" : "dinner", "name" : "Dinner" }` var getCategoryPlaylists = ` { "playlists" : { "href" : "https://api.spotify.com/v1/browse/categories/dinner/playlists?offset=0&limit=2", "items" : [ { "collaborative" : false, "external_urls" : { "spotify" : "http://open.spotify.com/user/spotify/playlist/59ZbFPES4DQwEjBpWHzrtC" }, "href" : "https://api.spotify.com/v1/users/spotify/playlists/59ZbFPES4DQwEjBpWHzrtC", "id" : "59ZbFPES4DQwEjBpWHzrtC", "images" : [ { "height" : 300, "url" : "https://i.scdn.co/image/68b6a65573a55095e9c0c0c33a274b18e0422736", "width" : 300 } ], "name" : "Dinner with Friends", "owner" : { "external_urls" : { "spotify" : "http://open.spotify.com/user/spotify" }, "href" : "https://api.spotify.com/v1/users/spotify", "id" : "spotify", "type" : "user", "uri" : "spotify:user:spotify" }, "public" : null, "tracks" : { "href" : "https://api.spotify.com/v1/users/spotify/playlists/59ZbFPES4DQwEjBpWHzrtC/tracks", "total" : 98 }, "type" : "playlist", "uri" : "spotify:user:spotify:playlist:59ZbFPES4DQwEjBpWHzrtC" }, { "collaborative" : false, "external_urls" : { "spotify" : "http://open.spotify.com/user/spotify/playlist/1WDw5izv4UhpobNdGXQug7" }, "href" : "https://api.spotify.com/v1/users/spotify/playlists/1WDw5izv4UhpobNdGXQug7", "id" : "1WDw5izv4UhpobNdGXQug7", "images" : [ { "height" : 300, "url" : "https://i.scdn.co/image/acdcc5e1aa4e9c1db523d684a35f9c0785e50152", "width" : 300 } ], "name" : "Dinner Music", "owner" : { "external_urls" : { "spotify" : "http://open.spotify.com/user/spotify" }, "href" : "https://api.spotify.com/v1/users/spotify", "id" : "spotify", "type" : "user", "uri" : "spotify:user:spotify" }, "public" : null, "tracks" : { "href" : "https://api.spotify.com/v1/users/spotify/playlists/1WDw5izv4UhpobNdGXQug7/tracks", "total" : 91 }, "type" : "playlist", "uri" : "spotify:user:spotify:playlist:1WDw5izv4UhpobNdGXQug7" } ], "limit" : 2, "next" : "https://api.spotify.com/v1/browse/categories/dinner/playlists?offset=2&limit=2", "offset" : 0, "previous" : null, "total" : 36 } }` var invalidToken = ` { "error": { "status": 401, "message": "Invalid access token" } }`
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
countries.go
Go
package spotify // [ISO 3166-1 alpha-2] country codes. // // [ISO 3166-1 alpha-2]: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 const ( CountryArgentina = "AR" CountryAustralia = "AU" CountryAustria = "AT" CountryBelarus = "BY" CountryBelgium = "BE" CountryBrazil = "BR" CountryCanada = "CA" CountryChile = "CL" CountryChina = "CN" CountryGermany = "DE" CountryHongKong = "HK" CountryIreland = "IE" CountryIndia = "IN" CountryItaly = "IT" CountryJapan = "JP" CountrySpain = "ES" CountryFinland = "FI" CountryFrance = "FR" CountryMexico = "MX" CountryNewZealand = "NZ" CountryRussia = "RU" CountrySwitzerland = "CH" CountryUnitedArabEmirates = "AE" CountryUnitedKingdom = "GB" CountryUSA = "US" )
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
cursor.go
Go
package spotify // This file contains the types that implement Spotify's cursor-based // paging object. Like the standard paging object, this object is a // container for a set of items. Unlike the standard paging object, a // cursor-based paging object does not provide random access to the results. // Cursor contains a key that can be used to find the next set // of items. type Cursor struct { After string `json:"after"` } // cursorPage contains all of the fields in a Spotify cursor-based // paging object, except for the actual items. This type is meant // to be embedded in other types that add the Items field. type cursorPage struct { // A link to the Web API endpoint returning the full // result of this request. Endpoint string `json:"href"` // The maximum number of items returned, as set in the query // (or default value if unset). Limit Numeric `json:"limit"` // The URL to the next set of items. Next string `json:"next"` // The total number of items available to return. Total Numeric `json:"total"` // The cursor used to find the next set of items. Cursor Cursor `json:"cursors"` } // FullArtistCursorPage is a cursor-based paging object containing // a set of [FullArtist] objects. type FullArtistCursorPage struct { cursorPage Artists []FullArtist `json:"items"` }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
examples/authenticate/authcode/authenticate.go
Go
// This example demonstrates how to authenticate with Spotify using the authorization code flow. // In order to run this example yourself, you'll need to: // // 1. Register an application at: https://developer.spotify.com/my-applications/ // - Use "http://localhost:8080/callback" as the redirect URI // 2. Set the SPOTIFY_ID environment variable to the client ID you got in step 1. // 3. Set the SPOTIFY_SECRET environment variable to the client secret from step 1. package main import ( "context" "fmt" "github.com/zmb3/spotify/v2/auth" "log" "net/http" "github.com/zmb3/spotify/v2" ) // redirectURI is the OAuth redirect URI for the application. // You must register an application at Spotify's developer portal // and enter this value. const redirectURI = "http://localhost:8080/callback" var ( auth = spotifyauth.New(spotifyauth.WithRedirectURL(redirectURI), spotifyauth.WithScopes(spotifyauth.ScopeUserReadPrivate)) ch = make(chan *spotify.Client) state = "abc123" ) func main() { // first start an HTTP server http.HandleFunc("/callback", completeAuth) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { log.Println("Got request for:", r.URL.String()) }) go func() { err := http.ListenAndServe(":8080", nil) if err != nil { log.Fatal(err) } }() url := auth.AuthURL(state) fmt.Println("Please log in to Spotify by visiting the following page in your browser:", url) // wait for auth to complete client := <-ch // use the client to make calls that require authorization user, err := client.CurrentUser(context.Background()) if err != nil { log.Fatal(err) } fmt.Println("You are logged in as:", user.ID) } func completeAuth(w http.ResponseWriter, r *http.Request) { tok, err := auth.Token(r.Context(), state, r) if err != nil { http.Error(w, "Couldn't get token", http.StatusForbidden) log.Fatal(err) } if st := r.FormValue("state"); st != state { http.NotFound(w, r) log.Fatalf("State mismatch: %s != %s\n", st, state) } // use the token to get an authenticated client client := spotify.New(auth.Client(r.Context(), tok)) fmt.Fprintf(w, "Login Completed!") ch <- client }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
examples/authenticate/clientcreds/client_credentials.go
Go
// This example demonstrates how to authenticate with Spotify using the // client credentials flow. Note that this flow does not include authorization // and can't be used to access a user's private data. // // Make sure you set the SPOTIFY_ID and SPOTIFY_SECRET environment variables // prior to running this example. package main import ( "context" "fmt" "github.com/zmb3/spotify/v2/auth" "log" "os" "github.com/zmb3/spotify/v2" "golang.org/x/oauth2/clientcredentials" ) func main() { ctx := context.Background() config := &clientcredentials.Config{ ClientID: os.Getenv("SPOTIFY_ID"), ClientSecret: os.Getenv("SPOTIFY_SECRET"), TokenURL: spotifyauth.TokenURL, } token, err := config.Token(ctx) if err != nil { log.Fatalf("couldn't get token: %v", err) } httpClient := spotifyauth.New().Client(ctx, token) client := spotify.New(httpClient) msg, page, err := client.FeaturedPlaylists(ctx) if err != nil { log.Fatalf("couldn't get features playlists: %v", err) } fmt.Println(msg) for _, playlist := range page.Playlists { fmt.Println(" ", playlist.Name) } }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
examples/authenticate/pkce/pkce.go
Go
// This example demonstrates how to authenticate with Spotify using the authorization code flow with PKCE. // In order to run this example yourself, you'll need to: // // 1. Register an application at: https://developer.spotify.com/my-applications/ // - Use "http://localhost:8080/callback" as the redirect URI // 2. Set the SPOTIFY_ID environment variable to the client ID you got in step 1. package main import ( "context" "fmt" spotifyauth "github.com/zmb3/spotify/v2/auth" "log" "os" "net/http" "golang.org/x/oauth2" "github.com/zmb3/spotify/v2" ) // redirectURI is the OAuth redirect URI for the application. // You must register an application at Spotify's developer portal // and enter this value. const redirectURI = "http://localhost:8080/callback" var ( auth = spotifyauth.New(spotifyauth.WithRedirectURL(redirectURI), spotifyauth.WithScopes(spotifyauth.ScopeUserReadPrivate)) ch = make(chan *spotify.Client) state = "abc123" // These should be randomly generated for each request // More information on generating these can be found here, // https://www.oauth.com/playground/authorization-code-with-pkce.html codeVerifier = "w0HfYrKnG8AihqYHA9_XUPTIcqEXQvCQfOF2IitRgmlF43YWJ8dy2b49ZUwVUOR.YnvzVoTBL57BwIhM4ouSa~tdf0eE_OmiMC_ESCcVOe7maSLIk9IOdBhRstAxjCl7" codeChallenge = "ZhZJzPQXYBMjH8FlGAdYK5AndohLzFfZT-8J7biT7ig" ) func main() { // first start an HTTP server http.HandleFunc("/callback", completeAuth) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { log.Println("Got request for:", r.URL.String()) }) go http.ListenAndServe(":8080", nil) url := auth.AuthURL(state, oauth2.SetAuthURLParam("code_challenge_method", "S256"), oauth2.SetAuthURLParam("code_challenge", codeChallenge), oauth2.SetAuthURLParam("client_id", os.Getenv("CLIENT_ID")), ) fmt.Println("Please log in to Spotify by visiting the following page in your browser:", url) // wait for auth to complete client := <-ch // use the client to make calls that require authorization user, err := client.CurrentUser(context.Background()) if err != nil { log.Fatal(err) } fmt.Println("You are logged in as:", user.ID) } func completeAuth(w http.ResponseWriter, r *http.Request) { tok, err := auth.Token(r.Context(), state, r, oauth2.SetAuthURLParam("code_verifier", codeVerifier)) if err != nil { http.Error(w, "Couldn't get token", http.StatusForbidden) log.Fatal(err) } if st := r.FormValue("state"); st != state { http.NotFound(w, r) log.Fatalf("State mismatch: %s != %s\n", st, state) } // use the token to get an authenticated client client := spotify.New(auth.Client(r.Context(), tok)) fmt.Fprintf(w, "Login Completed!") ch <- client }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
examples/cli/cli.go
Go
package cli import ( "context" "flag" "github.com/zmb3/spotify/v2" spotifyauth "github.com/zmb3/spotify/v2/auth" "golang.org/x/oauth2" "log" ) var auth = spotifyauth.New(spotifyauth.WithRedirectURL("http://localhost:3000/login_check")) func main() { code := flag.String("code", "", "authorization code to negotiate by token") flag.Parse() if *code == "" { log.Fatal("code required") } if err := Authorize(*code); err != nil { log.Fatal("error while negotiating the token: ", err) } } func Authorize(code string) error { ctx := context.Background() token, err := auth.Exchange(ctx, code) httpClient := oauth2.NewClient(context.Background(), oauth2.StaticTokenSource(token)) client := spotify.New(httpClient) user, err := client.CurrentUser(ctx) if err != nil { return err } log.Printf("Logged in as %s\n", user.DisplayName) return nil }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
examples/features/features.go
Go
package main import ( "context" "fmt" "log" "os" "text/tabwriter" spotifyauth "github.com/zmb3/spotify/v2/auth" "golang.org/x/oauth2/clientcredentials" "github.com/zmb3/spotify/v2" ) func main() { ctx := context.Background() config := &clientcredentials.Config{ ClientID: os.Getenv("SPOTIFY_ID"), ClientSecret: os.Getenv("SPOTIFY_SECRET"), TokenURL: spotifyauth.TokenURL, } token, err := config.Token(ctx) if err != nil { log.Fatalf("couldn't get token: %v", err) } httpClient := spotifyauth.New().Client(ctx, token) client := spotify.New(httpClient) // search for albums with the name Sempiternal results, err := client.Search(ctx, "Sempiternal", spotify.SearchTypeAlbum) if err != nil { log.Fatal(err) } // select the top album item := results.Albums.Albums[0] // get tracks from album res, err := client.GetAlbumTracks(ctx, item.ID, spotify.Market("US")) if err != nil { log.Fatal("error getting tracks ....", err.Error()) return } // *display in tabular form using TabWriter w := tabwriter.NewWriter(os.Stdout, 10, 2, 3, ' ', 0) fmt.Fprintf(w, "%s\t%s\t%s\t%s\t\n\n", "Songs", "Energy", "Danceability", "Valence") // loop through tracks for _, track := range res.Tracks { // retrieve features features, err := client.GetAudioFeatures(ctx, track.ID) if err != nil { log.Fatal("error getting audio features...", err.Error()) return } fmt.Fprintf(w, "%s\t%v\t%v\t%v\t\n", track.Name, features[0].Energy, features[0].Danceability, features[0].Valence) w.Flush() } }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
examples/paging/page.go
Go
package main import ( "context" "log" "os" "github.com/zmb3/spotify/v2" spotifyauth "github.com/zmb3/spotify/v2/auth" "golang.org/x/oauth2/clientcredentials" ) func main() { ctx := context.Background() config := &clientcredentials.Config{ ClientID: os.Getenv("SPOTIFY_ID"), ClientSecret: os.Getenv("SPOTIFY_SECRET"), TokenURL: spotifyauth.TokenURL, } token, err := config.Token(ctx) if err != nil { log.Fatalf("couldn't get token: %v", err) } httpClient := spotifyauth.New().Client(ctx, token) client := spotify.New(httpClient) // Public playlist owned by noah.stride: // "Long playlist for testing pagination" playlistID := "1ckDytqUi4BUYzs6HIhcAN" if id := os.Getenv("SPOTIFY_PLAYLIST"); id != "" { playlistID = id } tracks, err := client.GetPlaylistItems( ctx, spotify.ID(playlistID), ) if err != nil { log.Fatal(err) } log.Printf("Playlist has %d total tracks", tracks.Total) for page := 1; ; page++ { log.Printf(" Page %d has %d tracks", page, len(tracks.Items)) err = client.NextPage(ctx, tracks) if err == spotify.ErrNoMorePages { break } if err != nil { log.Fatal(err) } } }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
examples/player/player.go
Go
// This example demonstrates how to authenticate with Spotify. // In order to run this example yourself, you'll need to: // // 1. Register an application at: https://developer.spotify.com/my-applications/ // - Use "http://localhost:8080/callback" as the redirect URI // 2. Set the SPOTIFY_ID environment variable to the client ID you got in step 1. // 3. Set the SPOTIFY_SECRET environment variable to the client secret from step 1. package main import ( "context" "fmt" spotifyauth "github.com/zmb3/spotify/v2/auth" "log" "net/http" "strings" "github.com/zmb3/spotify/v2" ) // redirectURI is the OAuth redirect URI for the application. // You must register an application at Spotify's developer portal // and enter this value. const redirectURI = "http://localhost:8080/callback" var html = ` <br/> <a href="/player/play">Play</a><br/> <a href="/player/pause">Pause</a><br/> <a href="/player/next">Next track</a><br/> <a href="/player/previous">Previous Track</a><br/> <a href="/player/shuffle">Shuffle</a><br/> ` var ( auth = spotifyauth.New( spotifyauth.WithRedirectURL(redirectURI), spotifyauth.WithScopes(spotifyauth.ScopeUserReadCurrentlyPlaying, spotifyauth.ScopeUserReadPlaybackState, spotifyauth.ScopeUserModifyPlaybackState), ) ch = make(chan *spotify.Client) state = "abc123" ) func main() { // We'll want these variables sooner rather than later var client *spotify.Client var playerState *spotify.PlayerState http.HandleFunc("/callback", completeAuth) http.HandleFunc("/player/", func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() action := strings.TrimPrefix(r.URL.Path, "/player/") fmt.Println("Got request for:", action) var err error switch action { case "play": err = client.Play(ctx) case "pause": err = client.Pause(ctx) case "next": err = client.Next(ctx) case "previous": err = client.Previous(ctx) case "shuffle": playerState.ShuffleState = !playerState.ShuffleState err = client.Shuffle(ctx, playerState.ShuffleState) } if err != nil { log.Print(err) } w.Header().Set("Content-Type", "text/html") fmt.Fprint(w, html) }) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { log.Println("Got request for:", r.URL.String()) }) go func() { url := auth.AuthURL(state) fmt.Println("Please log in to Spotify by visiting the following page in your browser:", url) // wait for auth to complete client = <-ch // use the client to make calls that require authorization user, err := client.CurrentUser(context.Background()) if err != nil { log.Fatal(err) } fmt.Println("You are logged in as:", user.ID) playerState, err = client.PlayerState(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Found your %s (%s)\n", playerState.Device.Type, playerState.Device.Name) }() http.ListenAndServe(":8080", nil) } func completeAuth(w http.ResponseWriter, r *http.Request) { tok, err := auth.Token(r.Context(), state, r) if err != nil { http.Error(w, "Couldn't get token", http.StatusForbidden) log.Fatal(err) } if st := r.FormValue("state"); st != state { http.NotFound(w, r) log.Fatalf("State mismatch: %s != %s\n", st, state) } // use the token to get an authenticated client client := spotify.New(auth.Client(r.Context(), tok)) w.Header().Set("Content-Type", "text/html") fmt.Fprintf(w, "Login Completed!"+html) ch <- client }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
examples/profile/profile.go
Go
// Command profile gets the public profile information about a Spotify user. package main import ( "context" "flag" "fmt" spotifyauth "github.com/zmb3/spotify/v2/auth" "log" "os" "golang.org/x/oauth2/clientcredentials" "github.com/zmb3/spotify/v2" ) var userID = flag.String("user", "", "the Spotify user ID to look up") func main() { flag.Parse() ctx := context.Background() if *userID == "" { fmt.Fprintf(os.Stderr, "Error: missing user ID\n") flag.Usage() return } config := &clientcredentials.Config{ ClientID: os.Getenv("SPOTIFY_ID"), ClientSecret: os.Getenv("SPOTIFY_SECRET"), TokenURL: spotifyauth.TokenURL, } token, err := config.Token(context.Background()) if err != nil { log.Fatalf("couldn't get token: %v", err) } httpClient := spotifyauth.New().Client(ctx, token) client := spotify.New(httpClient) user, err := client.GetUsersPublicProfile(ctx, spotify.ID(*userID)) if err != nil { fmt.Fprintln(os.Stderr, err.Error()) return } fmt.Println("User ID:", user.ID) fmt.Println("Display name:", user.DisplayName) fmt.Println("Spotify URI:", string(user.URI)) fmt.Println("Endpoint:", user.Endpoint) fmt.Println("Followers:", user.Followers.Count) }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
examples/recommendation/recommendation.go
Go
package main import ( "context" "fmt" "log" "os" spotifyauth "github.com/zmb3/spotify/v2/auth" "golang.org/x/oauth2/clientcredentials" "github.com/zmb3/spotify/v2" ) func main() { ctx := context.Background() config := &clientcredentials.Config{ ClientID: os.Getenv("SPOTIFY_ID"), ClientSecret: os.Getenv("SPOTIFY_SECRET"), TokenURL: spotifyauth.TokenURL, } token, err := config.Token(ctx) if err != nil { log.Fatalf("couldn't get token: %v", err) } httpClient := spotifyauth.New().Client(ctx, token) client := spotify.New(httpClient) // store artist and genre info (upto 5 seed values allowed) favorite_artists := []string{"Invent Animate", "Spiritbox", "Sleep Token"} genres := []string{"metalcore"} var artist_ids []spotify.ID // find the ID for each artist and append it to list of artist ID's for _, artist := range favorite_artists { artists, err := client.Search(ctx, artist, spotify.SearchTypeArtist) if err != nil { log.Fatal(err) } artist_ids = append(artist_ids, artists.Artists.Artists[0].ID) } // store the values in seed seeds := spotify.Seeds{ Artists: artist_ids, Genres: genres, } // declare track attributes for a more refined search track_attributes := spotify.NewTrackAttributes(). MaxValence(0.4). TargetEnergy(0.6). TargetDanceability(0.6) // get recommendations based on seed values res, err := client.GetRecommendations(ctx, seeds, track_attributes, spotify.Country("US"), spotify.Limit(10)) if err != nil { log.Fatal(err) } // display the recommended tracks along with artists fmt.Println("\t---- Recommended Tracks ----") for _, track := range res.Tracks { fmt.Println(track.Name + " by " + track.Artists[0].Name) } }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
examples/search/search.go
Go
package main import ( "context" "fmt" spotifyauth "github.com/zmb3/spotify/v2/auth" "log" "os" "golang.org/x/oauth2/clientcredentials" "github.com/zmb3/spotify/v2" ) func main() { ctx := context.Background() config := &clientcredentials.Config{ ClientID: os.Getenv("SPOTIFY_ID"), ClientSecret: os.Getenv("SPOTIFY_SECRET"), TokenURL: spotifyauth.TokenURL, } token, err := config.Token(ctx) if err != nil { log.Fatalf("couldn't get token: %v", err) } httpClient := spotifyauth.New().Client(ctx, token) client := spotify.New(httpClient) // search for playlists and albums containing "holiday" results, err := client.Search(ctx, "holiday", spotify.SearchTypePlaylist|spotify.SearchTypeAlbum) if err != nil { log.Fatal(err) } // handle album results if results.Albums != nil { fmt.Println("Albums:") for _, item := range results.Albums.Albums { fmt.Println(" ", item.Name) } } // handle playlist results if results.Playlists != nil { fmt.Println("Playlists:") for _, item := range results.Playlists.Playlists { fmt.Println(" ", item.Name) } } }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
library.go
Go
package spotify import ( "context" "errors" "fmt" "net/http" "strings" ) // UserHasTracks checks if one or more tracks are saved to the current user's // "Your Music" library. func (c *Client) UserHasTracks(ctx context.Context, ids ...ID) ([]bool, error) { return c.libraryContains(ctx, "tracks", ids...) } // UserHasAlbums checks if one or more albums are saved to the current user's // "Your Albums" library. func (c *Client) UserHasAlbums(ctx context.Context, ids ...ID) ([]bool, error) { return c.libraryContains(ctx, "albums", ids...) } func (c *Client) libraryContains(ctx context.Context, typ string, ids ...ID) ([]bool, error) { if l := len(ids); l == 0 || l > 50 { return nil, errors.New("spotify: supports 1 to 50 IDs per call") } spotifyURL := fmt.Sprintf("%sme/%s/contains?ids=%s", c.baseURL, typ, strings.Join(toStringSlice(ids), ",")) var result []bool err := c.get(ctx, spotifyURL, &result) if err != nil { return nil, err } return result, err } // AddTracksToLibrary saves one or more tracks to the current user's // "Your Music" library. This call requires the [ScopeUserLibraryModify] scope. // A track can only be saved once; duplicate IDs are ignored. func (c *Client) AddTracksToLibrary(ctx context.Context, ids ...ID) error { return c.modifyLibrary(ctx, "tracks", true, ids...) } // RemoveTracksFromLibrary removes one or more tracks from the current user's // "Your Music" library. This call requires the [ScopeUserModifyLibrary] scope. // Trying to remove a track when you do not have the user's authorization // results in an [Error] with the status code set to [net/http.StatusUnauthorized]. func (c *Client) RemoveTracksFromLibrary(ctx context.Context, ids ...ID) error { return c.modifyLibrary(ctx, "tracks", false, ids...) } // AddAlbumsToLibrary saves one or more albums to the current user's // "Your Albums" library. This call requires the [ScopeUserLibraryModify] scope. // A track can only be saved once; duplicate IDs are ignored. func (c *Client) AddAlbumsToLibrary(ctx context.Context, ids ...ID) error { return c.modifyLibrary(ctx, "albums", true, ids...) } // RemoveAlbumsFromLibrary removes one or more albums from the current user's // "Your Albums" library. This call requires the [ScopeUserModifyLibrary] scope. // Trying to remove a track when you do not have the user's authorization // results in an [Error] with the status code set to [net/http.StatusUnauthorized]. func (c *Client) RemoveAlbumsFromLibrary(ctx context.Context, ids ...ID) error { return c.modifyLibrary(ctx, "albums", false, ids...) } func (c *Client) modifyLibrary(ctx context.Context, typ string, add bool, ids ...ID) error { if l := len(ids); l == 0 || l > 50 { return errors.New("spotify: this call supports 1 to 50 IDs per call") } spotifyURL := fmt.Sprintf("%sme/%s?ids=%s", c.baseURL, typ, strings.Join(toStringSlice(ids), ",")) method := "DELETE" if add { method = "PUT" } req, err := http.NewRequestWithContext(ctx, method, spotifyURL, nil) if err != nil { return err } return c.execute(req, nil) }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
library_test.go
Go
package spotify import ( "context" "errors" "net/http" "testing" ) func TestUserHasTracks(t *testing.T) { client, server := testClientString(http.StatusOK, `[ false, true ]`) defer server.Close() contains, err := client.UserHasTracks(context.Background(), "0udZHhCi7p1YzMlvI4fXoK", "55nlbqqFVnSsArIeYSQlqx") if err != nil { t.Error(err) } if l := len(contains); l != 2 { t.Error("Expected 2 results, got", l) } if contains[0] || !contains[1] { t.Error("Expected [false, true], got", contains) } } func TestAddTracksToLibrary(t *testing.T) { client, server := testClientString(http.StatusOK, "") defer server.Close() err := client.AddTracksToLibrary(context.Background(), "4iV5W9uYEdYUVa79Axb7Rh", "1301WleyT98MSxVHPZCA6M") if err != nil { t.Error(err) } } func TestAddTracksToLibraryFailure(t *testing.T) { client, server := testClientString(http.StatusUnauthorized, ` { "error": { "status": 401, "message": "Invalid access token" } }`) defer server.Close() err := client.AddTracksToLibrary(context.Background(), "4iV5W9uYEdYUVa79Axb7Rh", "1301WleyT98MSxVHPZCA6M") if err == nil { t.Error("Expected error and didn't get one") } } func TestAddTracksToLibraryWithContextCancelled(t *testing.T) { client, server := testClientString(http.StatusOK, ``) defer server.Close() ctx, done := context.WithCancel(context.Background()) done() err := client.AddTracksToLibrary(ctx, "4iV5W9uYEdYUVa79Axb7Rh", "1301WleyT98MSxVHPZCA6M") if !errors.Is(err, context.Canceled) { t.Error("Expected error and didn't get one") } } func TestRemoveTracksFromLibrary(t *testing.T) { client, server := testClientString(http.StatusOK, "") defer server.Close() err := client.RemoveTracksFromLibrary(context.Background(), "4iV5W9uYEdYUVa79Axb7Rh", "1301WleyT98MSxVHPZCA6M") if err != nil { t.Error(err) } } func TestUserHasAlbums(t *testing.T) { client, server := testClientString(http.StatusOK, `[ false, true ]`) defer server.Close() contains, err := client.UserHasAlbums(context.Background(), "0udZHhCi7p1YzMlvI4fXoK", "55nlbqqFVnSsArIeYSQlqx") if err != nil { t.Error(err) } if l := len(contains); l != 2 { t.Error("Expected 2 results, got", l) } if contains[0] || !contains[1] { t.Error("Expected [false, true], got", contains) } } func TestAddAlbumsToLibrary(t *testing.T) { client, server := testClientString(http.StatusOK, "") defer server.Close() err := client.AddAlbumsToLibrary(context.Background(), "4iV5W9uYEdYUVa79Axb7Rh", "1301WleyT98MSxVHPZCA6M") if err != nil { t.Error(err) } } func TestAddAlbumsToLibraryFailure(t *testing.T) { client, server := testClientString(http.StatusUnauthorized, ` { "error": { "status": 401, "message": "Invalid access token" } }`) defer server.Close() err := client.AddAlbumsToLibrary(context.Background(), "4iV5W9uYEdYUVa79Axb7Rh", "1301WleyT98MSxVHPZCA6M") if err == nil { t.Error("Expected error and didn't get one") } } func TestRemoveAlbumsFromLibrary(t *testing.T) { client, server := testClientString(http.StatusOK, "") defer server.Close() err := client.RemoveAlbumsFromLibrary(context.Background(), "4iV5W9uYEdYUVa79Axb7Rh", "1301WleyT98MSxVHPZCA6M") if err != nil { t.Error(err) } }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
page.go
Go
package spotify import ( "context" "errors" "fmt" "reflect" ) // ErrNoMorePages is the error returned when you attempt to get the next // (or previous) set of data but you've reached the end of the data set. var ErrNoMorePages = errors.New("spotify: no more pages") // This file contains the types that implement Spotify's paging object. // See: https://developer.spotify.com/web-api/object-model/#paging-object // basePage contains all of the fields in a Spotify paging object, except // for the actual items. This type is meant to be embedded in other types // that add the Items field. type basePage struct { // A link to the Web API Endpoint returning the full // result of this request. Endpoint string `json:"href"` // The maximum number of items in the response, as set // in the query (or default value if unset). Limit Numeric `json:"limit"` // The offset of the items returned, as set in the query // (or default value if unset). Offset Numeric `json:"offset"` // The total number of items available to return. Total Numeric `json:"total"` // The URL to the next page of items (if available). Next string `json:"next"` // The URL to the previous page of items (if available). Previous string `json:"previous"` } // FullArtistPage contains [FullArtists] returned by the Web API. type FullArtistPage struct { basePage Artists []FullArtist `json:"items"` } // SimpleAlbumPage contains [SimpleAlbums] returned by the Web API. type SimpleAlbumPage struct { basePage Albums []SimpleAlbum `json:"items"` } // SavedAlbumPage contains [SavedAlbums] returned by the Web API. type SavedAlbumPage struct { basePage Albums []SavedAlbum `json:"items"` } // SavedShowPage contains [SavedShows] returned by the Web API type SavedShowPage struct { basePage Shows []SavedShow `json:"items"` } // SimplePlaylistPage contains [SimplePlaylists] returned by the Web API. type SimplePlaylistPage struct { basePage Playlists []SimplePlaylist `json:"items"` } // SimpleTrackPage contains [SimpleTracks] returned by the Web API. type SimpleTrackPage struct { basePage Tracks []SimpleTrack `json:"items"` } // FullTrackPage contains [FullTracks] returned by the Web API. type FullTrackPage struct { basePage Tracks []FullTrack `json:"items"` } // SavedTrackPage contains [SavedTracks] return by the Web API. type SavedTrackPage struct { basePage Tracks []SavedTrack `json:"items"` } // PlaylistTrackPage contains information about tracks in a playlist. type PlaylistTrackPage struct { basePage Tracks []PlaylistTrack `json:"items"` } // CategoryPage contains [Category] objects returned by the Web API. type CategoryPage struct { basePage Categories []Category `json:"items"` } // SimpleEpisodePage contains [EpisodePage] returned by the Web API. type SimpleEpisodePage struct { basePage Episodes []EpisodePage `json:"items"` } // SimpleShowPage contains [ShowPage] returned by the Web API. type SimpleShowPage struct { basePage Shows []FullShow `json:"items"` } // pageable is an internal interface for types that support paging // by embedding basePage. type pageable interface{ canPage() } func (b *basePage) canPage() {} // NextPage fetches the next page of items and writes them into p. // It returns [ErrNoMorePages] if p already contains the last page. func (c *Client) NextPage(ctx context.Context, p pageable) error { if p == nil || reflect.ValueOf(p).IsNil() { return fmt.Errorf("spotify: p must be a non-nil pointer to a page") } val := reflect.ValueOf(p).Elem() field := val.FieldByName("Next") nextURL := field.Interface().(string) if len(nextURL) == 0 { return ErrNoMorePages } // Zero out the page so that we can overwrite it in the next // call to get. This is necessary because encoding/json does // not clear out existing values when unmarshaling JSON null. zero := reflect.Zero(val.Type()) val.Set(zero) return c.get(ctx, nextURL, p) } // PreviousPage fetches the previous page of items and writes them into p. // It returns [ErrNoMorePages] if p already contains the last page. func (c *Client) PreviousPage(ctx context.Context, p pageable) error { if p == nil || reflect.ValueOf(p).IsNil() { return fmt.Errorf("spotify: p must be a non-nil pointer to a page") } val := reflect.ValueOf(p).Elem() field := val.FieldByName("Previous") prevURL := field.Interface().(string) if len(prevURL) == 0 { return ErrNoMorePages } // Zero out the page so that we can overwrite it in the next // call to get. This is necessary because encoding/json does // not clear out existing values when unmarshaling JSON null. zero := reflect.Zero(val.Type()) val.Set(zero) return c.get(ctx, prevURL, p) }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
page_test.go
Go
package spotify import ( "context" "errors" "github.com/stretchr/testify/assert" "net/http" "testing" ) func TestClient_NextPage(t *testing.T) { testTable := []struct { Name string Input *basePage ExpectedPath string Err error }{ { "success", &basePage{ Next: "/v1/albums/0sNOF9WDwhWunNAHPD3Baj/tracks", Total: 600, }, "/v1/albums/0sNOF9WDwhWunNAHPD3Baj/tracks", nil, }, { "no more pages", &basePage{ Next: "", }, "", ErrNoMorePages, }, { "nil pointer error", nil, "", errors.New("spotify: p must be a non-nil pointer to a page"), }, } for _, tt := range testTable { t.Run(tt.Name, func(t *testing.T) { wasCalled := false client, server := testClientString(200, `{"total": 100}`, func(request *http.Request) { wasCalled = true assert.Equal(t, tt.ExpectedPath, request.URL.RequestURI()) }) if tt.Input != nil && tt.Input.Next != "" { tt.Input.Next = server.URL + tt.Input.Next // add fake server url so we intercept the message } err := client.NextPage(context.Background(), tt.Input) assert.Equal(t, tt.ExpectedPath != "", wasCalled) if tt.Err == nil { assert.NoError(t, err) assert.Equal(t, 100, int(tt.Input.Total)) // value should be from original 600 } else { assert.EqualError(t, err, tt.Err.Error()) } }) } } func TestClient_PreviousPage(t *testing.T) { testTable := []struct { Name string Input *basePage ExpectedPath string Err error }{ { "success", &basePage{ Previous: "/v1/albums/0sNOF9WDwhWunNAHPD3Baj/tracks", Total: 600, }, "/v1/albums/0sNOF9WDwhWunNAHPD3Baj/tracks", nil, }, { "no more pages", &basePage{ Previous: "", }, "", ErrNoMorePages, }, { "nil pointer error", nil, "", errors.New("spotify: p must be a non-nil pointer to a page"), }, } for _, tt := range testTable { t.Run(tt.Name, func(t *testing.T) { wasCalled := false client, server := testClientString(200, `{"total": 100}`, func(request *http.Request) { wasCalled = true assert.Equal(t, tt.ExpectedPath, request.URL.RequestURI()) }) if tt.Input != nil && tt.Input.Previous != "" { tt.Input.Previous = server.URL + tt.Input.Previous // add fake server url so we intercept the message } err := client.PreviousPage(context.Background(), tt.Input) assert.Equal(t, tt.ExpectedPath != "", wasCalled) if tt.Err == nil { assert.NoError(t, err) assert.Equal(t, 100, int(tt.Input.Total)) // value should be from original 600 } else { assert.EqualError(t, err, tt.Err.Error()) } }) } }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
player.go
Go
package spotify import ( "bytes" "context" "encoding/json" "net/http" "net/url" "strconv" "time" ) // PlayerDevice contains information about a device that a user can play music on. type PlayerDevice struct { // ID of the device. This may be empty. ID ID `json:"id"` // Active If this device is the currently active device. Active bool `json:"is_active"` // Restricted Whether controlling this device is restricted. At present if // this is "true" then no Web API commands will be accepted by this device. Restricted bool `json:"is_restricted"` // Name The name of the device. Name string `json:"name"` // Type of device, such as "Computer", "Smartphone" or "Speaker". Type string `json:"type"` // Volume The current volume in percent. Volume Numeric `json:"volume_percent"` } // PlayerState contains information about the current playback. type PlayerState struct { CurrentlyPlaying // Device The device that is currently active Device PlayerDevice `json:"device"` // ShuffleState Shuffle is on or off ShuffleState bool `json:"shuffle_state"` // RepeatState off, track, context RepeatState string `json:"repeat_state"` } // PlaybackContext is the playback context. type PlaybackContext struct { // ExternalURLs of the context, or null if not available. ExternalURLs map[string]string `json:"external_urls"` // Endpoint of the context, or null if not available. Endpoint string `json:"href"` // Type of the item's context. Can be one of album, artist or playlist. Type string `json:"type"` // URI is the Spotify URI for the context. URI URI `json:"uri"` } // CurrentlyPlaying contains the information about currently playing items. type CurrentlyPlaying struct { // Timestamp when data was fetched Timestamp int64 `json:"timestamp"` // PlaybackContext current context PlaybackContext PlaybackContext `json:"context"` // Progress into the currently playing track. Progress Numeric `json:"progress_ms"` // Playing If something is currently playing. Playing bool `json:"is_playing"` // The currently playing track. Can be null. Item *FullTrack `json:"item"` } type RecentlyPlayedItem struct { // Track is the track information Track SimpleTrack `json:"track"` // PlayedAt is the time that this song was played PlayedAt time.Time `json:"played_at"` // PlaybackContext is the current playback context PlaybackContext PlaybackContext `json:"context"` } type RecentlyPlayedResult struct { Items []RecentlyPlayedItem `json:"items"` } // PlaybackOffset can be specified either by track URI or Position. If the // Position field is set to a non-nil pointer, it will be taken into // consideration when specifying the playback offset. If the Position field is // set to a nil pointer, it will be ignored and only the URI will be used to // specify the offset. If both are present the request will return 400 BAD // REQUEST. If incorrect values are provided for position or uri, the request // may be accepted but with an unpredictable resulting action on playback. type PlaybackOffset struct { // Position is zero based and can’t be negative. Position *int `json:"position,omitempty"` // URI is a string representing the uri of the item to start at. URI URI `json:"uri,omitempty"` } type PlayOptions struct { // DeviceID The id of the device this command is targeting. If not // supplied, the user's currently active device is the target. DeviceID *ID `json:"-"` // PlaybackContext Spotify URI of the context to play. // Valid contexts are albums, artists & playlists. PlaybackContext *URI `json:"context_uri,omitempty"` // URIs Array of the Spotify track URIs to play. URIs []URI `json:"uris,omitempty"` // PlaybackOffset Indicates from where in the context playback should start. // Only available when context corresponds to an album or playlist // object, or when the URIs parameter is used. PlaybackOffset *PlaybackOffset `json:"offset,omitempty"` // PositionMs Indicates from what position to start playback. // Must be a positive number. Passing in a position that is greater // than the length of the track will cause the player to start playing the next song. // Defaults to 0, starting a track from the beginning. PositionMs Numeric `json:"position_ms,omitempty"` } // RecentlyPlayedOptions describes options for the recently-played request. All // fields are optional. Only one of AfterEpochMs and BeforeEpochMs may be // given. // // Note: it seems as if Spotify only remembers the fifty most-recent tracks. type RecentlyPlayedOptions struct { // Limit is the maximum number of items to return. Must be no greater than // fifty. Limit Numeric // AfterEpochMs is a Unix epoch in milliseconds that describes a time after // which to return songs. AfterEpochMs int64 // BeforeEpochMs is a Unix epoch in milliseconds that describes a time // before which to return songs. BeforeEpochMs int64 } type Queue struct { CurrentlyPlaying FullTrack `json:"currently_playing"` Items []FullTrack `json:"queue"` } // PlayerDevices information about available devices for the current user. // // Requires the [ScopeUserReadPlaybackState] scope in order to read information func (c *Client) PlayerDevices(ctx context.Context) ([]PlayerDevice, error) { var result struct { PlayerDevices []PlayerDevice `json:"devices"` } err := c.get(ctx, c.baseURL+"me/player/devices", &result) if err != nil { return nil, err } return result.PlayerDevices, nil } // PlayerState gets information about the playing state for the current user // Requires the [ScopeUserReadPlaybackState] scope in order to read information // // Supported options: [Market]. func (c *Client) PlayerState(ctx context.Context, opts ...RequestOption) (*PlayerState, error) { spotifyURL := c.baseURL + "me/player" if params := processOptions(opts...).urlParams.Encode(); params != "" { spotifyURL += "?" + params } var result PlayerState err := c.get(ctx, spotifyURL, &result) if err != nil { return nil, err } return &result, nil } // PlayerCurrentlyPlaying gets information about the currently playing status // for the current user. // // Requires the [ScopeUserReadCurrentlyPlaying] scope or the [ScopeUserReadPlaybackState] // scope in order to read information. // // Supported options: [Market]. func (c *Client) PlayerCurrentlyPlaying(ctx context.Context, opts ...RequestOption) (*CurrentlyPlaying, error) { spotifyURL := c.baseURL + "me/player/currently-playing" if params := processOptions(opts...).urlParams.Encode(); params != "" { spotifyURL += "?" + params } req, err := http.NewRequestWithContext(ctx, "GET", spotifyURL, nil) if err != nil { return nil, err } var result CurrentlyPlaying err = c.execute(req, &result, http.StatusNoContent) if err != nil { return nil, err } return &result, nil } // PlayerRecentlyPlayed gets a list of recently-played tracks for the current // user. This call requires [ScopeUserReadRecentlyPlayed]. func (c *Client) PlayerRecentlyPlayed(ctx context.Context) ([]RecentlyPlayedItem, error) { return c.PlayerRecentlyPlayedOpt(ctx, nil) } // PlayerRecentlyPlayedOpt is like [PlayerRecentlyPlayed], but it accepts // additional options for sorting and filtering the results. func (c *Client) PlayerRecentlyPlayedOpt(ctx context.Context, opt *RecentlyPlayedOptions) ([]RecentlyPlayedItem, error) { spotifyURL := c.baseURL + "me/player/recently-played" if opt != nil { v := url.Values{} if opt.Limit != 0 { v.Set("limit", strconv.FormatInt(int64(opt.Limit), 10)) } if opt.BeforeEpochMs != 0 { v.Set("before", strconv.FormatInt(int64(opt.BeforeEpochMs), 10)) } if opt.AfterEpochMs != 0 { v.Set("after", strconv.FormatInt(int64(opt.AfterEpochMs), 10)) } if params := v.Encode(); params != "" { spotifyURL += "?" + params } } result := RecentlyPlayedResult{} err := c.get(ctx, spotifyURL, &result) if err != nil { return nil, err } return result.Items, nil } // TransferPlayback transfers playback to a new device and determine if // it should start playing. // // Note that a value of false for the play parameter when also transferring // to another device_id will not pause playback. To ensure that playback is // paused on the new device you should send a pause command to the currently // active device before transferring to the new device_id. // // Requires the [ScopeUserModifyPlaybackState] in order to modify the player state. func (c *Client) TransferPlayback(ctx context.Context, deviceID ID, play bool) error { reqData := struct { DeviceID []ID `json:"device_ids"` Play bool `json:"play"` }{ DeviceID: []ID{deviceID}, Play: play, } buf := new(bytes.Buffer) err := json.NewEncoder(buf).Encode(reqData) if err != nil { return err } req, err := http.NewRequestWithContext(ctx, http.MethodPut, c.baseURL+"me/player", buf) if err != nil { return err } return c.execute(req, nil, http.StatusAccepted, http.StatusNoContent, ) } // Play Start a new context or resume current playback on the user's active // device. This call requires [ScopeUserModifyPlaybackState] in order to modify the player state. func (c *Client) Play(ctx context.Context) error { return c.PlayOpt(ctx, nil) } // PlayOpt is like [Play] but with more options. func (c *Client) PlayOpt(ctx context.Context, opt *PlayOptions) error { spotifyURL := c.baseURL + "me/player/play" buf := new(bytes.Buffer) if opt != nil { v := url.Values{} if opt.DeviceID != nil { v.Set("device_id", opt.DeviceID.String()) } if params := v.Encode(); params != "" { spotifyURL += "?" + params } err := json.NewEncoder(buf).Encode(opt) if err != nil { return err } } req, err := http.NewRequestWithContext(ctx, http.MethodPut, spotifyURL, buf) if err != nil { return err } return c.execute(req, nil, http.StatusAccepted, http.StatusNoContent, ) } // Pause Playback on the user's currently active device. // // Requires the [ScopeUserModifyPlaybackState] in order to modify the player state. func (c *Client) Pause(ctx context.Context) error { return c.PauseOpt(ctx, nil) } // PauseOpt is like [Pause] but with more options. // // Only expects [PlayOptions.DeviceID], all other options will be ignored. func (c *Client) PauseOpt(ctx context.Context, opt *PlayOptions) error { spotifyURL := c.baseURL + "me/player/pause" if opt != nil { v := url.Values{} if opt.DeviceID != nil { v.Set("device_id", opt.DeviceID.String()) } if params := v.Encode(); params != "" { spotifyURL += "?" + params } } req, err := http.NewRequestWithContext(ctx, http.MethodPut, spotifyURL, nil) if err != nil { return err } return c.execute(req, nil, http.StatusAccepted, http.StatusNoContent, ) } // GetQueue gets the user's queue on the user's currently // active device. This call requires [ScopeUserReadPlaybackState] func (c *Client) GetQueue(ctx context.Context) (*Queue, error) { spotifyURL := c.baseURL + "me/player/queue" v := url.Values{} if params := v.Encode(); params != "" { spotifyURL += "?" + params } var q Queue err := c.get(ctx, spotifyURL, &q) if err != nil { return nil, err } return &q, nil } // QueueSong adds a song to the user's queue on the user's currently // active device. This call requires [ScopeUserModifyPlaybackState] // to modify the player state func (c *Client) QueueSong(ctx context.Context, trackID ID) error { return c.QueueSongOpt(ctx, trackID, nil) } // QueueSongOpt is like [QueueSong] but with more options. // // Only expects [PlayOptions.DeviceID], all other options will be ignored. func (c *Client) QueueSongOpt(ctx context.Context, trackID ID, opt *PlayOptions) error { uri := "spotify:track:" + trackID spotifyURL := c.baseURL + "me/player/queue" v := url.Values{} v.Set("uri", uri.String()) if opt != nil { if opt.DeviceID != nil { v.Set("device_id", opt.DeviceID.String()) } } if params := v.Encode(); params != "" { spotifyURL += "?" + params } req, err := http.NewRequestWithContext(ctx, http.MethodPost, spotifyURL, nil) if err != nil { return err } req.Header.Set("Content-Type", "application/json") return c.execute(req, nil, http.StatusAccepted, http.StatusNoContent, ) } // Next skips to the next track in the user's queue in the user's // currently active device. This call requires [ScopeUserModifyPlaybackState] // in order to modify the player state. func (c *Client) Next(ctx context.Context) error { return c.NextOpt(ctx, nil) } // NextOpt is like Next but with more options. // // Only expects [PlayOptions.DeviceID], all other options will be ignored. func (c *Client) NextOpt(ctx context.Context, opt *PlayOptions) error { spotifyURL := c.baseURL + "me/player/next" if opt != nil { v := url.Values{} if opt.DeviceID != nil { v.Set("device_id", opt.DeviceID.String()) } if params := v.Encode(); params != "" { spotifyURL += "?" + params } } req, err := http.NewRequestWithContext(ctx, http.MethodPost, spotifyURL, nil) if err != nil { return err } return c.execute(req, nil, http.StatusAccepted, http.StatusNoContent, ) } // Previous skips to the previous track in the user's queue on the user's // currently active device. This call requires [ScopeUserModifyPlaybackState] // in order to modify the player state func (c *Client) Previous(ctx context.Context) error { return c.PreviousOpt(ctx, nil) } // PreviousOpt is like [Previous] but with more options. // // Only expects [PlayOptions.DeviceID], all other options will be ignored. func (c *Client) PreviousOpt(ctx context.Context, opt *PlayOptions) error { spotifyURL := c.baseURL + "me/player/previous" if opt != nil { v := url.Values{} if opt.DeviceID != nil { v.Set("device_id", opt.DeviceID.String()) } if params := v.Encode(); params != "" { spotifyURL += "?" + params } } req, err := http.NewRequestWithContext(ctx, http.MethodPost, spotifyURL, nil) if err != nil { return err } return c.execute(req, nil, http.StatusAccepted, http.StatusNoContent, ) } // Seek to the given position in the user’s currently playing track. // // The position in milliseconds to seek to. Must be a positive number. // Passing in a position that is greater than the length of the track // will cause the player to start playing the next song. // // Requires the [ScopeUserModifyPlaybackState] in order to modify the player state. func (c *Client) Seek(ctx context.Context, position int) error { return c.SeekOpt(ctx, position, nil) } // SeekOpt is like [Seek] but with more options. // // Only expects [PlayOptions.DeviceID], all other options will be ignored. func (c *Client) SeekOpt(ctx context.Context, position int, opt *PlayOptions) error { return c.playerFuncWithOpt( ctx, "me/player/seek", url.Values{ "position_ms": []string{strconv.FormatInt(int64(position), 10)}, }, opt, ) } // Repeat Set the repeat mode for the user's playback. // // Options are track, context, and off. // // Requires the ScopeUserModifyPlaybackState in order to modify the player state. func (c *Client) Repeat(ctx context.Context, state string) error { return c.RepeatOpt(ctx, state, nil) } // RepeatOpt is like [Repeat] but with more options. // // Only expects [PlayOptions.DeviceID], all other options will be ignored. func (c *Client) RepeatOpt(ctx context.Context, state string, opt *PlayOptions) error { return c.playerFuncWithOpt( ctx, "me/player/repeat", url.Values{ "state": []string{state}, }, opt, ) } // Volume set the volume for the user's current playback device. // // Percent is must be a value from 0 to 100 inclusive. // // Requires the [ScopeUserModifyPlaybackState] in order to modify the player state. func (c *Client) Volume(ctx context.Context, percent int) error { return c.VolumeOpt(ctx, percent, nil) } // VolumeOpt is like [Volume] but with more options. // // Only expects [PlayOptions.DeviceID], all other options will be ignored. func (c *Client) VolumeOpt(ctx context.Context, percent int, opt *PlayOptions) error { return c.playerFuncWithOpt( ctx, "me/player/volume", url.Values{ "volume_percent": []string{strconv.FormatInt(int64(percent), 10)}, }, opt, ) } // Shuffle switches shuffle on or off for user's playback. // // Requires the [ScopeUserModifyPlaybackState] in order to modify the player state. func (c *Client) Shuffle(ctx context.Context, shuffle bool) error { return c.ShuffleOpt(ctx, shuffle, nil) } // ShuffleOpt is like [Shuffle] but with more options. // // Only expects [PlayOptions.DeviceID], all other options will be ignored. func (c *Client) ShuffleOpt(ctx context.Context, shuffle bool, opt *PlayOptions) error { return c.playerFuncWithOpt( ctx, "me/player/shuffle", url.Values{ "state": []string{strconv.FormatBool(shuffle)}, }, opt, ) } func (c *Client) playerFuncWithOpt(ctx context.Context, urlSuffix string, values url.Values, opt *PlayOptions) error { spotifyURL := c.baseURL + urlSuffix if opt != nil { if opt.DeviceID != nil { values.Set("device_id", opt.DeviceID.String()) } } if params := values.Encode(); params != "" { spotifyURL += "?" + params } req, err := http.NewRequestWithContext(ctx, http.MethodPut, spotifyURL, nil) if err != nil { return err } return c.execute(req, nil, http.StatusAccepted, http.StatusNoContent, ) }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
player_test.go
Go
package spotify import ( "context" "net/http" "testing" ) func TestTransferPlaybackDeviceUnavailable(t *testing.T) { client, server := testClientString(http.StatusNotFound, "") defer server.Close() err := client.TransferPlayback(context.Background(), "newdevice", false) if err == nil { t.Error("expected error since auto retry is disabled") } } func TestTransferPlayback(t *testing.T) { client, server := testClientString(http.StatusNoContent, "") defer server.Close() err := client.TransferPlayback(context.Background(), "newdevice", true) if err != nil { t.Error(err) } } func TestVolume(t *testing.T) { client, server := testClientString(http.StatusNoContent, "") defer server.Close() err := client.Volume(context.Background(), 50) if err != nil { t.Error(err) } } func TestQueue(t *testing.T) { client, server := testClientString(http.StatusNoContent, "") defer server.Close() err := client.QueueSong(context.Background(), "4JpKVNYnVcJ8tuMKjAj50A") if err != nil { t.Error(err) } } func TestPlayerDevices(t *testing.T) { client, server := testClientFile(http.StatusOK, "test_data/player_available_devices.txt") defer server.Close() list, err := client.PlayerDevices(context.Background()) if err != nil { t.Error(err) return } if len(list) != 2 { t.Error("Expected two devices") } if list[0].Volume != 100 { t.Error("Expected volume to be 100 percent") } if list[1].Volume != 0 { t.Error("Expected null becomes 0") } } func TestPlayerState(t *testing.T) { client, server := testClientFile(http.StatusOK, "test_data/player_state.txt") defer server.Close() state, err := client.PlayerState(context.Background()) if err != nil { t.Error(err) return } if len(state.PlaybackContext.ExternalURLs) != 1 { t.Error("Expected one external url") } if state.Item == nil { t.Error("Expected item to be a track") } if state.Timestamp != 1491302708055 { t.Error("Expected timestamp to be 1491302708055") } if state.Progress != 102509 { t.Error("Expected progress to be 102509") } if state.Playing { t.Error("Expected not to be playing") } } func TestPlayerCurrentlyPlaying(t *testing.T) { client, server := testClientFile(http.StatusOK, "test_data/player_currently_playing.txt") defer server.Close() state, err := client.PlayerCurrentlyPlaying(context.Background()) if err != nil { t.Error(err) return } if len(state.PlaybackContext.ExternalURLs) != 1 { t.Error("Expected one external url") } if state.Item == nil { t.Error("Expected item to be a track") } if state.Timestamp != 1491302708055 { t.Error("Expected timestamp to be 1491302708055") } if state.Progress != 102509 { t.Error("Expected progress to be 102509") } if state.Playing { t.Error("Expected not to be playing") } } func TestPlayerRecentlyPlayed(t *testing.T) { client, server := testClientFile(http.StatusOK, "test_data/player_recently_played.txt") defer server.Close() items, err := client.PlayerRecentlyPlayed(context.Background()) if err != nil { t.Fatal(err) } if len(items) != 20 { t.Error("Too few or too many items were returned") } actualTimePhrase := items[0].PlayedAt.Format("2006-01-02T15:04:05.999Z") expectedTimePhrase := "2017-05-27T20:07:54.721Z" if actualTimePhrase != expectedTimePhrase { t.Errorf("Time of first track was not parsed correctly: [%s] != [%s]", actualTimePhrase, expectedTimePhrase) } actualAlbumName := items[0].Track.Album.Name expectedAlbumName := "Immortalized" if actualAlbumName != expectedAlbumName { t.Errorf("Album name of first track was not parsed correctly: [%s] != [%s]", actualAlbumName, expectedAlbumName) } } func TestPlayArgsError(t *testing.T) { json := `{ "error" : { "status" : 400, "message" : "Only one of either \"context_uri\" or \"uris\" can be specified" } }` client, server := testClientString(http.StatusUnauthorized, json) defer server.Close() err := client.Play(context.Background()) if err == nil { t.Error("Expected an error") } } func TestGetQueue(t *testing.T) { client, server := testClientFile(http.StatusOK, "test_data/get_queue.txt") defer server.Close() queue, err := client.GetQueue(context.Background()) if err != nil { t.Error(err) } if l := len(queue.Items); l == 0 { t.Fatal("Didn't get any results") } else if l != 20 { t.Errorf("Got %d playlists, expected 20\n", l) } p := queue.Items[0].SimpleTrack if p.Name != "This Is the End (For You My Friend)" { t.Error("Expected 'This Is the End (For You My Friend)', got", p.Name) } p = queue.CurrentlyPlaying.SimpleTrack if p.Name != "Know Your Enemy" { t.Error("Expected 'Know Your Enemy', got", p.Name) } }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
playlist.go
Go
package spotify import ( "bytes" "context" "encoding/base64" "encoding/json" "fmt" "io" "net/http" "strconv" "strings" ) // PlaylistTracks contains details about the tracks in a playlist. type PlaylistTracks struct { // A link to the Web API endpoint where full details of // the playlist's tracks can be retrieved. Endpoint string `json:"href"` // The total number of tracks in the playlist. Total Numeric `json:"total"` } // SimplePlaylist contains basic info about a Spotify playlist. type SimplePlaylist struct { // Indicates whether the playlist owner allows others to modify the playlist. // Note: only non-collaborative playlists are currently returned by Spotify's Web API. Collaborative bool `json:"collaborative"` // The playlist description. Empty string if no description is set. Description string `json:"description"` ExternalURLs map[string]string `json:"external_urls"` // A link to the Web API endpoint providing full details of the playlist. Endpoint string `json:"href"` ID ID `json:"id"` // The playlist image. Note: this field is only returned for modified, // verified playlists. Otherwise the slice is empty. If returned, the source // URL for the image is temporary and will expire in less than a day. Images []Image `json:"images"` Name string `json:"name"` Owner User `json:"owner"` IsPublic bool `json:"public"` // The version identifier for the current playlist. Can be supplied in other // requests to target a specific playlist version. SnapshotID string `json:"snapshot_id"` // A collection to the Web API endpoint where full details of the playlist's // tracks can be retrieved, along with the total number of tracks in the playlist. Tracks PlaylistTracks `json:"tracks"` URI URI `json:"uri"` } // FullPlaylist provides extra playlist data in addition to the data provided by [SimplePlaylist]. type FullPlaylist struct { SimplePlaylist // Information about the followers of this playlist. Followers Followers `json:"followers"` Tracks PlaylistTrackPage `json:"tracks"` } // FeaturedPlaylists gets a [list of playlists featured by Spotify]. // // Supported options: [Locale], [Country], [Timestamp], [Limit], [Offset]. // // [list of playlists featured by Spotify]: https://developer.spotify.com/documentation/web-api/reference/get-featured-playlists func (c *Client) FeaturedPlaylists(ctx context.Context, opts ...RequestOption) (message string, playlists *SimplePlaylistPage, e error) { spotifyURL := c.baseURL + "browse/featured-playlists" if params := processOptions(opts...).urlParams.Encode(); params != "" { spotifyURL += "?" + params } var result struct { Playlists SimplePlaylistPage `json:"playlists"` Message string `json:"message"` } err := c.get(ctx, spotifyURL, &result) if err != nil { return "", nil, err } return result.Message, &result.Playlists, nil } // FollowPlaylist [adds the current user as a follower] of the specified // playlist. Any playlist can be followed, regardless of its private/public // status, as long as you know the playlist ID. // // If the public argument is true, then the playlist will be included in the // user's public playlists. To be able to follow playlists privately, the user // must have granted the [ScopePlaylistModifyPrivate] scope. The // [ScopePlaylistModifyPublic] scope is required to follow playlists publicly. // // [adds the current user as a follower]: https://developer.spotify.com/documentation/web-api/reference/follow-playlist func (c *Client) FollowPlaylist(ctx context.Context, playlist ID, public bool) error { spotifyURL := buildFollowURI(c.baseURL, playlist) body := strings.NewReader(strconv.FormatBool(public)) req, err := http.NewRequestWithContext(ctx, "PUT", spotifyURL, body) if err != nil { return err } req.Header.Set("Content-Type", "application/json") return c.execute(req, nil) } // UnfollowPlaylist [removes the current user as a follower of a playlist]. // Unfollowing a publicly followed playlist requires [ScopePlaylistModifyPublic]. // Unfolowing a privately followed playlist requies [ScopePlaylistModifyPrivate]. // // [removes the current user as a follower of a playlist]: https://developer.spotify.com/documentation/web-api/reference/unfollow-playlist func (c *Client) UnfollowPlaylist(ctx context.Context, playlist ID) error { spotifyURL := buildFollowURI(c.baseURL, playlist) req, err := http.NewRequestWithContext(ctx, "DELETE", spotifyURL, nil) if err != nil { return err } return c.execute(req, nil) } func buildFollowURI(url string, playlist ID) string { return fmt.Sprintf("%splaylists/%s/followers", url, string(playlist)) } // GetPlaylistsForUser [gets a list of the playlists] owned or followed by a // particular Spotify user. // // Private playlists and collaborative playlists are only retrievable for the // current user. In order to read private playlists, the user must have granted // the [ScopePlaylistReadPrivate] scope. Note that this scope alone will not // return collaborative playlists, even though they are always private. In // order to read collaborative playlists, the user must have granted the // [ScopePlaylistReadCollaborative] scope. // // Supported options: [Limit], [Offset]. // // [gets a list of the playlists]: https://developer.spotify.com/documentation/web-api/reference/get-list-users-playlists func (c *Client) GetPlaylistsForUser(ctx context.Context, userID string, opts ...RequestOption) (*SimplePlaylistPage, error) { spotifyURL := c.baseURL + "users/" + userID + "/playlists" if params := processOptions(opts...).urlParams.Encode(); params != "" { spotifyURL += "?" + params } var result SimplePlaylistPage err := c.get(ctx, spotifyURL, &result) if err != nil { return nil, err } return &result, err } // GetPlaylist [fetches a playlist] from spotify. // // Supported options: [Fields]. // // [fetches a playlist]: https://developer.spotify.com/documentation/web-api/reference/get-playlist func (c *Client) GetPlaylist(ctx context.Context, playlistID ID, opts ...RequestOption) (*FullPlaylist, error) { spotifyURL := fmt.Sprintf("%splaylists/%s", c.baseURL, playlistID) if params := processOptions(opts...).urlParams.Encode(); params != "" { spotifyURL += "?" + params } var playlist FullPlaylist err := c.get(ctx, spotifyURL, &playlist) if err != nil { return nil, err } return &playlist, err } // GetPlaylistTracks [gets full details of the tracks in a playlist], given the // playlist's Spotify ID. // // Supported options: [Limit], [Offset], [Market], [Fields]. // // Deprecated: the Spotify api is moving towards supporting both tracks and episodes. Use [GetPlaylistItems] which // supports these. func (c *Client) GetPlaylistTracks( ctx context.Context, playlistID ID, opts ...RequestOption, ) (*PlaylistTrackPage, error) { spotifyURL := fmt.Sprintf("%splaylists/%s/tracks", c.baseURL, playlistID) if params := processOptions(opts...).urlParams.Encode(); params != "" { spotifyURL += "?" + params } var result PlaylistTrackPage err := c.get(ctx, spotifyURL, &result) if err != nil { return nil, err } return &result, nil } // PlaylistItem contains info about an item in a playlist. type PlaylistItem struct { // The date and time the track was added to the playlist. // You can use [TimestampLayout] to convert // this field to a [time.Time]. // Warning: very old playlists may not populate this value. AddedAt string `json:"added_at"` // The Spotify user who added the track to the playlist. // Warning: very old playlists may not populate this value. AddedBy User `json:"added_by"` // Whether this track is a local file or not. IsLocal bool `json:"is_local"` // Information about the track. Track PlaylistItemTrack `json:"track"` } // PlaylistItemTrack is a union type for both tracks and episodes. If both // values are null, it's likely that the piece of content is not available in // the configured market. type PlaylistItemTrack struct { Track *FullTrack Episode *EpisodePage } // UnmarshalJSON customises the unmarshalling based on the type flags set. func (t *PlaylistItemTrack) UnmarshalJSON(b []byte) error { // Spotify API will return `track: null`` where the content is not available // in the specified market. We should respect this and just pass the null // up... if bytes.Equal(b, []byte("null")) { return nil } itemType := struct { Type string `json:"type"` }{} err := json.Unmarshal(b, &itemType) if err != nil { return err } switch itemType.Type { case "episode": return json.Unmarshal(b, &t.Episode) case "track": return json.Unmarshal(b, &t.Track) default: return fmt.Errorf("unrecognized item type: %s", itemType.Type) } } // PlaylistItemPage contains information about items in a playlist. type PlaylistItemPage struct { basePage Items []PlaylistItem `json:"items"` } // GetPlaylistItems [gets full details of the items in a playlist], given the // playlist's [Spotify ID]. // // Supported options: [Limit], [Offset], [Market], [Fields]. // // [gets full details of the items in a playlist]: https://developer.spotify.com/documentation/web-api/reference/get-playlists-tracks // [Spotify ID]: https://developer.spotify.com/documentation/web-api/#spotify-uris-and-ids func (c *Client) GetPlaylistItems(ctx context.Context, playlistID ID, opts ...RequestOption) (*PlaylistItemPage, error) { spotifyURL := fmt.Sprintf("%splaylists/%s/tracks", c.baseURL, playlistID) // Add default as the first option so it gets override by url.Values#Set opts = append([]RequestOption{AdditionalTypes(EpisodeAdditionalType, TrackAdditionalType)}, opts...) if params := processOptions(opts...).urlParams.Encode(); params != "" { spotifyURL += "?" + params } var result PlaylistItemPage err := c.get(ctx, spotifyURL, &result) if err != nil { return nil, err } return &result, nil } // CreatePlaylistForUser [creates a playlist] for a Spotify user. // The playlist will be empty until you add tracks to it. // The playlistName does not need to be unique - a user can have // several playlists with the same name. // // Creating a public playlist for a user requires [ScopePlaylistModifyPublic]; // creating a private playlist requires [ScopePlaylistModifyPrivate]. // // On success, the newly created playlist is returned. // // [creates a playlist]: https://developer.spotify.com/documentation/web-api/reference/create-playlist func (c *Client) CreatePlaylistForUser(ctx context.Context, userID, playlistName, description string, public bool, collaborative bool) (*FullPlaylist, error) { spotifyURL := fmt.Sprintf("%susers/%s/playlists", c.baseURL, userID) body := struct { Name string `json:"name"` Public bool `json:"public"` Description string `json:"description"` Collaborative bool `json:"collaborative"` }{ playlistName, public, description, collaborative, } bodyJSON, err := json.Marshal(body) if err != nil { return nil, err } req, err := http.NewRequestWithContext(ctx, "POST", spotifyURL, bytes.NewReader(bodyJSON)) if err != nil { return nil, err } req.Header.Set("Content-Type", "application/json") var p FullPlaylist err = c.execute(req, &p, http.StatusCreated) if err != nil { return nil, err } return &p, nil } // ChangePlaylistName [changes the name of a playlist]. This call requires that the // user has authorized the [ScopePlaylistModifyPublic] or [ScopePlaylistModifyPrivate] // scopes (depending on whether the playlist is public or private). // The current user must own the playlist in order to modify it. // // [changes the name of a playlist]: https://developer.spotify.com/documentation/web-api/reference/change-playlist-details func (c *Client) ChangePlaylistName(ctx context.Context, playlistID ID, newName string) error { return c.modifyPlaylist(ctx, playlistID, newName, "", nil) } // ChangePlaylistAccess [modifies the public/private status of a playlist]. This call // requires that the user has authorized the [ScopePlaylistModifyPublic] or // [ScopePlaylistModifyPrivate] scopes (depending on whether the playlist is // currently public or private). The current user must own the playlist to modify it. // // [modifies the public/private status of a playlist]: https://developer.spotify.com/documentation/web-api/reference/change-playlist-details func (c *Client) ChangePlaylistAccess(ctx context.Context, playlistID ID, public bool) error { return c.modifyPlaylist(ctx, playlistID, "", "", &public) } // ChangePlaylistDescription [modifies the description of a playlist]. This call // requires that the user has authorized the [ScopePlaylistModifyPublic] or // [ScopePlaylistModifyPrivate] scopes (depending on whether the playlist is // currently public or private). The current user must own the playlist to modify it. // // [modifies the description of a playlist]: https://developer.spotify.com/documentation/web-api/reference/change-playlist-details func (c *Client) ChangePlaylistDescription(ctx context.Context, playlistID ID, newDescription string) error { return c.modifyPlaylist(ctx, playlistID, "", newDescription, nil) } // ChangePlaylistNameAndAccess combines [ChangePlaylistName] and [ChangePlaylistAccess] into // a single Web API call. It requires that the user has authorized the [ScopePlaylistModifyPublic] // or [ScopePlaylistModifyPrivate] scopes (depending on whether the playlist is currently // public or private). The current user must own the playlist to modify it. func (c *Client) ChangePlaylistNameAndAccess(ctx context.Context, playlistID ID, newName string, public bool) error { return c.modifyPlaylist(ctx, playlistID, newName, "", &public) } // ChangePlaylistNameAccessAndDescription combines [ChangePlaylistName], [ChangePlaylistAccess], and // [ChangePlaylistDescription] into a single Web API call. It requires that the user has authorized // the [ScopePlaylistModifyPublic] or [ScopePlaylistModifyPrivate] scopes (depending on whether the // playlist is currently public or private). The current user must own the playlist in order to modify it. func (c *Client) ChangePlaylistNameAccessAndDescription(ctx context.Context, playlistID ID, newName, newDescription string, public bool) error { return c.modifyPlaylist(ctx, playlistID, newName, newDescription, &public) } func (c *Client) modifyPlaylist(ctx context.Context, playlistID ID, newName, newDescription string, public *bool) error { body := struct { Name string `json:"name,omitempty"` Public *bool `json:"public,omitempty"` Description string `json:"description,omitempty"` }{ newName, public, newDescription, } bodyJSON, err := json.Marshal(body) if err != nil { return err } spotifyURL := fmt.Sprintf("%splaylists/%s", c.baseURL, string(playlistID)) req, err := http.NewRequestWithContext(ctx, "PUT", spotifyURL, bytes.NewReader(bodyJSON)) if err != nil { return err } req.Header.Set("Content-Type", "application/json") return c.execute(req, nil, http.StatusCreated) } // AddTracksToPlaylist [adds one or more tracks to a user's playlist]. // This call requires [ScopePlaylistModifyPublic] or [ScopePlaylistModifyPrivate]. // A maximum of 100 tracks can be added per call. It returns a snapshot ID that // can be used to identify this version (the new version) of the playlist in // future requests. // // [adds one or more tracks to a user's playlist]: https://developer.spotify.com/documentation/web-api/reference/add-tracks-to-playlist func (c *Client) AddTracksToPlaylist(ctx context.Context, playlistID ID, trackIDs ...ID) (snapshotID string, err error) { uris := make([]string, len(trackIDs)) for i, id := range trackIDs { uris[i] = fmt.Sprintf("spotify:track:%s", id) } m := make(map[string]interface{}) m["uris"] = uris spotifyURL := fmt.Sprintf("%splaylists/%s/tracks", c.baseURL, string(playlistID)) body, err := json.Marshal(m) if err != nil { return "", err } req, err := http.NewRequestWithContext(ctx, "POST", spotifyURL, bytes.NewReader(body)) if err != nil { return "", err } req.Header.Set("Content-Type", "application/json") result := struct { SnapshotID string `json:"snapshot_id"` }{} err = c.execute(req, &result, http.StatusCreated) if err != nil { return "", err } return result.SnapshotID, nil } // RemoveTracksFromPlaylist [removes one or more tracks from a user's playlist]. // This call requires that the user has authorized the [ScopePlaylistModifyPublic] // or [ScopePlaylistModifyPrivate] scopes. // // If the track(s) occur multiple times in the specified playlist, then all occurrences // of the track will be removed. If successful, the snapshot ID returned can be used to // identify the playlist version in future requests. // // [removes one or more tracks from a user's playlist]: https://developer.spotify.com/documentation/web-api/reference/remove-tracks-playlist func (c *Client) RemoveTracksFromPlaylist(ctx context.Context, playlistID ID, trackIDs ...ID) (newSnapshotID string, err error) { tracks := make([]struct { URI string `json:"uri"` }, len(trackIDs)) for i, u := range trackIDs { tracks[i].URI = fmt.Sprintf("spotify:track:%s", u) } return c.removeTracksFromPlaylist(ctx, playlistID, tracks, "") } // TrackToRemove specifies a track to be removed from a playlist. // Positions is a slice of 0-based track indices. // TrackToRemove is used with RemoveTracksFromPlaylistOpt. type TrackToRemove struct { URI string `json:"uri"` Positions []int `json:"positions"` } // NewTrackToRemove returns a [TrackToRemove] with the specified // track ID and playlist locations. func NewTrackToRemove(trackID string, positions []int) TrackToRemove { return TrackToRemove{ URI: fmt.Sprintf("spotify:track:%s", trackID), Positions: positions, } } // RemoveTracksFromPlaylistOpt is like [RemoveTracksFromPlaylist], but it supports // optional parameters that offer more fine-grained control. Instead of deleting // all occurrences of a track, this function takes an index with each track URI // that indicates the position of the track in the playlist. // // In addition, the snapshotID parameter allows you to specify the snapshot ID // against which you want to make the changes. Spotify will validate that the // specified tracks exist in the specified positions and make the changes, even // if more recent changes have been made to the playlist. If a track in the // specified position is not found, the entire request will fail and no edits // will take place. (Note: the snapshot is optional, pass the empty string if // you don't care about it.) func (c *Client) RemoveTracksFromPlaylistOpt( ctx context.Context, playlistID ID, tracks []TrackToRemove, snapshotID string, ) (newSnapshotID string, err error) { return c.removeTracksFromPlaylist(ctx, playlistID, tracks, snapshotID) } func (c *Client) removeTracksFromPlaylist( ctx context.Context, playlistID ID, tracks interface{}, snapshotID string, ) (newSnapshotID string, err error) { m := make(map[string]interface{}) m["tracks"] = tracks if snapshotID != "" { m["snapshot_id"] = snapshotID } spotifyURL := fmt.Sprintf("%splaylists/%s/tracks", c.baseURL, string(playlistID)) body, err := json.Marshal(m) if err != nil { return "", err } req, err := http.NewRequestWithContext(ctx, "DELETE", spotifyURL, bytes.NewReader(body)) if err != nil { return "", err } req.Header.Set("Content-Type", "application/json") result := struct { SnapshotID string `json:"snapshot_id"` }{} err = c.execute(req, &result) if err != nil { return "", err } return result.SnapshotID, err } // ReplacePlaylistTracks [replaces all of the tracks in a playlist], overwriting its // existing tracks This can be useful for replacing or reordering tracks, or for // clearing a playlist. // // Modifying a public playlist requires that the user has authorized the // [ScopePlaylistModifyPublic] scope. Modifying a private playlist requires the // [ScopePlaylistModifyPrivate] scope. // // A maximum of 100 tracks are permitted in this call. Additional tracks must be // added via [AddTracksToPlaylist]. // // [replaces all of the tracks in a playlist]: https://developer.spotify.com/documentation/web-api/reference/reorder-or-replace-playlists-tracks func (c *Client) ReplacePlaylistTracks(ctx context.Context, playlistID ID, trackIDs ...ID) error { trackURIs := make([]string, len(trackIDs)) for i, u := range trackIDs { trackURIs[i] = fmt.Sprintf("spotify:track:%s", u) } spotifyURL := fmt.Sprintf("%splaylists/%s/tracks?uris=%s", c.baseURL, playlistID, strings.Join(trackURIs, ",")) req, err := http.NewRequestWithContext(ctx, "PUT", spotifyURL, nil) if err != nil { return err } return c.execute(req, nil, http.StatusCreated) } // ReplacePlaylistItems [replaces all the items in a playlist], overwriting its // existing tracks This can be useful for replacing or reordering tracks, or for // clearing a playlist. // // Modifying a public playlist requires that the user has authorized the // [ScopePlaylistModifyPublic] scope. Modifying a private playlist requires the // [ScopePlaylistModifyPrivate] scope. // // A maximum of 100 tracks is permited in this call. Additional tracks must be // added via AddTracksToPlaylist. // // [replaces all the items in a playlist]: https://developer.spotify.com/documentation/web-api/reference/reorder-or-replace-playlists-tracks func (c *Client) ReplacePlaylistItems(ctx context.Context, playlistID ID, items ...URI) (string, error) { m := make(map[string]interface{}) m["uris"] = items body, err := json.Marshal(m) if err != nil { return "", err } spotifyURL := fmt.Sprintf("%splaylists/%s/tracks", c.baseURL, playlistID) req, err := http.NewRequestWithContext(ctx, "PUT", spotifyURL, bytes.NewReader(body)) if err != nil { return "", err } req.Header.Set("Content-Type", "application/json") result := struct { SnapshotID string `json:"snapshot_id"` }{} err = c.execute(req, &result, http.StatusCreated) if err != nil { return "", err } return result.SnapshotID, nil } // UserFollowsPlaylist [checks if one or more (up to 5) users are following] // a Spotify playlist, given the playlist's owner and ID. // // Checking if a user follows a playlist publicly doesn't require any scopes. // Checking if the user is privately following a playlist is only possible for the // current user when that user has granted access to the [ScopePlaylistReadPrivate] scope. // // [checks if one or more (up to 5) users are following]: https://developer.spotify.com/documentation/web-api/reference/check-if-user-follows-playlist func (c *Client) UserFollowsPlaylist(ctx context.Context, playlistID ID, userIDs ...string) ([]bool, error) { spotifyURL := fmt.Sprintf("%splaylists/%s/followers/contains?ids=%s", c.baseURL, playlistID, strings.Join(userIDs, ",")) follows := make([]bool, len(userIDs)) err := c.get(ctx, spotifyURL, &follows) if err != nil { return nil, err } return follows, nil } // PlaylistReorderOptions is used with ReorderPlaylistTracks to reorder // a track or group of tracks in a playlist. // // For example, in a playlist with 10 tracks, you can: // // - move the first track to the end of the playlist by setting // RangeStart to 0 and InsertBefore to 10 // - move the last track to the beginning of the playlist by setting // RangeStart to 9 and InsertBefore to 0 // - Move the last 2 tracks to the beginning of the playlist by setting // RangeStart to 8 and RangeLength to 2. type PlaylistReorderOptions struct { // The position of the first track to be reordered. // This field is required. RangeStart Numeric `json:"range_start"` // The amount of tracks to be reordered. This field is optional. If // you don't set it, the value 1 will be used. RangeLength Numeric `json:"range_length,omitempty"` // The position where the tracks should be inserted. To reorder the // tracks to the end of the playlist, simply set this to the position // after the last track. This field is required. InsertBefore Numeric `json:"insert_before"` // The playlist's snapshot ID against which you wish to make the changes. // This field is optional. SnapshotID string `json:"snapshot_id,omitempty"` } // ReorderPlaylistTracks reorders a track or group of tracks in a playlist. It // returns a snapshot ID that can be used to identify the (newly modified) playlist // version in future requests. // // See the docs for [PlaylistReorderOptions] for information on how the reordering // works. // // Reordering tracks in the current user's public playlist requires [ScopePlaylistModifyPublic]. // Reordering tracks in the user's private playlists (including collaborative playlists) requires // [ScopePlaylistModifyPrivate]. func (c *Client) ReorderPlaylistTracks(ctx context.Context, playlistID ID, opt PlaylistReorderOptions) (snapshotID string, err error) { spotifyURL := fmt.Sprintf("%splaylists/%s/tracks", c.baseURL, playlistID) j, err := json.Marshal(opt) if err != nil { return "", err } req, err := http.NewRequestWithContext(ctx, "PUT", spotifyURL, bytes.NewReader(j)) if err != nil { return "", err } req.Header.Set("Content-Type", "application/json") result := struct { SnapshotID string `json:"snapshot_id"` }{} err = c.execute(req, &result) if err != nil { return "", err } return result.SnapshotID, nil } // SetPlaylistImage replaces the image used to represent a playlist. // This action can only be performed by the owner of the playlist, // and requires [ScopeImageUpload] as well as [ScopeModifyPlaylistPublic] or // [ScopeModifyPlaylistPrivate]. func (c *Client) SetPlaylistImage(ctx context.Context, playlistID ID, img io.Reader) error { spotifyURL := fmt.Sprintf("%splaylists/%s/images", c.baseURL, playlistID) // data flow: // img (reader) -> copy into base64 encoder (writer) -> pipe (write end) // pipe (read end) -> request body r, w := io.Pipe() go func() { enc := base64.NewEncoder(base64.StdEncoding, w) _, err := io.Copy(enc, img) _ = enc.Close() _ = w.CloseWithError(err) }() req, err := http.NewRequestWithContext(ctx, "PUT", spotifyURL, r) if err != nil { return err } req.Header.Set("Content-Type", "image/jpeg") return c.execute(req, nil, http.StatusAccepted) }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
playlist_test.go
Go
package spotify import ( "bytes" "context" "encoding/json" "fmt" "io" "net/http" "testing" "time" ) func TestFeaturedPlaylists(t *testing.T) { client, server := testClientFile(http.StatusOK, "test_data/featured_playlists.txt") defer server.Close() country := "SE" msg, p, err := client.FeaturedPlaylists(context.Background(), Country(country)) if err != nil { t.Error(err) return } if msg != "New Music Friday!" { t.Errorf("Want 'Enjoy a mellow afternoon.', got'%s'\n", msg) } if len(p.Playlists) == 0 { t.Fatal("Empty playlists result") } expected := "New Music Friday Sweden" if name := p.Playlists[0].Name; name != expected { t.Errorf("Want '%s', got '%s'\n", expected, name) } expected = "Äntligen fredag och ny musik! Happy New Music Friday!" if desc := p.Playlists[0].Description; desc != expected { t.Errorf("Want '%s', got '%s'\n", expected, desc) } } func TestFeaturedPlaylistsExpiredToken(t *testing.T) { json := `{ "error": { "status": 401, "message": "The access token expired" } }` client, server := testClientString(http.StatusUnauthorized, json) defer server.Close() msg, pl, err := client.FeaturedPlaylists(context.Background()) if msg != "" || pl != nil || err == nil { t.Fatal("Expected an error") } serr, ok := err.(Error) if !ok { t.Fatalf("Expected spotify Error, got %T", err) } if serr.Status != http.StatusUnauthorized { t.Error("Expected HTTP 401") } } func TestPlaylistsForUser(t *testing.T) { client, server := testClientFile(http.StatusOK, "test_data/playlists_for_user.txt") defer server.Close() playlists, err := client.GetPlaylistsForUser(context.Background(), "whizler") if err != nil { t.Error(err) } if l := len(playlists.Playlists); l == 0 { t.Fatal("Didn't get any results") } else if l != 7 { t.Errorf("Got %d playlists, expected 7\n", l) } p := playlists.Playlists[0] if p.Name != "Top 40" { t.Error("Expected Top 40, got", p.Name) } if p.Tracks.Total != 40 { t.Error("Expected 40 tracks, got", p.Tracks.Total) } expected := "Nederlandse Top 40, de enige echte hitlijst van Nederland! Official Dutch Top 40. Check top40.nl voor alle details en luister iedere vrijdag vanaf 14.00 uur naar de lijst op Qmusic met Domien Verschuuren." if p.Description != expected { t.Errorf("Expected '%s', got '%s'\n", expected, p.Description) } } func TestGetPlaylist(t *testing.T) { client, server := testClientFile(http.StatusOK, "test_data/get_playlist.txt") defer server.Close() p, err := client.GetPlaylist(context.Background(), "1h9q8vXXDl2vHOmwdsuXms") if err != nil { t.Error(err) } if p.Collaborative { t.Error("Playlist shouldn't be collaborative") } if p.Description != "Bit of a overlap with phonk but whatever" { t.Error("Description is invalid") } // Ensure the Description field is also present in the SimplePlaylist part of the object if p.SimplePlaylist.Description != "Bit of a overlap with phonk but whatever" { t.Error("Description is invalid in the SimplePlaylist part of the object") } } func TestGetPlaylistOpt(t *testing.T) { client, server := testClientFile(http.StatusOK, "test_data/get_playlist_opt.txt") defer server.Close() fields := "href,name,owner(!href,external_urls),tracks.items(added_by.id,track(name,href,album(name,href)))" p, err := client.GetPlaylist(context.Background(), "59ZbFPES4DQwEjBpWHzrtC", Fields(fields)) if err != nil { t.Error(err) } if p.Collaborative { t.Error("Playlist shouldn't be collaborative") } if p.Description != "" { t.Error("No description should be included") } // A bit counterintuitive, but we excluded tracks.total from the API call so it should be 0 in the model. if p.Tracks.Total != 0 { t.Errorf("Tracks.Total should be 0, got %d", p.Tracks.Total) } } func TestFollowPlaylistSetsContentType(t *testing.T) { client, server := testClientString(http.StatusOK, "", func(req *http.Request) { if req.Header.Get("Content-Type") != "application/json" { t.Error("Follow playlist request didn't contain Content-Type: application/json") } }) defer server.Close() err := client.FollowPlaylist(context.Background(), "playlistID", true) if err != nil { t.Error(err) } } func TestGetPlaylistTracks(t *testing.T) { client, server := testClientFile(http.StatusOK, "test_data/playlist_tracks.txt") defer server.Close() tracks, err := client.GetPlaylistTracks(context.Background(), "5lH9NjOeJvctAO92ZrKQNB") if err != nil { t.Error(err) } if tracks.Total != 40 { t.Errorf("Got %d tracks, expected 40\n", tracks.Total) } if len(tracks.Tracks) == 0 { t.Fatal("No tracks returned") } expected := "Calm Down" actual := tracks.Tracks[0].Track.Name if expected != actual { t.Errorf("Got '%s', expected '%s'\n", actual, expected) } added := tracks.Tracks[0].AddedAt tm, err := time.Parse(TimestampLayout, added) if err != nil { t.Error(err) } if f := tm.Format(DateLayout); f != "2022-07-15" { t.Errorf("Expected added at 2022-07-15, got %s\n", f) } } func TestGetPlaylistItemsEpisodes(t *testing.T) { client, server := testClientFile(http.StatusOK, "test_data/playlist_items_episodes.json") defer server.Close() tracks, err := client.GetPlaylistItems(context.Background(), "playlistID") if err != nil { t.Error(err) } if tracks.Total != 4 { t.Errorf("Got %d tracks, expected 47\n", tracks.Total) } if len(tracks.Items) == 0 { t.Fatal("No tracks returned") } expected := "112: Dirty Coms" actual := tracks.Items[0].Track.Episode.Name if expected != actual { t.Errorf("Got '%s', expected '%s'\n", actual, expected) } added := tracks.Items[0].AddedAt tm, err := time.Parse(TimestampLayout, added) if err != nil { t.Error(err) } if f := tm.Format(DateLayout); f != "2022-05-20" { t.Errorf("Expected added at 2014-11-25, got %s\n", f) } } func TestGetPlaylistItemsTracks(t *testing.T) { client, server := testClientFile(http.StatusOK, "test_data/playlist_items_tracks.json") defer server.Close() tracks, err := client.GetPlaylistItems(context.Background(), "playlistID") if err != nil { t.Error(err) } if tracks.Total != 2 { t.Errorf("Got %d tracks, expected 47\n", tracks.Total) } if len(tracks.Items) == 0 { t.Fatal("No tracks returned") } expected := "Typhoons" actual := tracks.Items[0].Track.Track.Name if expected != actual { t.Errorf("Got '%s', expected '%s'\n", actual, expected) } added := tracks.Items[0].AddedAt tm, err := time.Parse(TimestampLayout, added) if err != nil { t.Error(err) } if f := tm.Format(DateLayout); f != "2022-05-20" { t.Errorf("Expected added at 2014-11-25, got %s\n", f) } } func TestGetPlaylistItemsTracksAndEpisodes(t *testing.T) { client, server := testClientFile(http.StatusOK, "test_data/playlist_items_episodes_and_tracks.json") defer server.Close() tracks, err := client.GetPlaylistItems(context.Background(), "playlistID") if err != nil { t.Error(err) } if tracks.Total != 4 { t.Errorf("Got %d tracks, expected 47\n", tracks.Total) } if len(tracks.Items) == 0 { t.Fatal("No tracks returned") } expected := "491- The Missing Middle" actual := tracks.Items[0].Track.Episode.Name if expected != actual { t.Errorf("Got '%s', expected '%s'\n", actual, expected) } added := tracks.Items[0].AddedAt tm, err := time.Parse(TimestampLayout, added) if err != nil { t.Error(err) } if f := tm.Format(DateLayout); f != "2022-05-20" { t.Errorf("Expected added at 2014-11-25, got %s\n", f) } expected = "Typhoons" actual = tracks.Items[2].Track.Track.Name if expected != actual { t.Errorf("Got '%s', expected '%s'\n", actual, expected) } added = tracks.Items[0].AddedAt tm, err = time.Parse(TimestampLayout, added) if err != nil { t.Error(err) } if f := tm.Format(DateLayout); f != "2022-05-20" { t.Errorf("Expected added at 2014-11-25, got %s\n", f) } } func TestGetPlaylistItemsOverride(t *testing.T) { var types string client, server := testClientString(http.StatusForbidden, "", func(r *http.Request) { types = r.URL.Query().Get("additional_types") }) defer server.Close() _, _ = client.GetPlaylistItems(context.Background(), "playlistID", AdditionalTypes(EpisodeAdditionalType)) if types != "episode" { t.Errorf("Expected additional type episode, got %s\n", types) } } func TestGetPlaylistItemsDefault(t *testing.T) { var types string client, server := testClientString(http.StatusForbidden, "", func(r *http.Request) { types = r.URL.Query().Get("additional_types") }) defer server.Close() _, _ = client.GetPlaylistItems(context.Background(), "playlistID") if types != "episode,track" { t.Errorf("Expected additional type episode, got %s\n", types) } } func TestUserFollowsPlaylist(t *testing.T) { client, server := testClientString(http.StatusOK, `[ true, false ]`) defer server.Close() follows, err := client.UserFollowsPlaylist(context.Background(), ID("2v3iNvBS8Ay1Gt2uXtUKUT"), "possan", "elogain") if err != nil { t.Error(err) } if len(follows) != 2 || !follows[0] || follows[1] { t.Errorf("Expected '[true, false]', got %#v\n", follows) } } // NOTE collaborative is a fmt boolean. var newPlaylist = ` { "collaborative": %t, "description": "Test Description", "external_urls": { "spotify": "api.http://open.spotify.com/user/thelinmichael/playlist/7d2D2S200NyUE5KYs80PwO" }, "followers": { "href": null, "total": 0 }, "href": "https://api.spotify.com/v1/users/thelinmichael/playlists/7d2D2S200NyUE5KYs80PwO", "id": "7d2D2S200NyUE5KYs80PwO", "images": [ ], "name": "A New Playlist", "owner": { "external_urls": { "spotify": "api.http://open.spotify.com/user/thelinmichael" }, "href": "https://api.spotify.com/v1/users/thelinmichael", "id": "thelinmichael", "type": "user", "url": "spotify:user:thelinmichael" }, "public": false, "snapshot_id": "s0o3TSuYnRLl2jch+oA4OEbKwq/fNxhGBkSPnvhZdmWjNV0q3uCAWuGIhEx8SHIx", "tracks": { "href": "https://api.spotify.com/v1/users/thelinmichael/playlists/7d2D2S200NyUE5KYs80PwO/tracks", "items": [ ], "limit": 100, "next": null, "offset": 0, "previous": null, "total": 0 }, "type": "playlist", "url": "spotify:user:thelinmichael:playlist:7d2D2S200NyUE5KYs80PwO" }` func TestCreatePlaylist(t *testing.T) { client, server := testClientString(http.StatusCreated, fmt.Sprintf(newPlaylist, false)) defer server.Close() p, err := client.CreatePlaylistForUser(context.Background(), "thelinmichael", "A New Playlist", "Test Description", false, false) if err != nil { t.Error(err) } if p.IsPublic { t.Error("Expected private playlist, got public") } if p.Name != "A New Playlist" { t.Errorf("Expected 'A New Playlist', got '%s'\n", p.Name) } if p.Description != "Test Description" { t.Errorf("Expected 'Test Description', got '%s'\n", p.Description) } if p.Tracks.Total != 0 { t.Error("Expected new playlist to be empty") } if p.Collaborative { t.Error("Expected non-collaborative playlist, got collaborative") } } func TestCreateCollaborativePlaylist(t *testing.T) { client, server := testClientString(http.StatusCreated, fmt.Sprintf(newPlaylist, true)) defer server.Close() p, err := client.CreatePlaylistForUser(context.Background(), "thelinmichael", "A New Playlist", "Test Description", false, true) if err != nil { t.Error(err) } if p.IsPublic { t.Error("Expected private playlist, got public") } if p.Name != "A New Playlist" { t.Errorf("Expected 'A New Playlist', got '%s'\n", p.Name) } if p.Description != "Test Description" { t.Errorf("Expected 'Test Description', got '%s'\n", p.Description) } if p.Tracks.Total != 0 { t.Error("Expected new playlist to be empty") } if !p.Collaborative { t.Error("Expected collaborative playlist, got non-collaborative") } } func TestRenamePlaylist(t *testing.T) { client, server := testClientString(http.StatusOK, "") defer server.Close() if err := client.ChangePlaylistName(context.Background(), ID("playlist-id"), "new name"); err != nil { t.Error(err) } } func TestChangePlaylistAccess(t *testing.T) { client, server := testClientString(http.StatusOK, "") defer server.Close() if err := client.ChangePlaylistAccess(context.Background(), ID("playlist-id"), true); err != nil { t.Error(err) } } func TestChangePlaylistDescription(t *testing.T) { client, server := testClientString(http.StatusOK, "") defer server.Close() if err := client.ChangePlaylistDescription(context.Background(), ID("playlist-id"), "new description"); err != nil { t.Error(err) } } func TestChangePlaylistNameAndAccess(t *testing.T) { client, server := testClientString(http.StatusOK, "") defer server.Close() if err := client.ChangePlaylistNameAndAccess(context.Background(), ID("playlist-id"), "new_name", true); err != nil { t.Error(err) } } func TestChangePlaylistNameAccessAndDescription(t *testing.T) { client, server := testClientString(http.StatusOK, "") defer server.Close() if err := client.ChangePlaylistNameAccessAndDescription(context.Background(), ID("playlist-id"), "new_name", "new description", true); err != nil { t.Error(err) } } func TestChangePlaylistNameFailure(t *testing.T) { client, server := testClientString(http.StatusForbidden, "") defer server.Close() if err := client.ChangePlaylistName(context.Background(), ID("playlist-id"), "new_name"); err == nil { t.Error("Expected error but didn't get one") } } func TestAddTracksToPlaylist(t *testing.T) { client, server := testClientString(http.StatusCreated, `{ "snapshot_id" : "JbtmHBDBAYu3/bt8BOXKjzKx3i0b6LCa/wVjyl6qQ2Yf6nFXkbmzuEa+ZI/U1yF+" }`) defer server.Close() snapshot, err := client.AddTracksToPlaylist(context.Background(), ID("playlist_id"), ID("track1"), ID("track2")) if err != nil { t.Error(err) } if snapshot != "JbtmHBDBAYu3/bt8BOXKjzKx3i0b6LCa/wVjyl6qQ2Yf6nFXkbmzuEa+ZI/U1yF+" { t.Error("Didn't get expected snapshot ID") } } func TestRemoveTracksFromPlaylist(t *testing.T) { client, server := testClientString(http.StatusOK, `{ "snapshot_id" : "JbtmHBDBAYu3/bt8BOXKjzKx3i0b6LCa/wVjyl6qQ2Yf6nFXkbmzuEa+ZI/U1yF+" }`, func(req *http.Request) { requestBody, err := io.ReadAll(req.Body) if err != nil { t.Fatal("Could not read request body:", err) } var body map[string]interface{} err = json.Unmarshal(requestBody, &body) if err != nil { t.Fatal("Error decoding request body:", err) } tracksArray, ok := body["tracks"] if !ok { t.Error("No tracks JSON object in request body") } tracksSlice := tracksArray.([]interface{}) if l := len(tracksSlice); l != 2 { t.Fatalf("Expected 2 tracks, got %d\n", l) } track0 := tracksSlice[0].(map[string]interface{}) trackURI, ok := track0["uri"] if !ok { t.Error("Track object doesn't contain 'uri' field") } if trackURI != "spotify:track:track1" { t.Errorf("Expected URI: 'spotify:track:track1', got '%s'\n", trackURI) } }) defer server.Close() snapshotID, err := client.RemoveTracksFromPlaylist(context.Background(), "playlistID", "track1", "track2") if err != nil { t.Error(err) } if snapshotID != "JbtmHBDBAYu3/bt8BOXKjzKx3i0b6LCa/wVjyl6qQ2Yf6nFXkbmzuEa+ZI/U1yF+" { t.Error("Incorrect snapshot ID") } } func TestRemoveTracksFromPlaylistOpt(t *testing.T) { client, server := testClientString(http.StatusOK, `{ "snapshot_id" : "JbtmHBDBAYu3/bt8BOXKjzKx3i0b6LCa/wVjyl6qQ2Yf6nFXkbmzuEa+ZI/U1yF+" }`, func(req *http.Request) { requestBody, err := io.ReadAll(req.Body) if err != nil { t.Fatal(err) } var body map[string]interface{} err = json.Unmarshal(requestBody, &body) if err != nil { t.Fatal(err) } if _, ok := body["snapshot_id"]; ok { t.Error("JSON contains snapshot_id field when none was specified") fmt.Println(string(requestBody)) return } jsonTracks := body["tracks"].([]interface{}) if len(jsonTracks) != 3 { t.Fatal("Expected 3 tracks, got", len(jsonTracks)) } track1 := jsonTracks[1].(map[string]interface{}) expected := "spotify:track:track1" if track1["uri"] != expected { t.Fatalf("Want '%s', got '%s'\n", expected, track1["uri"]) } indices := track1["positions"].([]interface{}) if len(indices) != 1 || int(indices[0].(float64)) != 9 { t.Error("Track indices incorrect") } }) defer server.Close() tracks := []TrackToRemove{ NewTrackToRemove("track0", []int{0, 4}), // remove track0 in position 0 and 4 NewTrackToRemove("track1", []int{9}), // remove track1 in position 9... NewTrackToRemove("track2", []int{8}), } // intentionally not passing a snapshot ID here snapshotID, err := client.RemoveTracksFromPlaylistOpt(context.Background(), "playlistID", tracks, "") if err != nil || snapshotID != "JbtmHBDBAYu3/bt8BOXKjzKx3i0b6LCa/wVjyl6qQ2Yf6nFXkbmzuEa+ZI/U1yF+" { t.Fatal("Remove call failed. err=", err) } } func TestClient_ReplacePlaylistItems(t *testing.T) { type clientFields struct { httpCode int body string } type args struct { ctx context.Context playlistID ID items []URI } type want struct { requestBody string snapshot string err string } tests := []struct { name string clientFields clientFields args args want want }{ { name: "Happy path", clientFields: clientFields{ httpCode: http.StatusCreated, body: `{"snapshot_id": "test_snapshot"}`, }, args: args{ ctx: context.TODO(), playlistID: "playlistID", items: []URI{"spotify:track:track1", "spotify:track:track2"}, }, want: want{ requestBody: `{"uris":["spotify:track:track1","spotify:track:track2"]}`, snapshot: "test_snapshot", }, }, { name: "Forbidden", clientFields: clientFields{ httpCode: http.StatusForbidden, }, args: args{ ctx: context.TODO(), playlistID: "playlistID", items: []URI{"spotify:track:track1", "spotify:track:track2"}, }, want: want{ err: "spotify: Forbidden [403]", }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { var gotRequestBody string c, server := testClientString(tt.clientFields.httpCode, tt.clientFields.body, func(request *http.Request) { b, err := io.ReadAll(request.Body) defer request.Body.Close() if err != nil { t.Error(err) } gotRequestBody = string(b) }) defer server.Close() gotSnapshot, gotErr := c.ReplacePlaylistItems(tt.args.ctx, tt.args.playlistID, tt.args.items...) if gotErr == nil && tt.want.err != "" { t.Errorf("Expected an error %s, got nil", tt.want.err) return } if gotErr != nil { if gotErr.Error() != tt.want.err { t.Errorf("Expected error %s, got %s", tt.want.err, gotErr) } return } if gotSnapshot != tt.want.snapshot { t.Errorf("Expected snapshot %s, got %s", tt.want.snapshot, gotSnapshot) } if gotRequestBody != tt.want.requestBody { t.Errorf("Expected requestBody %s, got %s", tt.want.requestBody, gotRequestBody) } }) } } func TestReplacePlaylistTracks(t *testing.T) { client, server := testClientString(http.StatusCreated, "") defer server.Close() err := client.ReplacePlaylistTracks(context.Background(), "playlistID", "track1", "track2") if err != nil { t.Error(err) } } func TestReplacePlaylistTracksForbidden(t *testing.T) { client, server := testClientString(http.StatusForbidden, "") defer server.Close() err := client.ReplacePlaylistTracks(context.Background(), "playlistID", "track1", "track2") if err == nil { t.Error("Replace succeeded but shouldn't have") } } func TestReorderPlaylistRequest(t *testing.T) { client, server := testClientString(http.StatusNotFound, "", func(req *http.Request) { if ct := req.Header.Get("Content-Type"); ct != "application/json" { t.Errorf("Expected Content-Type: application/json, got '%s'\n", ct) } if req.Method != "PUT" { t.Errorf("Expected a PUT, got a %s\n", req.Method) } // unmarshal the JSON into a map[string]interface{} // so we can test for existence of certain keys var body map[string]interface{} err := json.NewDecoder(req.Body).Decode(&body) if err != nil { t.Errorf("Expected no error, got %v", err) } if start, ok := body["range_start"]; ok { if start != float64(3) { t.Errorf("Expected range_start to be 3, but it was %#v\n", start) } } else { t.Errorf("Required field range_start is missing") } if ib, ok := body["insert_before"]; ok { if ib != float64(8) { t.Errorf("Expected insert_before to be 8, but it was %#v\n", ib) } } else { t.Errorf("Required field insert_before is missing") } if _, ok := body["range_length"]; ok { t.Error("Parameter range_length shouldn't have been in body") } if _, ok := body["snapshot_id"]; ok { t.Error("Parameter snapshot_id shouldn't have been in body") } }) defer server.Close() _, err := client.ReorderPlaylistTracks(context.Background(), "playlist", PlaylistReorderOptions{ RangeStart: 3, InsertBefore: 8, }) if want := "spotify: Not Found [404]"; err == nil || err.Error() != want { t.Errorf("Expected error: want %v, got %v", want, err) } } func TestSetPlaylistImage(t *testing.T) { client, server := testClientString(http.StatusAccepted, "", func(req *http.Request) { if ct := req.Header.Get("Content-Type"); ct != "image/jpeg" { t.Errorf("wrong content type, got %s, want image/jpeg", ct) } if req.Method != "PUT" { t.Errorf("expected a PUT, got a %s\n", req.Method) } body, err := io.ReadAll(req.Body) if err != nil { t.Fatal(err) } if !bytes.Equal(body, []byte("Zm9v")) { t.Errorf("invalid request body: want Zm9v, got %s", string(body)) } }) defer server.Close() err := client.SetPlaylistImage(context.Background(), "playlist", bytes.NewReader([]byte("foo"))) if err != nil { t.Fatal(err) } }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
recommendation.go
Go
package spotify import ( "context" "fmt" "net/url" "strconv" "strings" ) // Seeds contains IDs of artists, genres and/or tracks // to be used as seeds for recommendations type Seeds struct { Artists []ID Tracks []ID Genres []string } // count returns the total number of seeds contained in s. func (s Seeds) count() int { return len(s.Artists) + len(s.Tracks) + len(s.Genres) } // Recommendations contains a list of recommended tracks based on seeds. type Recommendations struct { Seeds []RecommendationSeed `json:"seeds"` Tracks []SimpleTrack `json:"tracks"` } // RecommendationSeed represents a recommendation seed after // being processed by the Spotify API. type RecommendationSeed struct { AfterFilteringSize Numeric `json:"afterFilteringSize"` AfterRelinkingSize Numeric `json:"afterRelinkingSize"` Endpoint string `json:"href"` ID ID `json:"id"` InitialPoolSize Numeric `json:"initialPoolSize"` Type string `json:"type"` } // MaxNumberOfSeeds allowed by Spotify for a recommendation request. const MaxNumberOfSeeds = 5 // setSeedValues sets url values into v for each seed in seeds func setSeedValues(seeds Seeds, v url.Values) { if len(seeds.Artists) != 0 { v.Set("seed_artists", strings.Join(toStringSlice(seeds.Artists), ",")) } if len(seeds.Tracks) != 0 { v.Set("seed_tracks", strings.Join(toStringSlice(seeds.Tracks), ",")) } if len(seeds.Genres) != 0 { v.Set("seed_genres", strings.Join(seeds.Genres, ",")) } } // setTrackAttributesValues sets track attributes values to the given url values func setTrackAttributesValues(trackAttributes *TrackAttributes, values url.Values) { if trackAttributes == nil { return } for attr, val := range trackAttributes.intAttributes { values.Set(attr, strconv.Itoa(val)) } for attr, val := range trackAttributes.floatAttributes { values.Set(attr, strconv.FormatFloat(val, 'f', -1, 64)) } } // GetRecommendations returns a [list of recommended tracks] based on the given // seeds. Recommendations are generated based on the available information for a // given seed entity and matched against similar artists and tracks. If there is // sufficient information about the provided seeds, a list of tracks will be // returned together with pool size details. For artists and tracks that are // very new or obscure there might not be enough data to generate a list of // tracks. // // Supported options: [Limit], [Country]. // // [list of recommended tracks]: https://developer.spotify.com/documentation/web-api/reference/get-recommendations func (c *Client) GetRecommendations(ctx context.Context, seeds Seeds, trackAttributes *TrackAttributes, opts ...RequestOption) (*Recommendations, error) { v := processOptions(opts...).urlParams if seeds.count() == 0 { return nil, fmt.Errorf("spotify: at least one seed is required") } if seeds.count() > MaxNumberOfSeeds { return nil, fmt.Errorf("spotify: exceeded maximum of %d seeds", MaxNumberOfSeeds) } setSeedValues(seeds, v) setTrackAttributesValues(trackAttributes, v) spotifyURL := c.baseURL + "recommendations?" + v.Encode() var recommendations Recommendations err := c.get(ctx, spotifyURL, &recommendations) if err != nil { return nil, err } return &recommendations, err } // GetAvailableGenreSeeds retrieves a [list of available genres] seed parameter // values for recommendations. // // [list of available genres]: https://developer.spotify.com/documentation/web-api/reference/get-recommendation-genres func (c *Client) GetAvailableGenreSeeds(ctx context.Context) ([]string, error) { spotifyURL := c.baseURL + "recommendations/available-genre-seeds" genreSeeds := make(map[string][]string) err := c.get(ctx, spotifyURL, &genreSeeds) if err != nil { return nil, err } return genreSeeds["genres"], nil }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
recommendation_test.go
Go
package spotify import ( "context" "net/url" "testing" ) func TestGetRecommendations(t *testing.T) { // test data corresponding to Spotify Console web API sample client, server := testClientFile(200, "test_data/recommendations.txt") defer server.Close() seeds := Seeds{ Artists: []ID{"4NHQUGzhtTLFvgF5SZesLK"}, Tracks: []ID{"0c6xIDDpzE81m2q797ordA"}, Genres: []string{"classical", "country"}, } country := "ES" limit := 10 recommendations, err := client.GetRecommendations(context.Background(), seeds, nil, Country(country), Limit(limit)) if err != nil { t.Fatal(err) } if len(recommendations.Tracks) != 10 { t.Error("Expected 10 recommended tracks") } if recommendations.Tracks[0].Artists[0].Name != "Heinrich Isaac" { t.Error("Expected the artist of the first recommended track to be Heinrich Isaac") } } func TestSetSeedValues(t *testing.T) { expectedValues := "seed_artists=4NHQUGzhtTLFvgF5SZesLK%2C5PHQUGzhtTUIvgF5SZesGY&seed_genres=classical%2Ccountry" v := url.Values{} seeds := Seeds{ Artists: []ID{"4NHQUGzhtTLFvgF5SZesLK", "5PHQUGzhtTUIvgF5SZesGY"}, Genres: []string{"classical", "country"}, } setSeedValues(seeds, v) actualValues := v.Encode() if actualValues != expectedValues { t.Errorf("Expected seed values to be %s but got %s", expectedValues, actualValues) } } func TestSetTrackAttributesValues(t *testing.T) { expectedValues := "max_duration_ms=200&min_duration_ms=20&min_energy=0.45&target_acousticness=0.27&target_duration_ms=160" v := url.Values{} ta := NewTrackAttributes(). MaxDuration(200). MinDuration(20). TargetDuration(160). MinEnergy(0.45). TargetAcousticness(0.27) setTrackAttributesValues(ta, v) actualValues := v.Encode() if actualValues != expectedValues { t.Errorf("Expected track attributes values to be %s but got %s", expectedValues, actualValues) } } func TestSetEmptyTrackAttributesValues(t *testing.T) { expectedValues := "" v := url.Values{} setTrackAttributesValues(nil, v) actualValues := v.Encode() if actualValues != expectedValues { t.Errorf("Expected track attributes values to be empty but got %s", actualValues) } }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
request_options.go
Go
package spotify import ( "net/url" "strconv" "strings" ) type RequestOption func(*requestOptions) type requestOptions struct { urlParams url.Values } // Limit sets the number of entries that a request should return. func Limit(amount int) RequestOption { return func(o *requestOptions) { o.urlParams.Set("limit", strconv.Itoa(amount)) } } // Market enables track re-linking. func Market(code string) RequestOption { return func(o *requestOptions) { o.urlParams.Set("market", code) } } // Country enables a specific region to be specified for region-specific suggestions e.g popular playlists // The Country option takes an ISO 3166-1 alpha-2 country code. It can be // used to ensure that the category exists for a particular country. func Country(code string) RequestOption { return func(o *requestOptions) { o.urlParams.Set("country", code) } } // Locale enables a specific language to be used when returning results. // The Locale argument is an ISO 639 language code and an ISO 3166-1 alpha-2 // country code, separated by an underscore. It can be used to get the // category strings in a particular language (for example: "es_MX" means // get categories in Mexico, returned in Spanish). func Locale(code string) RequestOption { return func(o *requestOptions) { o.urlParams.Set("locale", code) } } // Offset sets the index of the first entry to return. func Offset(amount int) RequestOption { return func(o *requestOptions) { o.urlParams.Set("offset", strconv.Itoa(amount)) } } // Timestamp in ISO 8601 format (yyyy-MM-ddTHH:mm:ss). // Use this parameter to specify the user's local time to // get results tailored for that specific date and time // in the day. If not provided, the response defaults to // the current UTC time. func Timestamp(ts string) RequestOption { return func(o *requestOptions) { o.urlParams.Set("timestamp", ts) } } // After is the last ID retrieved from the previous request. This allows pagination. func After(after string) RequestOption { return func(o *requestOptions) { o.urlParams.Set("after", after) } } // Fields is a comma-separated list of the fields to return. // See the JSON tags on [FullPlaylist] for valid field options. // For example, to get just the playlist's description and URI: // // fields = "description,uri" // // A dot separator can be used to specify non-reoccurring fields, while // parentheses can be used to specify reoccurring fields within objects. // For example, to get just the added date and the user ID of the adder: // // fields = "tracks.items(added_at,added_by.id)" // // Use multiple parentheses to drill down into nested objects, for example: // // fields = "tracks.items(track(name,href,album(name,href)))" // // Fields can be excluded by prefixing them with an exclamation mark, for example; // // fields = "tracks.items(track(name,href,album(!name,href)))" func Fields(fields string) RequestOption { return func(o *requestOptions) { o.urlParams.Set("fields", fields) } } type Range string const ( // LongTermRange is calculated from several years of data, including new data where possible LongTermRange Range = "long_term" // MediumTermRange is approximately the last six months MediumTermRange Range = "medium_term" // ShortTermRange is approximately the last four weeks ShortTermRange Range = "short_term" ) // Timerange sets the time period that Spotify will use when returning // information. Use [LongTermRange], [MediumTermRange] and [ShortTermRange] to // set the appropriate period. func Timerange(timerange Range) RequestOption { return func(o *requestOptions) { o.urlParams.Set("time_range", string(timerange)) } } type AdditionalType string const ( EpisodeAdditionalType = "episode" TrackAdditionalType = "track" ) // AdditionalTypes is a list of item types that your client supports besides // the default track type. Valid types are: [EpisodeAdditionalType] and // [TrackAdditionalType]. func AdditionalTypes(types ...AdditionalType) RequestOption { strTypes := make([]string, len(types)) for i, t := range types { strTypes[i] = string(t) } csv := strings.Join(strTypes, ",") return func(o *requestOptions) { o.urlParams.Set("additional_types", csv) } } func processOptions(options ...RequestOption) requestOptions { o := requestOptions{ urlParams: url.Values{}, } for _, opt := range options { opt(&o) } return o }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
request_options_test.go
Go
package spotify import ( "testing" ) func TestOptions(t *testing.T) { t.Parallel() resultSet := processOptions( After("example_id"), Country(CountryUnitedKingdom), Limit(13), Locale("en_GB"), Market(CountryArgentina), Offset(1), Timerange("long"), Timestamp("2000-11-02T13:37:00"), ) expected := "after=example_id&country=GB&limit=13&locale=en_GB&market=AR&offset=1&time_range=long&timestamp=2000-11-02T13%3A37%3A00" actual := resultSet.urlParams.Encode() if actual != expected { t.Errorf("Expected '%v', got '%v'", expected, actual) } }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
search.go
Go
package spotify import ( "context" "strings" ) const ( // MarketFromToken can be used in place of the Options.Country parameter // if the Client has a valid access token. In this case, the // results will be limited to content that is playable in the // country associated with the user's account. The user must have // granted access to the user-read-private scope when the access // token was issued. MarketFromToken = "from_token" ) // SearchType represents the type of a query used by [Search]. type SearchType int // Search type values that can be passed to [Search]. These are flags // that can be bitwise OR'd together to search for multiple types of content // simultaneously. const ( SearchTypeAlbum SearchType = 1 << iota SearchTypeArtist = 1 << iota SearchTypePlaylist = 1 << iota SearchTypeTrack = 1 << iota SearchTypeShow = 1 << iota SearchTypeEpisode = 1 << iota ) func (st SearchType) encode() string { types := []string{} if st&SearchTypeAlbum != 0 { types = append(types, "album") } if st&SearchTypeArtist != 0 { types = append(types, "artist") } if st&SearchTypePlaylist != 0 { types = append(types, "playlist") } if st&SearchTypeTrack != 0 { types = append(types, "track") } if st&SearchTypeShow != 0 { types = append(types, "show") } if st&SearchTypeEpisode != 0 { types = append(types, "episode") } return strings.Join(types, ",") } // SearchResult contains the results of a call to [Search]. // Fields that weren't searched for will be nil pointers. type SearchResult struct { Artists *FullArtistPage `json:"artists"` Albums *SimpleAlbumPage `json:"albums"` Playlists *SimplePlaylistPage `json:"playlists"` Tracks *FullTrackPage `json:"tracks"` Shows *SimpleShowPage `json:"shows"` Episodes *SimpleEpisodePage `json:"episodes"` } // Search gets [Spotify catalog information] about artists, albums, tracks, // or playlists that match a keyword string. t is a mask containing one or more // search types. For example, `Search(query, SearchTypeArtist|SearchTypeAlbum)` // will search for artists or albums matching the specified keywords. // // # Matching // // Matching of search keywords is NOT case sensitive. Keywords are matched in // any order unless surrounded by double quotes. Searching for playlists will // return results where the query keyword(s) match any part of the playlist's // name or description. Only popular public playlists are returned. // // # Operators // // The operator NOT can be used to exclude results. For example, // query = "roadhouse NOT blues" returns items that match "roadhouse" but excludes // those that also contain the keyword "blues". Similarly, the OR operator can // be used to broaden the search. query = "roadhouse OR blues" returns all results // that include either of the terms. Only one OR operator can be used in a query. // // Operators should be specified in uppercase. // // # Wildcards // // The asterisk (*) character can, with some limitations, be used as a wildcard // (maximum of 2 per query). It will match a variable number of non-white-space // characters. It cannot be used in a quoted phrase, in a field filter, or as // the first character of a keyword string. // // # Field filters // // By default, results are returned when a match is found in any field of the // target object type. Searches can be made more specific by specifying an album, // artist, or track field filter. For example, "album:gold artist:abba type:album" // will only return results with the text "gold" in the album name and the text // "abba" in the artist's name. // // The field filter "year" can be used with album, artist, and track searches to // limit the results to a particular year. For example "bob year:2014" or // "bob year:1980-2020". // // The field filter "tag:new" can be used in album searches to retrieve only // albums released in the last two weeks. The field filter "tag:hipster" can be // used in album searches to retrieve only albums with the lowest 10% popularity. // // Other possible field filters, depending on object types being searched, // include "genre", "upc", and "isrc". For example "damian genre:reggae-pop". // // If the Market field is specified in the options, then the results will only // contain artists, albums, and tracks playable in the specified country // (playlist results are not affected by the Market option). Additionally, // the constant MarketFromToken can be used with authenticated clients. // If the client has a valid access token, then the results will only include // content playable in the user's country. // // Supported options: [Limit], [Market], [Offset]. // // [Spotify catalog information]: https://developer.spotify.com/documentation/web-api/reference/search func (c *Client) Search(ctx context.Context, query string, t SearchType, opts ...RequestOption) (*SearchResult, error) { v := processOptions(opts...).urlParams v.Set("q", query) v.Set("type", t.encode()) spotifyURL := c.baseURL + "search?" + v.Encode() var result SearchResult err := c.get(ctx, spotifyURL, &result) if err != nil { return nil, err } return &result, err } // NextArtistResults loads the next page of artists into the specified search result. func (c *Client) NextArtistResults(ctx context.Context, s *SearchResult) error { if s.Artists == nil || s.Artists.Next == "" { return ErrNoMorePages } return c.get(ctx, s.Artists.Next, s) } // PreviousArtistResults loads the previous page of artists into the specified search result. func (c *Client) PreviousArtistResults(ctx context.Context, s *SearchResult) error { if s.Artists == nil || s.Artists.Previous == "" { return ErrNoMorePages } return c.get(ctx, s.Artists.Previous, s) } // NextAlbumResults loads the next page of albums into the specified search result. func (c *Client) NextAlbumResults(ctx context.Context, s *SearchResult) error { if s.Albums == nil || s.Albums.Next == "" { return ErrNoMorePages } return c.get(ctx, s.Albums.Next, s) } // PreviousAlbumResults loads the previous page of albums into the specified search result. func (c *Client) PreviousAlbumResults(ctx context.Context, s *SearchResult) error { if s.Albums == nil || s.Albums.Previous == "" { return ErrNoMorePages } return c.get(ctx, s.Albums.Previous, s) } // NextPlaylistResults loads the next page of playlists into the specified search result. func (c *Client) NextPlaylistResults(ctx context.Context, s *SearchResult) error { if s.Playlists == nil || s.Playlists.Next == "" { return ErrNoMorePages } return c.get(ctx, s.Playlists.Next, s) } // PreviousPlaylistResults loads the previous page of playlists into the specified search result. func (c *Client) PreviousPlaylistResults(ctx context.Context, s *SearchResult) error { if s.Playlists == nil || s.Playlists.Previous == "" { return ErrNoMorePages } return c.get(ctx, s.Playlists.Previous, s) } // PreviousTrackResults loads the previous page of tracks into the specified search result. func (c *Client) PreviousTrackResults(ctx context.Context, s *SearchResult) error { if s.Tracks == nil || s.Tracks.Previous == "" { return ErrNoMorePages } return c.get(ctx, s.Tracks.Previous, s) } // NextTrackResults loads the next page of tracks into the specified search result. func (c *Client) NextTrackResults(ctx context.Context, s *SearchResult) error { if s.Tracks == nil || s.Tracks.Next == "" { return ErrNoMorePages } return c.get(ctx, s.Tracks.Next, s) } // PreviousShowResults loads the previous page of shows into the specified search result. func (c *Client) PreviousShowResults(ctx context.Context, s *SearchResult) error { if s.Shows == nil || s.Shows.Previous == "" { return ErrNoMorePages } return c.get(ctx, s.Shows.Previous, s) } // NextShowResults loads the next page of shows into the specified search result. func (c *Client) NextShowResults(ctx context.Context, s *SearchResult) error { if s.Shows == nil || s.Shows.Next == "" { return ErrNoMorePages } return c.get(ctx, s.Shows.Next, s) } // PreviousEpisodeResults loads the previous page of episodes into the specified search result. func (c *Client) PreviousEpisodeResults(ctx context.Context, s *SearchResult) error { if s.Episodes == nil || s.Episodes.Previous == "" { return ErrNoMorePages } return c.get(ctx, s.Episodes.Previous, s) } // NextEpisodeResults loads the next page of episodes into the specified search result. func (c *Client) NextEpisodeResults(ctx context.Context, s *SearchResult) error { if s.Episodes == nil || s.Episodes.Next == "" { return ErrNoMorePages } return c.get(ctx, s.Episodes.Next, s) }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
search_test.go
Go
package spotify import ( "context" "net/http" "testing" ) func TestSearchArtist(t *testing.T) { client, server := testClientFile(http.StatusOK, "test_data/search_artist.txt") defer server.Close() result, err := client.Search(context.Background(), "tania bowra", SearchTypeArtist) if err != nil { t.Error(err) } if result.Albums != nil { t.Error("Searched for artists but received album results") } if result.Playlists != nil { t.Error("Searched for artists but received playlist results") } if result.Tracks != nil { t.Error("Searched for artists but received track results") } if result.Artists == nil || len(result.Artists.Artists) == 0 { t.Error("Didn't receive artist results") } if result.Artists.Artists[0].Name != "Tania Bowra" { t.Error("Got wrong artist name") } } func TestSearchTracks(t *testing.T) { client, server := testClientFile(http.StatusOK, "test_data/search_tracks.txt") defer server.Close() result, err := client.Search(context.Background(), "uptown", SearchTypeTrack) if err != nil { t.Error(err) } if result.Albums != nil { t.Error("Searched for tracks but got album results") } if result.Playlists != nil { t.Error("Searched for tracks but got playlist results") } if result.Artists != nil { t.Error("Searched for tracks but got artist results") } if result.Tracks == nil || len(result.Tracks.Tracks) == 0 { t.Fatal("Didn't receive track results") } if name := result.Tracks.Tracks[0].Name; name != "Uptown Funk" { t.Errorf("Got %s, wanted Uptown Funk\n", name) } } func TestSearchPlaylistTrack(t *testing.T) { client, server := testClientFile(http.StatusOK, "test_data/search_trackplaylist.txt") defer server.Close() result, err := client.Search(context.Background(), "holiday", SearchTypePlaylist|SearchTypeTrack) if err != nil { t.Error(err) } if result.Albums != nil { t.Error("Searched for playlists and tracks but received album results") } if result.Artists != nil { t.Error("Searched for playlists and tracks but received artist results") } if result.Tracks == nil { t.Error("Didn't receive track results") } if result.Playlists == nil { t.Error("Didn't receive playlist results") } } func TestPrevNextSearchPageErrors(t *testing.T) { client, server := testClientString(0, "") defer server.Close() // we expect to get ErrNoMorePages when trying to get the prev/next page // under either of these conditions: // 1) there are no results (nil) nilResults := &SearchResult{nil, nil, nil, nil, nil, nil} if client.NextAlbumResults(context.Background(), nilResults) != ErrNoMorePages || client.NextArtistResults(context.Background(), nilResults) != ErrNoMorePages || client.NextPlaylistResults(context.Background(), nilResults) != ErrNoMorePages || client.NextTrackResults(context.Background(), nilResults) != ErrNoMorePages || client.NextShowResults(context.Background(), nilResults) != ErrNoMorePages || client.NextEpisodeResults(context.Background(), nilResults) != ErrNoMorePages { t.Error("Next search result page should have failed for nil results") } if client.PreviousAlbumResults(context.Background(), nilResults) != ErrNoMorePages || client.PreviousArtistResults(context.Background(), nilResults) != ErrNoMorePages || client.PreviousPlaylistResults(context.Background(), nilResults) != ErrNoMorePages || client.PreviousTrackResults(context.Background(), nilResults) != ErrNoMorePages || client.PreviousShowResults(context.Background(), nilResults) != ErrNoMorePages || client.PreviousEpisodeResults(context.Background(), nilResults) != ErrNoMorePages { t.Error("Previous search result page should have failed for nil results") } // 2) the prev/next URL is empty emptyURL := &SearchResult{ Artists: new(FullArtistPage), Albums: new(SimpleAlbumPage), Playlists: new(SimplePlaylistPage), Tracks: new(FullTrackPage), Shows: new(SimpleShowPage), Episodes: new(SimpleEpisodePage), } if client.NextAlbumResults(context.Background(), emptyURL) != ErrNoMorePages || client.NextArtistResults(context.Background(), emptyURL) != ErrNoMorePages || client.NextPlaylistResults(context.Background(), emptyURL) != ErrNoMorePages || client.NextTrackResults(context.Background(), emptyURL) != ErrNoMorePages || client.NextShowResults(context.Background(), emptyURL) != ErrNoMorePages || client.NextEpisodeResults(context.Background(), emptyURL) != ErrNoMorePages { t.Error("Next search result page should have failed with empty URL") } if client.PreviousAlbumResults(context.Background(), emptyURL) != ErrNoMorePages || client.PreviousArtistResults(context.Background(), emptyURL) != ErrNoMorePages || client.PreviousPlaylistResults(context.Background(), emptyURL) != ErrNoMorePages || client.PreviousTrackResults(context.Background(), emptyURL) != ErrNoMorePages || client.PreviousShowResults(context.Background(), emptyURL) != ErrNoMorePages || client.PreviousEpisodeResults(context.Background(), emptyURL) != ErrNoMorePages { t.Error("Previous search result page should have failed with empty URL") } }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
show.go
Go
package spotify import ( "context" "net/http" "strconv" "strings" "time" ) type SavedShow struct { // The date and time the show was saved, represented as an ISO 8601 UTC // timestamp with a zero offset (YYYY-MM-DDTHH:MM:SSZ). You can use // [TimestampLayout] to convert this to a [time.Time]. AddedAt string `json:"added_at"` FullShow `json:"show"` } // FullShow contains full data about a show. type FullShow struct { SimpleShow // A list of the show’s episodes. Episodes SimpleEpisodePage `json:"episodes"` } // SimpleShow contains basic data about a show. type SimpleShow struct { // A list of the countries in which the show can be played, // identified by their [ISO 3166-1 alpha-2] code. // // [ISO 3166-1 alpha-2]: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 AvailableMarkets []string `json:"available_markets"` // The copyright statements of the show. Copyrights []Copyright `json:"copyrights"` // A description of the show. Description string `json:"description"` // Whether or not the show has explicit content // (true = yes it does; false = no it does not OR unknown). Explicit bool `json:"explicit"` // Known external URLs for this show. ExternalURLs map[string]string `json:"external_urls"` // A link to the Web API endpoint providing full details // of the show. Href string `json:"href"` // The SpotifyID for the show. ID ID `json:"id"` // The cover art for the show in various sizes, // widest first. Images []Image `json:"images"` // True if all of the show’s episodes are hosted outside // of Spotify’s CDN. This field might be null in some cases. IsExternallyHosted *bool `json:"is_externally_hosted"` // A list of the languages used in the show, identified by // their [ISO 639] code. // // [ISO 639]: https://en.wikipedia.org/wiki/ISO_639 Languages []string `json:"languages"` // The media type of the show. MediaType string `json:"media_type"` // The name of the show. Name string `json:"name"` // The publisher of the show. Publisher string `json:"publisher"` // The object type: “show”. Type string `json:"type"` // The Spotify URI for the show. URI URI `json:"uri"` } type EpisodePage struct { // A URL to a 30 second preview (MP3 format) of the episode. AudioPreviewURL string `json:"audio_preview_url"` // A description of the episode. Description string `json:"description"` // The episode length in milliseconds. Duration_ms Numeric `json:"duration_ms"` // Whether or not the episode has explicit content // (true = yes it does; false = no it does not OR unknown). Explicit bool `json:"explicit"` // External URLs for this episode. ExternalURLs map[string]string `json:"external_urls"` // A link to the Web API endpoint providing full details of the episode. Href string `json:"href"` // The [Spotify ID] for the episode. // // [Spotify ID]: https://developer.spotify.com/documentation/web-api/#spotify-uris-and-ids ID ID `json:"id"` // The cover art for the episode in various sizes, widest first. Images []Image `json:"images"` // True if the episode is hosted outside of Spotify’s CDN. IsExternallyHosted bool `json:"is_externally_hosted"` // True if the episode is playable in the given market. // Otherwise false. IsPlayable bool `json:"is_playable"` // A list of the languages used in the episode, identified by their [ISO 639] code. // // [ISO 639]: https://en.wikipedia.org/wiki/ISO_639 Languages []string `json:"languages"` // The name of the episode. Name string `json:"name"` // The date the episode was first released, for example // "1981-12-15". Depending on the precision, it might // be shown as "1981" or "1981-12". ReleaseDate string `json:"release_date"` // The precision with which release_date value is known: // "year", "month", or "day". ReleaseDatePrecision string `json:"release_date_precision"` // The user’s most recent position in the episode. Set if the // supplied access token is a user token and has the scope // user-read-playback-position. ResumePoint ResumePointObject `json:"resume_point"` // The show on which the episode belongs. Show SimpleShow `json:"show"` // The object type: "episode". Type string `json:"type"` // The Spotify URI for the episode. URI URI `json:"uri"` } type ResumePointObject struct { // Whether or not the episode has been fully played by the user. FullyPlayed bool `json:"fully_played"` // The user’s most recent position in the episode in milliseconds. ResumePositionMs Numeric `json:"resume_position_ms"` } // ReleaseDateTime converts [EpisodePage.ReleaseDate] to a [time.Time]. // All of the fields in the result may not be valid. For example, if // [EpisodePage.ReleaseDatePrecision] is "month", then only the month and year // (but not the day) of the result are valid. func (e *EpisodePage) ReleaseDateTime() time.Time { if e.ReleaseDatePrecision == "day" { result, _ := time.Parse(DateLayout, e.ReleaseDate) return result } if e.ReleaseDatePrecision == "month" { ym := strings.Split(e.ReleaseDate, "-") year, _ := strconv.Atoi(ym[0]) month, _ := strconv.Atoi(ym[1]) return time.Date(year, time.Month(month), 1, 0, 0, 0, 0, time.UTC) } year, _ := strconv.Atoi(e.ReleaseDate) return time.Date(year, 1, 1, 0, 0, 0, 0, time.UTC) } // GetShow retrieves information about a [specific show]. // // Supported options: [Market]. // // [specific show]: https://developer.spotify.com/documentation/web-api/reference/get-a-show func (c *Client) GetShow(ctx context.Context, id ID, opts ...RequestOption) (*FullShow, error) { spotifyURL := c.baseURL + "shows/" + string(id) if params := processOptions(opts...).urlParams.Encode(); params != "" { spotifyURL += "?" + params } var result FullShow err := c.get(ctx, spotifyURL, &result) if err != nil { return nil, err } return &result, nil } // GetShowEpisodes retrieves paginated [episode information] about a specific show. // // Supported options: [Market], [Limit], [Offset]. // // [episode information]: https://developer.spotify.com/documentation/web-api/reference/get-a-shows-episodes func (c *Client) GetShowEpisodes(ctx context.Context, id string, opts ...RequestOption) (*SimpleEpisodePage, error) { spotifyURL := c.baseURL + "shows/" + id + "/episodes" if params := processOptions(opts...).urlParams.Encode(); params != "" { spotifyURL += "?" + params } var result SimpleEpisodePage err := c.get(ctx, spotifyURL, &result) if err != nil { return nil, err } return &result, nil } // SaveShowsForCurrentUser [saves one or more shows] to current Spotify user's library. // // [saves one or more shows]: https://developer.spotify.com/documentation/web-api/reference/save-shows-user func (c *Client) SaveShowsForCurrentUser(ctx context.Context, ids []ID) error { spotifyURL := c.baseURL + "me/shows?ids=" + strings.Join(toStringSlice(ids), ",") req, err := http.NewRequestWithContext(ctx, http.MethodPut, spotifyURL, nil) if err != nil { return err } return c.execute(req, nil, http.StatusOK) } // GetEpisode gets an [episode] from a show. // // [episode]: https://developer.spotify.com/documentation/web-api/reference/get-an-episode func (c *Client) GetEpisode(ctx context.Context, id string, opts ...RequestOption) (*EpisodePage, error) { spotifyURL := c.baseURL + "episodes/" + id if params := processOptions(opts...).urlParams.Encode(); params != "" { spotifyURL += "?" + params } var result EpisodePage err := c.get(ctx, spotifyURL, &result) if err != nil { return nil, err } return &result, nil }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
show_test.go
Go
package spotify import ( "bytes" "context" "net/http" "testing" ) func TestGetShow(t *testing.T) { c, s := testClientFile(http.StatusOK, "test_data/get_show.txt") defer s.Close() r, err := c.GetShow(context.Background(), "1234") if err != nil { t.Fatal(err) } if r.SimpleShow.Name != "Uncommon Core" { t.Error("Invalid data:", r.Name) } if len(r.Episodes.Episodes) != 25 { t.Error("Invalid data", len(r.Episodes.Episodes)) } } func TestGetShowEpisodes(t *testing.T) { c, s := testClientFile(http.StatusOK, "test_data/get_show_episodes.txt") defer s.Close() r, err := c.GetShowEpisodes(context.Background(), "1234") if err != nil { t.Fatal(err) } if r.Total != 25 { t.Error("Invalid data:", r.Total) } if r.Offset != 0 { t.Error("Invalid data:", r.Offset) } if len(r.Episodes) != 25 { t.Error("Invalid data", len(r.Episodes)) } } func TestSaveShowsForCurrentUser(t *testing.T) { c, s := testClient(http.StatusOK, new(bytes.Buffer), func(req *http.Request) { if ids := req.URL.Query().Get("ids"); ids != "1,2" { t.Error("Invalid data:", ids) } }) defer s.Close() err := c.SaveShowsForCurrentUser(context.Background(), []ID{"1", "2"}) if err != nil { t.Fatal(err) } } func TestSaveShowsForCurrentUser_Errors(t *testing.T) { c, s := testClient(http.StatusInternalServerError, new(bytes.Buffer)) defer s.Close() err := c.SaveShowsForCurrentUser(context.Background(), []ID{"1"}) if err == nil { t.Fatal(err) } } func TestGetEpisode(t *testing.T) { c, s := testClientFile(http.StatusOK, "test_data/get_episode.txt") defer s.Close() id := "2DSKnz9Hqm1tKimcXqcMJD" r, err := c.GetEpisode(context.Background(), id) if err != nil { t.Fatal(err) } if r.ID.String() != id { t.Error("Invalid data:", r.ID) } if r.Type != "episode" { t.Error("Invalid data:", r.ID) } }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
spotify.go
Go
// Package spotify provides utilities for interfacing // with Spotify's Web API. package spotify import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "net/http" "strconv" "time" "golang.org/x/oauth2" ) const ( // DateLayout can be used with time.Parse to create time.Time values // from Spotify date strings. For example, PrivateUser.Birthdate // uses this format. DateLayout = "2006-01-02" // TimestampLayout can be used with time.Parse to create time.Time // values from SpotifyTimestamp strings. It is an ISO 8601 UTC timestamp // with a zero offset. For example, PlaylistTrack's AddedAt field uses // this format. TimestampLayout = "2006-01-02T15:04:05Z" // defaultRetryDurationS helps us fix an apparent server bug whereby we will // be told to retry but not be given a wait-interval. defaultRetryDuration = time.Second * 5 ) // Client is a client for working with the Spotify Web API. // It is best to create this using spotify.New() type Client struct { http *http.Client baseURL string autoRetry bool acceptLanguage string } type ClientOption func(client *Client) // WithRetry configures the Spotify API client to automatically retry requests that fail due to rate limiting. func WithRetry(shouldRetry bool) ClientOption { return func(client *Client) { client.autoRetry = shouldRetry } } // WithBaseURL provides an alternative base url to use for requests to the Spotify API. This can be used to connect to a // staging or other alternative environment. func WithBaseURL(url string) ClientOption { return func(client *Client) { client.baseURL = url } } // WithAcceptLanguage configures the client to provide the accept language header on all requests. func WithAcceptLanguage(lang string) ClientOption { return func(client *Client) { client.acceptLanguage = lang } } // New returns a client for working with the Spotify Web API. // The provided httpClient must provide Authentication with the requests. // The auth package may be used to generate a suitable client. func New(httpClient *http.Client, opts ...ClientOption) *Client { c := &Client{ http: httpClient, baseURL: "https://api.spotify.com/v1/", } for _, opt := range opts { opt(c) } return c } // URI identifies an artist, album, track, or category. For example, // spotify:track:6rqhFgbbKwnb9MLmUQDhG6 type URI string // ID is a base-62 identifier for an artist, track, album, etc. // It can be found at the end of a spotify.URI. type ID string func (id *ID) String() string { return string(*id) } // Numeric is a convenience type for handling numbers sent as either integers or floats. type Numeric int // UnmarshalJSON unmarshals a JSON number (float or int) into the Numeric type. func (n *Numeric) UnmarshalJSON(data []byte) error { var f float64 if err := json.Unmarshal(data, &f); err != nil { return err } *n = Numeric(int(f)) return nil } // Followers contains information about the number of people following a // particular artist or playlist. type Followers struct { // The total number of followers. Count Numeric `json:"total"` // A link to the Web API endpoint providing full details of the followers, // or the empty string if this data is not available. Endpoint string `json:"href"` } // Image identifies an image associated with an item. type Image struct { // The image height, in pixels. Height Numeric `json:"height"` // The image width, in pixels. Width Numeric `json:"width"` // The source URL of the image. URL string `json:"url"` } // Download downloads the image and writes its data to the specified io.Writer. func (i Image) Download(dst io.Writer) error { resp, err := http.Get(i.URL) if err != nil { return err } defer resp.Body.Close() // TODO: get Content-Type from header? if resp.StatusCode != http.StatusOK { return errors.New("Couldn't download image - HTTP" + strconv.Itoa(resp.StatusCode)) } _, err = io.Copy(dst, resp.Body) return err } // Error represents an error returned by the Spotify Web API. type Error struct { // A short description of the error. Message string `json:"message"` // The HTTP status code. Status int `json:"status"` // RetryAfter contains the time before which client should not retry a // rate-limited request, calculated from the Retry-After header, when present. RetryAfter time.Time `json:"-"` } func (e Error) Error() string { return fmt.Sprintf("spotify: %s [%d]", e.Message, e.Status) } // HTTPStatus returns the HTTP status code returned by the server when the error // occurred. func (e Error) HTTPStatus() int { return e.Status } // decodeError decodes an Error from an io.Reader. func decodeError(resp *http.Response) error { responseBody, err := io.ReadAll(resp.Body) if err != nil { return err } if ctHeader := resp.Header.Get("Content-Type"); ctHeader == "" { msg := string(responseBody) if len(msg) == 0 { msg = http.StatusText(resp.StatusCode) } return Error{ Message: msg, Status: resp.StatusCode, } } if len(responseBody) == 0 { return Error{ Message: "server response without body", Status: resp.StatusCode, } } buf := bytes.NewBuffer(responseBody) var e struct { E Error `json:"error"` } err = json.NewDecoder(buf).Decode(&e) if err != nil { return Error{ Message: fmt.Sprintf("failed to decode error response %q", responseBody), Status: resp.StatusCode, } } e.E.Status = resp.StatusCode if e.E.Message == "" { // Some errors will result in there being a useful status-code but an // empty message. An example of this is when we send some of the // arguments directly in the HTTP query and the URL ends-up being too // long. e.E.Message = "server response without error description" } if retryAfter, _ := strconv.Atoi(resp.Header.Get("Retry-After")); retryAfter != 0 { e.E.RetryAfter = time.Now().Add(time.Duration(retryAfter) * time.Second) } return e.E } // shouldRetry determines whether the status code indicates that the // previous operation should be retried at a later time func shouldRetry(status int) bool { return status == http.StatusAccepted || status == http.StatusTooManyRequests } // isFailure determines whether the code indicates failure func isFailure(code int, validCodes []int) bool { for _, item := range validCodes { if item == code { return false } } return true } // `execute` executes a non-GET request. `needsStatus` describes other HTTP // status codes that will be treated as success. Note that we allow all 200s // even if there are additional success codes that represent success. func (c *Client) execute(req *http.Request, result interface{}, needsStatus ...int) error { if c.acceptLanguage != "" { req.Header.Set("Accept-Language", c.acceptLanguage) } for { resp, err := c.http.Do(req) if err != nil { return err } defer resp.Body.Close() if c.autoRetry && isFailure(resp.StatusCode, needsStatus) && shouldRetry(resp.StatusCode) { select { case <-req.Context().Done(): // If the context is cancelled, return the original error case <-time.After(retryDuration(resp)): continue } } if resp.StatusCode == http.StatusNoContent { return nil } if (resp.StatusCode >= 300 || resp.StatusCode < 200) && isFailure(resp.StatusCode, needsStatus) { return decodeError(resp) } if result != nil { if err := json.NewDecoder(resp.Body).Decode(result); err != nil { return err } } break } return nil } func retryDuration(resp *http.Response) time.Duration { raw := resp.Header.Get("Retry-After") if raw == "" { return defaultRetryDuration } seconds, err := strconv.ParseInt(raw, 10, 32) if err != nil { return defaultRetryDuration } return time.Duration(seconds) * time.Second } func (c *Client) get(ctx context.Context, url string, result interface{}) error { for { req, err := http.NewRequestWithContext(ctx, "GET", url, nil) if c.acceptLanguage != "" { req.Header.Set("Accept-Language", c.acceptLanguage) } if err != nil { return err } resp, err := c.http.Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode == http.StatusTooManyRequests && c.autoRetry { select { case <-ctx.Done(): // If the context is cancelled, return the original error case <-time.After(retryDuration(resp)): continue } } if resp.StatusCode == http.StatusNoContent { return nil } if resp.StatusCode != http.StatusOK { return decodeError(resp) } return json.NewDecoder(resp.Body).Decode(result) } } // NewReleases gets a list of new album releases featured in Spotify. // Supported options: Country, Limit, Offset func (c *Client) NewReleases(ctx context.Context, opts ...RequestOption) (albums *SimpleAlbumPage, err error) { spotifyURL := c.baseURL + "browse/new-releases" if params := processOptions(opts...).urlParams.Encode(); params != "" { spotifyURL += "?" + params } var objmap map[string]*json.RawMessage err = c.get(ctx, spotifyURL, &objmap) if err != nil { return nil, err } var result SimpleAlbumPage err = json.Unmarshal(*objmap["albums"], &result) if err != nil { return nil, err } return &result, nil } // Token gets the client's current token. func (c *Client) Token() (*oauth2.Token, error) { transport, ok := c.http.Transport.(*oauth2.Transport) if !ok { return nil, errors.New("spotify: client not backed by oauth2 transport") } t, err := transport.Source.Token() if err != nil { return nil, err } return t, nil }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
spotify_test.go
Go
package spotify import ( "context" "errors" "io" "net/http" "net/http/httptest" "os" "strconv" "strings" "testing" "time" "golang.org/x/oauth2" ) func testClient(code int, body io.Reader, validators ...func(*http.Request)) (*Client, *httptest.Server) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { for _, v := range validators { v(r) } w.WriteHeader(code) _, _ = io.Copy(w, body) r.Body.Close() if closer, ok := body.(io.Closer); ok { closer.Close() } })) client := &Client{ http: http.DefaultClient, baseURL: server.URL + "/", } return client, server } // Returns a client whose requests will always return // the specified status code and body. func testClientString(code int, body string, validators ...func(*http.Request)) (*Client, *httptest.Server) { return testClient(code, strings.NewReader(body), validators...) } // Returns a client whose requests will always return // a response with the specified status code and a body // that is read from the specified file. func testClientFile(code int, filename string, validators ...func(*http.Request)) (*Client, *httptest.Server) { f, err := os.Open(filename) if err != nil { panic(err) } return testClient(code, f, validators...) } func TestNewReleases(t *testing.T) { c, s := testClientFile(http.StatusOK, "test_data/new_releases.txt") defer s.Close() r, err := c.NewReleases(context.Background()) if err != nil { t.Fatal(err) } if r.Albums[0].ID != "60mvULtYiNSRmpVvoa3RE4" { t.Error("Invalid data:", r.Albums[0].ID) } if r.Albums[0].Name != "We Are One (Ole Ola) [The Official 2014 FIFA World Cup Song]" { t.Error("Invalid data", r.Albums[0].Name) } } func TestNewReleasesRateLimitExceeded(t *testing.T) { t.Parallel() handlers := []http.HandlerFunc{ // first attempt fails http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Retry-After", "2") w.WriteHeader(http.StatusTooManyRequests) _, _ = io.WriteString(w, `{ "error": { "message": "slow down", "status": 429 } }`) }), // next attempt succeeds http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { f, err := os.Open("test_data/new_releases.txt") if err != nil { t.Fatal(err) } defer f.Close() _, err = io.Copy(w, f) if err != nil { t.Fatal(err) } }), } i := 0 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { handlers[i](w, r) i++ })) defer server.Close() client := &Client{http: http.DefaultClient, baseURL: server.URL + "/", autoRetry: true} releases, err := client.NewReleases(context.Background()) if err != nil { t.Fatal(err) } if releases.Albums[0].ID != "60mvULtYiNSRmpVvoa3RE4" { t.Error("Invalid data:", releases.Albums[0].ID) } } func TestRateLimitExceededReportsRetryAfter(t *testing.T) { t.Parallel() const retryAfter = 2 handlers := []http.HandlerFunc{ // first attempt fails http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Retry-After", strconv.Itoa(retryAfter)) w.WriteHeader(http.StatusTooManyRequests) _, _ = io.WriteString(w, `{ "error": { "message": "slow down", "status": 429 } }`) }), // next attempt succeeds http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { f, err := os.Open("test_data/new_releases.txt") if err != nil { t.Fatal(err) } defer f.Close() _, err = io.Copy(w, f) if err != nil { t.Fatal(err) } }), } i := 0 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { handlers[i](w, r) i++ })) defer server.Close() client := &Client{http: http.DefaultClient, baseURL: server.URL + "/"} _, err := client.NewReleases(context.Background()) if err == nil { t.Fatal("expected an error") } var spotifyError Error if !errors.As(err, &spotifyError) { t.Fatalf("expected a spotify error, got %T", err) } if retryAfter*time.Second-time.Until(spotifyError.RetryAfter) > time.Second { t.Error("expected RetryAfter value") } } func TestClient_Token(t *testing.T) { // oauth setup for valid test token config := oauth2.Config{ ClientID: "test_client", ClientSecret: "test_client_secret", Endpoint: oauth2.Endpoint{}, RedirectURL: "http://redirect.redirect", Scopes: nil, } token := &oauth2.Token{ AccessToken: "access_token", TokenType: "test_type", RefreshToken: "refresh_token", Expiry: time.Now().Add(time.Hour), } t.Run("success", func(t *testing.T) { httpClient := config.Client(context.Background(), token) client := New(httpClient) token, err := client.Token() if err != nil { t.Error(err) } if !token.Valid() { t.Errorf("Token should be valid: %v", token) } if token.AccessToken != "access_token" { t.Errorf("Invalid access token data: %s", token.AccessToken) } if token.RefreshToken != "refresh_token" { t.Errorf("Invalid refresh token data: %s", token.RefreshToken) } if token.TokenType != "test_type" { t.Errorf("Invalid token type: %s", token.TokenType) } }) t.Run("non oauth2 transport", func(t *testing.T) { client := &Client{ http: http.DefaultClient, } _, err := client.Token() if err == nil || err.Error() != "spotify: client not backed by oauth2 transport" { t.Errorf("Should throw error: %s", "spotify: client not backed by oauth2 transport") } }) t.Run("invalid token", func(t *testing.T) { httpClient := config.Client(context.Background(), nil) client := New(httpClient) _, err := client.Token() if err == nil || err.Error() != "oauth2: token expired and refresh token is not set" { t.Errorf("Should throw error: %s", "oauth2: token expired and refresh token is not set") } }) } func TestDecode429Error(t *testing.T) { resp := &http.Response{ StatusCode: http.StatusTooManyRequests, Header: http.Header{"Retry-After": []string{"2"}}, Body: io.NopCloser(strings.NewReader(`Too many requests`)), } err := decodeError(resp) if err == nil { t.Fatal("Expected error") } if err.Error() != "spotify: Too many requests [429]" { t.Error("Unexpected error message:", err.Error()) } const wantSTatus = http.StatusTooManyRequests var gotStatus int var statusErr interface{ HTTPStatus() int } if errors.As(err, &statusErr) { gotStatus = statusErr.HTTPStatus() } if gotStatus != wantSTatus { t.Errorf("Expected status %d, got %d", wantSTatus, gotStatus) } }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
track.go
Go
package spotify import ( "context" "errors" "fmt" "strings" "time" ) type TrackExternalIDs struct { ISRC string `json:"isrc"` EAN string `json:"ean"` UPC string `json:"upc"` } // SimpleTrack contains basic info about a track. type SimpleTrack struct { Album SimpleAlbum `json:"album"` Artists []SimpleArtist `json:"artists"` // A list of the countries in which the track can be played, // identified by their [ISO 3166-1 alpha-2] codes. // // [ISO 3166-1 alpha=2]: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 AvailableMarkets []string `json:"available_markets"` // The disc number (usually 1 unless the album consists of more than one disc). DiscNumber Numeric `json:"disc_number"` // The length of the track, in milliseconds. Duration Numeric `json:"duration_ms"` // Whether or not the track has explicit lyrics. // true => yes, it does; false => no, it does not. Explicit bool `json:"explicit"` // External URLs for this track. ExternalURLs map[string]string `json:"external_urls"` // ExternalIDs are IDs for this track in other databases ExternalIDs TrackExternalIDs `json:"external_ids"` // A link to the Web API endpoint providing full details for this track. Endpoint string `json:"href"` ID ID `json:"id"` Name string `json:"name"` // A URL to a 30 second preview (MP3) of the track. PreviewURL string `json:"preview_url"` // The number of the track. If an album has several // discs, the track number is the number on the specified // DiscNumber. TrackNumber Numeric `json:"track_number"` URI URI `json:"uri"` // Type of the track Type string `json:"type"` } func (st SimpleTrack) String() string { return fmt.Sprintf("TRACK<[%s] [%s]>", st.ID, st.Name) } // LinkedFromInfo is included in a track response when [Track Relinking] is applied. // // [Track Relinking]: https://developer.spotify.com/documentation/general/guides/track-relinking-guide/ type LinkedFromInfo struct { // ExternalURLs are the known external APIs for this track or album ExternalURLs map[string]string `json:"external_urls"` // Href is a link to the Web API endpoint providing full details Href string `json:"href"` // ID of the linked track ID ID `json:"id"` // Type of the link: album of the track Type string `json:"type"` // URI is the [Spotify URI] of the track/album. // // [Spotify URI]: https://developer.spotify.com/documentation/web-api/#spotify-uris-and-ids URI string `json:"uri"` } // FullTrack provides extra track data in addition to what is provided by [SimpleTrack]. type FullTrack struct { SimpleTrack // Popularity of the track. The value will be between 0 and 100, // with 100 being the most popular. The popularity is calculated from // both total plays and most recent plays. Popularity Numeric `json:"popularity"` // IsPlayable is included when [Track Relinking] is applied, and reports if // the track is playable. It's reported when the "market" parameter is // passed to the tracks listing API. // // [Track Relinking]: https://developer.spotify.com/documentation/general/guides/track-relinking-guide/ IsPlayable *bool `json:"is_playable"` // LinkedFromInfo is included in a track response when [Track Relinking] is // applied, and points to the linked track. It's reported when the "market" // parameter is passed to the tracks listing API. // // [Track Relinking]: https://developer.spotify.com/documentation/general/guides/track-relinking-guide/ LinkedFrom *LinkedFromInfo `json:"linked_from"` } // PlaylistTrack contains info about a track in a playlist. type PlaylistTrack struct { // The date and time the track was added to the playlist. You can use // [TimestampLayout] to convert this field to a [time.Time]. // Warning: very old playlists may not populate this value. AddedAt string `json:"added_at"` // The Spotify user who added the track to the playlist. // Warning: vary old playlists may not populate this value. AddedBy User `json:"added_by"` // Whether this track is a local file or not. IsLocal bool `json:"is_local"` // Information about the track. Track FullTrack `json:"track"` } // SavedTrack provides info about a track saved to a user's account. type SavedTrack struct { // The date and time the track was saved, represented as an ISO 8601 UTC // timestamp with a zero offset (YYYY-MM-DDTHH:MM:SSZ). You can use // [TimestampLayout] to convert this to a [time.Time]. AddedAt string `json:"added_at"` FullTrack `json:"track"` } // TimeDuration returns the track's duration as a [time.Duration] value. func (t *SimpleTrack) TimeDuration() time.Duration { return time.Duration(t.Duration) * time.Millisecond } // GetTrack gets Spotify catalog information for // a [single track] identified by its unique [Spotify ID]. // // Supported options: [Market]. // // [single track]: https://developer.spotify.com/documentation/web-api/reference/get-track // [Spotify ID]: https://developer.spotify.com/documentation/web-api/#spotify-uris-and-ids func (c *Client) GetTrack(ctx context.Context, id ID, opts ...RequestOption) (*FullTrack, error) { spotifyURL := c.baseURL + "tracks/" + string(id) var t FullTrack if params := processOptions(opts...).urlParams.Encode(); params != "" { spotifyURL += "?" + params } err := c.get(ctx, spotifyURL, &t) if err != nil { return nil, err } return &t, nil } // GetTracks gets Spotify catalog information for [multiple tracks] based on their // Spotify IDs. It supports up to 50 tracks in a single call. Tracks are // returned in the order requested. If a track is not found, that position in the // result will be nil. Duplicate ids in the query will result in duplicate // tracks in the result. // // Supported options: [Market]. // // [multiple tracks]: https://developer.spotify.com/documentation/web-api/reference/get-several-tracks func (c *Client) GetTracks(ctx context.Context, ids []ID, opts ...RequestOption) ([]*FullTrack, error) { if len(ids) > 50 { return nil, errors.New("spotify: FindTracks supports up to 50 tracks") } params := processOptions(opts...).urlParams params.Set("ids", strings.Join(toStringSlice(ids), ",")) spotifyURL := c.baseURL + "tracks?" + params.Encode() var t struct { Tracks []*FullTrack `json:"tracks"` } err := c.get(ctx, spotifyURL, &t) if err != nil { return nil, err } return t.Tracks, nil }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
track_attributes.go
Go
package spotify // TrackAttributes contains various tuneable parameters that can be used for recommendations. // For each of the tuneable track attributes, target, min and max values may be provided. // // Target: // // Tracks with the attribute values nearest to the target values will be preferred. // For example, you might request TargetEnergy=0.6 and TargetDanceability=0.8. // All target values will be weighed equally in ranking results. // // Max: // // A hard ceiling on the selected track attribute’s value can be provided. // For example, MaxInstrumentalness=0.35 would filter out most tracks // that are likely to be instrumental. // // Min: // // A hard floor on the selected track attribute’s value can be provided. // For example, min_tempo=140 would restrict results to only those tracks // with a tempo of greater than 140 beats per minute. type TrackAttributes struct { intAttributes map[string]int floatAttributes map[string]float64 } // NewTrackAttributes returns a new [TrackAttributes] instance with no attributes set. // Attributes can then be chained following a builder pattern: // // ta := NewTrackAttributes(). // MaxAcousticness(0.15). // TargetPopularity(90) func NewTrackAttributes() *TrackAttributes { return &TrackAttributes{ intAttributes: map[string]int{}, floatAttributes: map[string]float64{}, } } // MaxAcousticness sets the maximum acousticness. // Acousticness is a confidence measure from 0.0 to 1.0 of whether // the track is acoustic. A value of 1.0 represents high confidence // that the track is acoustic. func (ta *TrackAttributes) MaxAcousticness(acousticness float64) *TrackAttributes { ta.floatAttributes["max_acousticness"] = acousticness return ta } // MinAcousticness sets the minimum acousticness. // Acousticness is a confidence measure from 0.0 to 1.0 of whether // the track is acoustic. A value of 1.0 represents high confidence // that the track is acoustic. func (ta *TrackAttributes) MinAcousticness(acousticness float64) *TrackAttributes { ta.floatAttributes["min_acousticness"] = acousticness return ta } // TargetAcousticness sets the target acousticness. // Acousticness is a confidence measure from 0.0 to 1.0 of whether // the track is acoustic. A value of 1.0 represents high confidence // that the track is acoustic. func (ta *TrackAttributes) TargetAcousticness(acousticness float64) *TrackAttributes { ta.floatAttributes["target_acousticness"] = acousticness return ta } // MaxDanceability sets the maximum danceability. // Danceability describes how suitable a track is for dancing based on // a combination of musical elements including tempo, rhythm stability, // beat strength, and overall regularity. // A value of 0.0 is least danceable and 1.0 is most danceable. func (ta *TrackAttributes) MaxDanceability(danceability float64) *TrackAttributes { ta.floatAttributes["max_danceability"] = danceability return ta } // MinDanceability sets the minimum danceability. // Danceability describes how suitable a track is for dancing based on // a combination of musical elements including tempo, rhythm stability, // beat strength, and overall regularity. // A value of 0.0 is least danceable and 1.0 is most danceable. func (ta *TrackAttributes) MinDanceability(danceability float64) *TrackAttributes { ta.floatAttributes["min_danceability"] = danceability return ta } // TargetDanceability sets the target danceability. // Danceability describes how suitable a track is for dancing based on // a combination of musical elements including tempo, rhythm stability, // beat strength, and overall regularity. // A value of 0.0 is least danceable and 1.0 is most danceable. func (ta *TrackAttributes) TargetDanceability(danceability float64) *TrackAttributes { ta.floatAttributes["target_danceability"] = danceability return ta } // MaxDuration sets the maximum length of the track in milliseconds. func (ta *TrackAttributes) MaxDuration(duration int) *TrackAttributes { ta.intAttributes["max_duration_ms"] = duration return ta } // MinDuration sets the minimum length of the track in milliseconds. func (ta *TrackAttributes) MinDuration(duration int) *TrackAttributes { ta.intAttributes["min_duration_ms"] = duration return ta } // TargetDuration sets the target length of the track in milliseconds. func (ta *TrackAttributes) TargetDuration(duration int) *TrackAttributes { ta.intAttributes["target_duration_ms"] = duration return ta } // MaxEnergy sets the maximum energy. // Energy is a measure from 0.0 to 1.0 and represents a perceptual measure // of intensity and activity. Typically, energetic tracks feel fast, loud, // and noisy. func (ta *TrackAttributes) MaxEnergy(energy float64) *TrackAttributes { ta.floatAttributes["max_energy"] = energy return ta } // MinEnergy sets the minimum energy. // Energy is a measure from 0.0 to 1.0 and represents a perceptual measure // of intensity and activity. Typically, energetic tracks feel fast, loud, // and noisy. func (ta *TrackAttributes) MinEnergy(energy float64) *TrackAttributes { ta.floatAttributes["min_energy"] = energy return ta } // TargetEnergy sets the target energy. // Energy is a measure from 0.0 to 1.0 and represents a perceptual measure // of intensity and activity. Typically, energetic tracks feel fast, loud, // and noisy. func (ta *TrackAttributes) TargetEnergy(energy float64) *TrackAttributes { ta.floatAttributes["target_energy"] = energy return ta } // MaxInstrumentalness sets the maximum instrumentalness. // Instrumentalness predicts whether a track contains no vocals. // "Ooh" and "aah" sounds are treated as instrumental in this context. // Rap or spoken word tracks are clearly "vocal". // The closer the instrumentalness value is to 1.0, // the greater likelihood the track contains no vocal content. // Values above 0.5 are intended to represent instrumental tracks, // but confidence is higher as the value approaches 1.0. func (ta *TrackAttributes) MaxInstrumentalness(instrumentalness float64) *TrackAttributes { ta.floatAttributes["max_instrumentalness"] = instrumentalness return ta } // MinInstrumentalness sets the minimum instrumentalness. // Instrumentalness predicts whether a track contains no vocals. // "Ooh" and "aah" sounds are treated as instrumental in this context. // Rap or spoken word tracks are clearly "vocal". // The closer the instrumentalness value is to 1.0, // the greater likelihood the track contains no vocal content. // Values above 0.5 are intended to represent instrumental tracks, // but confidence is higher as the value approaches 1.0. func (ta *TrackAttributes) MinInstrumentalness(instrumentalness float64) *TrackAttributes { ta.floatAttributes["min_instrumentalness"] = instrumentalness return ta } // TargetInstrumentalness sets the target instrumentalness. // Instrumentalness predicts whether a track contains no vocals. // "Ooh" and "aah" sounds are treated as instrumental in this context. // Rap or spoken word tracks are clearly "vocal". // The closer the instrumentalness value is to 1.0, // the greater likelihood the track contains no vocal content. // Values above 0.5 are intended to represent instrumental tracks, // but confidence is higher as the value approaches 1.0. func (ta *TrackAttributes) TargetInstrumentalness(instrumentalness float64) *TrackAttributes { ta.floatAttributes["target_instrumentalness"] = instrumentalness return ta } // MaxKey sets the maximum key. // Integers map to pitches using standard [Pitch Class] notation // // [Pitch Class]: https://en.wikipedia.org/wiki/Pitch_class func (ta *TrackAttributes) MaxKey(key int) *TrackAttributes { ta.intAttributes["max_key"] = key return ta } // MinKey sets the minimum key. // Integers map to pitches using standard [Pitch Class] notation // // [Pitch Class]: https://en.wikipedia.org/wiki/Pitch_class func (ta *TrackAttributes) MinKey(key int) *TrackAttributes { ta.intAttributes["min_key"] = key return ta } // TargetKey sets the target key. // Integers map to pitches using standard [Pitch Class] notation. // // [Pitch Class]: https://en.wikipedia.org/wiki/Pitch_class func (ta *TrackAttributes) TargetKey(key int) *TrackAttributes { ta.intAttributes["target_key"] = key return ta } // MaxLiveness sets the maximum liveness. // Detects the presence of an audience in the recording. Higher liveness // values represent an increased probability that the track was performed live. // A value above 0.8 provides strong likelihood that the track is live. func (ta *TrackAttributes) MaxLiveness(liveness float64) *TrackAttributes { ta.floatAttributes["max_liveness"] = liveness return ta } // MinLiveness sets the minimum liveness. // Detects the presence of an audience in the recording. Higher liveness // values represent an increased probability that the track was performed live. // A value above 0.8 provides strong likelihood that the track is live. func (ta *TrackAttributes) MinLiveness(liveness float64) *TrackAttributes { ta.floatAttributes["min_liveness"] = liveness return ta } // TargetLiveness sets the target liveness. // Detects the presence of an audience in the recording. Higher liveness // values represent an increased probability that the track was performed live. // A value above 0.8 provides strong likelihood that the track is live. func (ta *TrackAttributes) TargetLiveness(liveness float64) *TrackAttributes { ta.floatAttributes["target_liveness"] = liveness return ta } // MaxLoudness sets the maximum loudness in decibels (dB). // Loudness values are averaged across the entire track and are // useful for comparing the relative loudness of tracks. // Typical values range between -60 and 0 dB. func (ta *TrackAttributes) MaxLoudness(loudness float64) *TrackAttributes { ta.floatAttributes["max_loudness"] = loudness return ta } // MinLoudness sets the minimum loudness in decibels (dB). // Loudness values are averaged across the entire track and are // useful for comparing the relative loudness of tracks. // Typical values range between -60 and 0 dB. func (ta *TrackAttributes) MinLoudness(loudness float64) *TrackAttributes { ta.floatAttributes["min_loudness"] = loudness return ta } // TargetLoudness sets the target loudness in decibels (dB). // Loudness values are averaged across the entire track and are // useful for comparing the relative loudness of tracks. // Typical values range between -60 and 0 dB. func (ta *TrackAttributes) TargetLoudness(loudness float64) *TrackAttributes { ta.floatAttributes["target_loudness"] = loudness return ta } // MaxMode sets the maximum mode. // Mode indicates the modality (major or minor) of a track. func (ta *TrackAttributes) MaxMode(mode int) *TrackAttributes { ta.intAttributes["max_mode"] = mode return ta } // MinMode sets the minimum mode. // Mode indicates the modality (major or minor) of a track. func (ta *TrackAttributes) MinMode(mode int) *TrackAttributes { ta.intAttributes["min_mode"] = mode return ta } // TargetMode sets the target mode. // Mode indicates the modality (major or minor) of a track. func (ta *TrackAttributes) TargetMode(mode int) *TrackAttributes { ta.intAttributes["target_mode"] = mode return ta } // MaxPopularity sets the maximum popularity. // The value will be between 0 and 100, with 100 being the most popular. // The popularity is calculated by algorithm and is based, in the most part, // on the total number of plays the track has had and how recent those plays are. // Note: When applying track relinking via the market parameter, it is expected to find // relinked tracks with popularities that do not match min_*, max_* and target_* popularities. // These relinked tracks are accurate replacements for unplayable tracks // with the expected popularity scores. Original, non-relinked tracks are // available via the linked_from attribute of the relinked track response. func (ta *TrackAttributes) MaxPopularity(popularity int) *TrackAttributes { ta.intAttributes["max_popularity"] = popularity return ta } // MinPopularity sets the minimum popularity. // The value will be between 0 and 100, with 100 being the most popular. // The popularity is calculated by algorithm and is based, in the most part, // on the total number of plays the track has had and how recent those plays are. // Note: When applying track relinking via the market parameter, it is expected to find // relinked tracks with popularities that do not match min_*, max_* and target_* popularities. // These relinked tracks are accurate replacements for unplayable tracks // with the expected popularity scores. Original, non-relinked tracks are // available via the linked_from attribute of the relinked track response. func (ta *TrackAttributes) MinPopularity(popularity int) *TrackAttributes { ta.intAttributes["min_popularity"] = popularity return ta } // TargetPopularity sets the target popularity. // The value will be between 0 and 100, with 100 being the most popular. // The popularity is calculated by algorithm and is based, in the most part, // on the total number of plays the track has had and how recent those plays are. // Note: When applying track relinking via the market parameter, it is expected to find // relinked tracks with popularities that do not match min_*, max_* and target_* popularities. // These relinked tracks are accurate replacements for unplayable tracks // with the expected popularity scores. Original, non-relinked tracks are // available via the linked_from attribute of the relinked track response. func (ta *TrackAttributes) TargetPopularity(popularity int) *TrackAttributes { ta.intAttributes["target_popularity"] = popularity return ta } // MaxSpeechiness sets the maximum speechiness. // Speechiness detects the presence of spoken words in a track. // The more exclusively speech-like the recording, the closer to 1.0 // the speechiness will be. // Values above 0.66 describe tracks that are probably made entirely of // spoken words. Values between 0.33 and 0.66 describe tracks that may // contain both music and speech, including such cases as rap music. // Values below 0.33 most likely represent music and other non-speech-like tracks. func (ta *TrackAttributes) MaxSpeechiness(speechiness float64) *TrackAttributes { ta.floatAttributes["max_speechiness"] = speechiness return ta } // MinSpeechiness sets the minimum speechiness. // Speechiness detects the presence of spoken words in a track. // The more exclusively speech-like the recording, the closer to 1.0 // the speechiness will be. // Values above 0.66 describe tracks that are probably made entirely of // spoken words. Values between 0.33 and 0.66 describe tracks that may // contain both music and speech, including such cases as rap music. // Values below 0.33 most likely represent music and other non-speech-like tracks. func (ta *TrackAttributes) MinSpeechiness(speechiness float64) *TrackAttributes { ta.floatAttributes["min_speechiness"] = speechiness return ta } // TargetSpeechiness sets the target speechiness. // Speechiness detects the presence of spoken words in a track. // The more exclusively speech-like the recording, the closer to 1.0 // the speechiness will be. // Values above 0.66 describe tracks that are probably made entirely of // spoken words. Values between 0.33 and 0.66 describe tracks that may // contain both music and speech, including such cases as rap music. // Values below 0.33 most likely represent music and other non-speech-like tracks. func (ta *TrackAttributes) TargetSpeechiness(speechiness float64) *TrackAttributes { ta.floatAttributes["target_speechiness"] = speechiness return ta } // MaxTempo sets the maximum tempo in beats per minute (BPM). func (ta *TrackAttributes) MaxTempo(tempo float64) *TrackAttributes { ta.floatAttributes["max_tempo"] = tempo return ta } // MinTempo sets the minimum tempo in beats per minute (BPM). func (ta *TrackAttributes) MinTempo(tempo float64) *TrackAttributes { ta.floatAttributes["min_tempo"] = tempo return ta } // TargetTempo sets the target tempo in beats per minute (BPM). func (ta *TrackAttributes) TargetTempo(tempo float64) *TrackAttributes { ta.floatAttributes["target_tempo"] = tempo return ta } // MaxTimeSignature sets the maximum time signature. // The time signature (meter) is a notational convention to // specify how many beats are in each bar (or measure). func (ta *TrackAttributes) MaxTimeSignature(timeSignature int) *TrackAttributes { ta.intAttributes["max_time_signature"] = timeSignature return ta } // MinTimeSignature sets the minimum time signature. // The time signature (meter) is a notational convention to // specify how many beats are in each bar (or measure). func (ta *TrackAttributes) MinTimeSignature(timeSignature int) *TrackAttributes { ta.intAttributes["min_time_signature"] = timeSignature return ta } // TargetTimeSignature sets the target time signature. // The time signature (meter) is a notational convention to // specify how many beats are in each bar (or measure). func (ta *TrackAttributes) TargetTimeSignature(timeSignature int) *TrackAttributes { ta.intAttributes["target_time_signature"] = timeSignature return ta } // MaxValence sets the maximum valence. // Valence is a measure from 0.0 to 1.0 describing the musical positiveness // conveyed by a track. // Tracks with high valence sound more positive (e.g. happy, cheerful, euphoric), // while tracks with low valence sound more negative (e.g. sad, depressed, angry). func (ta *TrackAttributes) MaxValence(valence float64) *TrackAttributes { ta.floatAttributes["max_valence"] = valence return ta } // MinValence sets the minimum valence. // Valence is a measure from 0.0 to 1.0 describing the musical positiveness // / conveyed by a track. // Tracks with high valence sound more positive (e.g. happy, cheerful, euphoric), // while tracks with low valence sound more negative (e.g. sad, depressed, angry). func (ta *TrackAttributes) MinValence(valence float64) *TrackAttributes { ta.floatAttributes["min_valence"] = valence return ta } // TargetValence sets the target valence. // Valence is a measure from 0.0 to 1.0 describing the musical positiveness // / conveyed by a track. // Tracks with high valence sound more positive (e.g. happy, cheerful, euphoric), // while tracks with low valence sound more negative (e.g. sad, depressed, angry). func (ta *TrackAttributes) TargetValence(valence float64) *TrackAttributes { ta.floatAttributes["target_valence"] = valence return ta }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
track_test.go
Go
package spotify import ( "context" "net/http" "testing" ) func TestFindTrack(t *testing.T) { client, server := testClientFile(http.StatusOK, "test_data/find_track.txt") defer server.Close() track, err := client.GetTrack(context.Background(), "1zHlj4dQ8ZAtrayhuDDmkY") if err != nil { t.Error(err) return } if track.Name != "Timber" { t.Errorf("Wanted track Timer, got %s\n", track.Name) } } func TestFindTrackWithFloats(t *testing.T) { client, server := testClientFile(http.StatusOK, "test_data/find_track_with_floats.txt") defer server.Close() track, err := client.GetTrack(context.Background(), "1zHlj4dQ8ZAtrayhuDDmkY") if err != nil { t.Error(err) return } if track.Name != "Timber" { t.Errorf("Wanted track Timer, got %s\n", track.Name) } } func TestFindTracksSimple(t *testing.T) { client, server := testClientFile(http.StatusOK, "test_data/find_tracks_simple.txt") defer server.Close() tracks, err := client.GetTracks(context.Background(), []ID{"0eGsygTp906u18L0Oimnem", "1lDWb6b6ieDQ2xT7ewTC3G"}) if err != nil { t.Error(err) return } if l := len(tracks); l != 2 { t.Errorf("Wanted 2 tracks, got %d\n", l) return } } func TestFindTracksNotFound(t *testing.T) { client, server := testClientFile(http.StatusOK, "test_data/find_tracks_notfound.txt") defer server.Close() tracks, err := client.GetTracks(context.Background(), []ID{"0eGsygTp906u18L0Oimnem", "1lDWb6b6iecccdsdckTC3G"}) if err != nil { t.Error(err) return } if l := len(tracks); l != 2 { t.Errorf("Expected 2 results, got %d\n", l) return } if tracks[0].Name != "Mr. Brightside" { t.Errorf("Expected Mr. Brightside, got %s\n", tracks[0].Name) } if tracks[1] != nil { t.Error("Expected nil track (invalid ID) but got valid track") } }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
user.go
Go
package spotify import ( "context" "errors" "fmt" "net/http" "net/url" "strings" ) // User contains the basic, publicly available information about a Spotify user. type User struct { // The name displayed on the user's profile. // Note: Spotify currently fails to populate // this field when querying for a playlist. DisplayName string `json:"display_name"` // Known public external URLs for the user. ExternalURLs map[string]string `json:"external_urls"` // Information about followers of the user. Followers Followers `json:"followers"` // A link to the Web API endpoint for this user. Endpoint string `json:"href"` // The Spotify user ID for the user. ID string `json:"id"` // The user's profile image. Images []Image `json:"images"` // The Spotify URI for the user. URI URI `json:"uri"` } // PrivateUser contains additional information about a user. // This data is private and requires user authentication. type PrivateUser struct { User // The country of the user, as set in the user's account profile. // An [ISO 3166-1 alpha-2] country code. This field is only available when // the current user has granted access to the [ScopeUserReadPrivate] scope. // // [ISO 3166-1 alpha-2]: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 Country string `json:"country"` // The user's email address, as entered by the user when creating their account. // Note: this email is UNVERIFIED - there is no proof that it actually // belongs to the user. This field is only available when the current user // has granted access to the [ScopeUserReadEmail] scope. Email string `json:"email"` // The user's Spotify subscription level: "premium", "free", etc. // The subscription level "open" can be considered the same as "free". // This field is only available when the current user has granted access to // the [ScopeUserReadPrivate] scope. Product string `json:"product"` // The user's date of birth, in the format 'YYYY-MM-DD'. You can use // [DateLayout] to convert this to a [time.Time] value. This field is only // available when the current user has granted access to the // [ScopeUserReadBirthdate] scope. Birthdate string `json:"birthdate"` } // GetUsersPublicProfile gets [public profile] information about a // Spotify User. It does not require authentication. // // [public profile]: https://developer.spotify.com/documentation/web-api/reference/get-users-profile func (c *Client) GetUsersPublicProfile(ctx context.Context, userID ID) (*User, error) { spotifyURL := c.baseURL + "users/" + string(userID) var user User err := c.get(ctx, spotifyURL, &user) if err != nil { return nil, err } return &user, nil } // CurrentUser gets detailed profile information about the // [current user]. // // Reading the user's email address requires that the application // has the [ScopeUserReadEmail] scope. Reading the country, display // name, profile images, and product subscription level requires // that the application has the [ScopeUserReadPrivate] scope. // // Warning: The email address in the response will be the address // that was entered when the user created their spotify account. // This email address is unverified - do not assume that Spotify has // checked that the email address actually belongs to the user. // // [current user]: https://developer.spotify.com/documentation/web-api/reference/get-current-users-profile func (c *Client) CurrentUser(ctx context.Context) (*PrivateUser, error) { var result PrivateUser err := c.get(ctx, c.baseURL+"me", &result) if err != nil { return nil, err } return &result, nil } // CurrentUsersShows gets a [list of shows] saved in the current // Spotify user's "Your Music" library. // // Supported options: [Limit], [Offset]. // // [list of shows]: https://developer.spotify.com/documentation/web-api/reference/get-users-saved-shows func (c *Client) CurrentUsersShows(ctx context.Context, opts ...RequestOption) (*SavedShowPage, error) { spotifyURL := c.baseURL + "me/shows" if params := processOptions(opts...).urlParams.Encode(); params != "" { spotifyURL += "?" + params } var result SavedShowPage err := c.get(ctx, spotifyURL, &result) if err != nil { return nil, err } return &result, nil } // CurrentUsersTracks gets a [list of songs] saved in the current // Spotify user's "Your Music" library. // // Supported options: [Limit], [Country], [Offset]. // // [list of songs]: https://developer.spotify.com/documentation/web-api/reference/get-users-saved-tracks func (c *Client) CurrentUsersTracks(ctx context.Context, opts ...RequestOption) (*SavedTrackPage, error) { spotifyURL := c.baseURL + "me/tracks" if params := processOptions(opts...).urlParams.Encode(); params != "" { spotifyURL += "?" + params } var result SavedTrackPage err := c.get(ctx, spotifyURL, &result) if err != nil { return nil, err } return &result, nil } // FollowUser [adds the current user as a follower] of one or more // spotify users, identified by their [Spotify ID]s. // // Modifying the lists of artists or users the current user follows // requires that the application has the [ScopeUserFollowModify] scope. // // [adds the current user as a follower]: https://developer.spotify.com/documentation/web-api/reference/follow-artists-users // [Spotify ID]: https://developer.spotify.com/documentation/web-api/#spotify-uris-and-ids func (c *Client) FollowUser(ctx context.Context, ids ...ID) error { return c.modifyFollowers(ctx, "user", true, ids...) } // FollowArtist [adds the current user as a follower] of one or more // spotify artists, identified by their [Spotify ID]s. // // Modifying the lists of artists or users the current user follows // requires that the application has the [ScopeUserFollowModify] scope. // // [adds the current user as a follower]: https://developer.spotify.com/documentation/web-api/reference/follow-artists-users // [Spotify ID]: https://developer.spotify.com/documentation/web-api/#spotify-uris-and-ids func (c *Client) FollowArtist(ctx context.Context, ids ...ID) error { return c.modifyFollowers(ctx, "artist", true, ids...) } // UnfollowUser [removes the current user as a follower] of one or more // Spotify users. // // Modifying the lists of artists or users the current user follows // requires that the application has the [ScopeUserFollowModify] scope. // // [removes the current user as a follower]: https://developer.spotify.com/documentation/web-api/reference/unfollow-artists-users func (c *Client) UnfollowUser(ctx context.Context, ids ...ID) error { return c.modifyFollowers(ctx, "user", false, ids...) } // UnfollowArtist [removes the current user as a follower] of one or more // Spotify artists. // // Modifying the lists of artists or users the current user follows // requires that the application has the [ScopeUserFollowModify] scope. // // [removes the current user as a follower]: https://developer.spotify.com/documentation/web-api/reference/unfollow-artists-users func (c *Client) UnfollowArtist(ctx context.Context, ids ...ID) error { return c.modifyFollowers(ctx, "artist", false, ids...) } // CurrentUserFollows [checks to see if the current user is following] // one or more artists or other Spotify Users. This call requires // [ScopeUserFollowRead]. // // The t argument indicates the type of the IDs, and must be either // "user" or "artist". // // The result is returned as a slice of bool values in the same order // in which the IDs were specified. // // [checks to see if the current user is following]: https://developer.spotify.com/documentation/web-api/reference/check-current-user-follows func (c *Client) CurrentUserFollows(ctx context.Context, t string, ids ...ID) ([]bool, error) { if l := len(ids); l == 0 || l > 50 { return nil, errors.New("spotify: UserFollows supports 1 to 50 IDs") } if t != "artist" && t != "user" { return nil, errors.New("spotify: t must be 'artist' or 'user'") } spotifyURL := fmt.Sprintf("%sme/following/contains?type=%s&ids=%s", c.baseURL, t, strings.Join(toStringSlice(ids), ",")) var result []bool err := c.get(ctx, spotifyURL, &result) if err != nil { return nil, err } return result, nil } func (c *Client) modifyFollowers(ctx context.Context, usertype string, follow bool, ids ...ID) error { if l := len(ids); l == 0 || l > 50 { return errors.New("spotify: Follow/Unfollow supports 1 to 50 IDs") } v := url.Values{} v.Add("type", usertype) v.Add("ids", strings.Join(toStringSlice(ids), ",")) spotifyURL := c.baseURL + "me/following?" + v.Encode() method := "PUT" if !follow { method = "DELETE" } req, err := http.NewRequestWithContext(ctx, method, spotifyURL, nil) if err != nil { return err } return c.execute(req, nil, http.StatusNoContent) } // CurrentUsersFollowedArtists gets the [current user's followed artists]. // This call requires that the user has granted the [ScopeUserFollowRead] scope. // // Supported options: [Limit], [After]. // // [current user's followed artists]: https://developer.spotify.com/documentation/web-api/reference/get-followed func (c *Client) CurrentUsersFollowedArtists(ctx context.Context, opts ...RequestOption) (*FullArtistCursorPage, error) { spotifyURL := c.baseURL + "me/following" v := processOptions(opts...).urlParams v.Set("type", "artist") if params := v.Encode(); params != "" { spotifyURL += "?" + params } var result struct { A FullArtistCursorPage `json:"artists"` } err := c.get(ctx, spotifyURL, &result) if err != nil { return nil, err } return &result.A, nil } // CurrentUsersAlbums gets a [list of albums] saved in the current // Spotify user's "Your Music" library. // // Supported options: [Market], [Limit], [Offset]. // // [list of albums]: https://developer.spotify.com/documentation/web-api/reference/get-users-saved-albums func (c *Client) CurrentUsersAlbums(ctx context.Context, opts ...RequestOption) (*SavedAlbumPage, error) { spotifyURL := c.baseURL + "me/albums" if params := processOptions(opts...).urlParams.Encode(); params != "" { spotifyURL += "?" + params } var result SavedAlbumPage err := c.get(ctx, spotifyURL, &result) if err != nil { return nil, err } return &result, nil } // CurrentUsersPlaylists gets a [list of the playlists] owned or followed by // the current spotify user. // // Private playlists require the [ScopePlaylistReadPrivate] scope. Note that // this scope alone will not return collaborative playlists, even though // they are always private. In order to retrieve collaborative playlists // the user must authorize the [ScopePlaylistReadCollaborative] scope. // // Supported options: [Limit], [Offset]. // // [list of the playlists]: https://developer.spotify.com/documentation/web-api/reference/get-a-list-of-current-users-playlists func (c *Client) CurrentUsersPlaylists(ctx context.Context, opts ...RequestOption) (*SimplePlaylistPage, error) { spotifyURL := c.baseURL + "me/playlists" if params := processOptions(opts...).urlParams.Encode(); params != "" { spotifyURL += "?" + params } var result SimplePlaylistPage err := c.get(ctx, spotifyURL, &result) if err != nil { return nil, err } return &result, nil } // CurrentUsersTopArtists fetches a list of the [user's top artists] over the specified [Timerange]. // The default is [MediumTermRange]. // // Supported options: [Limit], [Timerange] // // [user's top artists]: https://developer.spotify.com/documentation/web-api/reference/get-users-top-artists-and-tracks func (c *Client) CurrentUsersTopArtists(ctx context.Context, opts ...RequestOption) (*FullArtistPage, error) { spotifyURL := c.baseURL + "me/top/artists" if params := processOptions(opts...).urlParams.Encode(); params != "" { spotifyURL += "?" + params } var result FullArtistPage err := c.get(ctx, spotifyURL, &result) if err != nil { return nil, err } return &result, nil } // CurrentUsersTopTracks fetches the [user's top tracks] over the specified // [Timerange]. The default limit is 20 and the default timerange is // [MediumTermRange]. This call requires [ScopeUserTopRead]. // // Supported options: [Limit], [Timerange], [Offset]. // // [user's top tracks]: https://developer.spotify.com/documentation/web-api/reference/get-users-top-artists-and-tracks func (c *Client) CurrentUsersTopTracks(ctx context.Context, opts ...RequestOption) (*FullTrackPage, error) { spotifyURL := c.baseURL + "me/top/tracks" if params := processOptions(opts...).urlParams.Encode(); params != "" { spotifyURL += "?" + params } var result FullTrackPage err := c.get(ctx, spotifyURL, &result) if err != nil { return nil, err } return &result, nil }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
user_test.go
Go
package spotify import ( "context" "fmt" "io" "net/http" "net/http/httptest" "strings" "testing" ) const userResponse = ` { "display_name" : "Ronald Pompa", "external_urls" : { "spotify" : "https://open.spotify.com/user/wizzler" }, "followers" : { "href" : null, "total" : 3829 }, "href" : "https://api.spotify.com/v1/users/wizzler", "id" : "wizzler", "images" : [ { "height" : null, "url" : "http://profile-images.scdn.co/images/userprofile/default/9d51820e73667ea5f1e97ea601cf0593b558050e", "width" : null } ], "type" : "user", "uri" : "spotify:user:wizzler" }` func TestUserProfile(t *testing.T) { client, server := testClientString(http.StatusOK, userResponse) defer server.Close() user, err := client.GetUsersPublicProfile(context.Background(), "wizzler") if err != nil { t.Error(err) return } if user.ID != "wizzler" { t.Error("Expected user wizzler, got ", user.ID) } if f := user.Followers.Count; f != 3829 { t.Errorf("Expected 3829 followers, got %d\n", f) } } func TestCurrentUser(t *testing.T) { json := `{ "country" : "US", "display_name" : null, "email" : "username@domain.com", "external_urls" : { "spotify" : "https://open.spotify.com/user/username" }, "followers" : { "href" : null, "total" : 0 }, "href" : "https://api.spotify.com/v1/users/userame", "id" : "username", "images" : [ ], "product" : "premium", "type" : "user", "uri" : "spotify:user:username", "birthdate" : "1985-05-01" }` client, server := testClientString(http.StatusOK, json) defer server.Close() me, err := client.CurrentUser(context.Background()) if err != nil { t.Error(err) return } if me.Country != CountryUSA || me.Email != "username@domain.com" || me.Product != "premium" { t.Error("Received incorrect response") } if me.Birthdate != "1985-05-01" { t.Errorf("Expected '1985-05-01', got '%s'\n", me.Birthdate) } } func TestFollowUsersMissingScope(t *testing.T) { json := `{ "error": { "status": 403, "message": "Insufficient client scope" } }` client, server := testClientString(http.StatusForbidden, json, func(req *http.Request) { if req.URL.Query().Get("type") != "user" { t.Error("Request made with the wrong type parameter") } }) defer server.Close() err := client.FollowUser(context.Background(), ID("exampleuser01")) serr, ok := err.(Error) if !ok { t.Fatal("Expected insufficient client scope error") } if serr.Status != http.StatusForbidden { t.Error("Expected HTTP 403") } } func TestFollowArtist(t *testing.T) { client, server := testClientString(http.StatusNoContent, "", func(req *http.Request) { if req.URL.Query().Get("type") != "artist" { t.Error("Request made with the wrong type parameter") } }) defer server.Close() if err := client.FollowArtist(context.Background(), "3ge4xOaKvWfhRwgx0Rldov"); err != nil { t.Error(err) } } func TestFollowArtistAutoRetry(t *testing.T) { t.Parallel() handlers := []http.HandlerFunc{ // first attempt fails http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Retry-After", "2") w.WriteHeader(http.StatusTooManyRequests) _, _ = io.WriteString(w, `{ "error": { "message": "slow down", "status": 429 } }`) }), // next attempt succeeds http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) }), } i := 0 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { handlers[i](w, r) i++ })) defer server.Close() client := &Client{http: http.DefaultClient, baseURL: server.URL + "/", autoRetry: true} if err := client.FollowArtist(context.Background(), "3ge4xOaKvWfhRwgx0Rldov"); err != nil { t.Error(err) } } func TestFollowUsersInvalidToken(t *testing.T) { json := `{ "error": { "status": 401, "message": "Invalid access token" } }` client, server := testClientString(http.StatusUnauthorized, json, func(req *http.Request) { if req.URL.Query().Get("type") != "user" { t.Error("Request made with the wrong type parameter") } }) defer server.Close() err := client.FollowUser(context.Background(), ID("dummyID")) serr, ok := err.(Error) if !ok { t.Fatal("Expected invalid token error") } if serr.Status != http.StatusUnauthorized { t.Error("Expected HTTP 401") } } func TestUserFollows(t *testing.T) { json := "[ false, true ]" client, server := testClientString(http.StatusOK, json) defer server.Close() follows, err := client.CurrentUserFollows(context.Background(), "artist", ID("74ASZWbe4lXaubB36ztrGX"), ID("08td7MxkoHQkXnWAYD8d6Q")) if err != nil { t.Error(err) return } if len(follows) != 2 || follows[0] || !follows[1] { t.Error("Incorrect result", follows) } } func TestCurrentUsersTracks(t *testing.T) { client, server := testClientFile(http.StatusOK, "test_data/current_users_tracks.txt") defer server.Close() tracks, err := client.CurrentUsersTracks(context.Background()) if err != nil { t.Error(err) return } if tracks.Limit != 20 { t.Errorf("Expected limit 20, got %d\n", tracks.Limit) } if tracks.Endpoint != "https://api.spotify.com/v1/me/tracks?offset=0&limit=20" { t.Error("Endpoint incorrect") } if tracks.Total != 3 { t.Errorf("Expect 3 results, got %d\n", tracks.Total) return } if len(tracks.Tracks) != int(tracks.Total) { t.Error("Didn't get expected number of results") return } expected := "You & I (Nobody In The World)" if tracks.Tracks[0].Name != expected { t.Errorf("Expected '%s', got '%s'\n", expected, tracks.Tracks[0].Name) fmt.Printf("\n%#v\n", tracks.Tracks[0]) } } func TestCurrentUsersAlbums(t *testing.T) { client, server := testClientFile(http.StatusOK, "test_data/current_users_albums.txt") defer server.Close() albums, err := client.CurrentUsersAlbums(context.Background()) if err != nil { t.Error(err) return } if albums.Limit != 20 { t.Errorf("Expected limit 20, got %d\n", albums.Limit) } if albums.Endpoint != "https://api.spotify.com/v1/me/albums?offset=0&limit=20" { t.Error("Endpoint incorrect") } if albums.Total != 2 { t.Errorf("Expect 2 results, got %d\n", albums.Total) return } if len(albums.Albums) != int(albums.Total) { t.Error("Didn't get expected number of results") return } expected := "Love In The Future" if albums.Albums[0].Name != expected { t.Errorf("Expected '%s', got '%s'\n", expected, albums.Albums[0].Name) fmt.Printf("\n%#v\n", albums.Albums[0]) } upc := "886444160742" u, ok := albums.Albums[0].ExternalIDs["upc"] if !ok { t.Error("External IDs missing UPC") } if u != upc { t.Errorf("Wrong UPC: want %s, got %s\n", upc, u) } } func TestCurrentUsersPlaylists(t *testing.T) { client, server := testClientFile(http.StatusOK, "test_data/current_users_playlists.txt") defer server.Close() playlists, err := client.CurrentUsersPlaylists(context.Background()) if err != nil { t.Error(err) } if playlists.Limit != 5 { t.Errorf("Expected limit 5, got %d\n", playlists.Limit) } if playlists.Offset != 20 { t.Errorf("Expected offset 20, got %d\n", playlists.Offset) } if playlists.Total != 42 { t.Errorf("Expected 42 playlists, got %d\n", playlists.Total) } tests := []struct { Name string Description string Public bool TrackCount int }{ {"Core", "", true, 3}, {"Black/Atmo/Prog ?", "This is kinda fuzzy", true, 10}, {"Troll", "", false, 7}, {"Melomiel", "", true, 3}, {"HEAVY MIEL", "Deathcore,techdeath, tout ce qui tape plus fort que du melodeath", true, 10}, } for i := range tests { p := playlists.Playlists[i] if p.Name != tests[i].Name { t.Errorf("Expected '%s', got '%s'\n", tests[i].Name, p.Name) } if p.Description != tests[i].Description { t.Errorf("Expected '%s', got '%s'\n", tests[i].Description, p.Description) } if p.IsPublic != tests[i].Public { t.Errorf("Expected public to be %#v, got %#v\n", tests[i].Public, p.IsPublic) } if int(p.Tracks.Total) != tests[i].TrackCount { t.Errorf("Expected %d tracks, got %d\n", tests[i].TrackCount, p.Tracks.Total) } } } func TestUsersFollowedArtists(t *testing.T) { json := ` { "artists" : { "items" : [ { "external_urls" : { "spotify" : "https://open.spotify.com/artist/0I2XqVXqHScXjHhk6AYYRe" }, "followers" : { "href" : null, "total" : 7753 }, "genres" : [ "swedish hip hop" ], "href" : "https://api.spotify.com/v1/artists/0I2XqVXqHScXjHhk6AYYRe", "id" : "0I2XqVXqHScXjHhk6AYYRe", "images" : [ { "height" : 640, "url" : "https://i.scdn.co/image/2c8c0cea05bf3d3c070b7498d8d0b957c4cdec20", "width" : 640 }, { "height" : 300, "url" : "https://i.scdn.co/image/394302b42c4b894786943e028cdd46d7baaa29b7", "width" : 300 }, { "height" : 64, "url" : "https://i.scdn.co/image/ca9df7225ade6e5dfc62e7076709ca3409a7cbbf", "width" : 64 } ], "name" : "Afasi & Filthy", "popularity" : 54, "type" : "artist", "uri" : "spotify:artist:0I2XqVXqHScXjHhk6AYYRe" } ], "next" : "https://api.spotify.com/v1/users/thelinmichael/following?type=artist&after=0aV6DOiouImYTqrR5YlIqx&limit=20", "total" : 183, "cursors" : { "after" : "0aV6DOiouImYTqrR5YlIqx" }, "limit" : 20, "href" : "https://api.spotify.com/v1/users/thelinmichael/following?type=artist&limit=20" } }` client, server := testClientString(http.StatusOK, json) defer server.Close() artists, err := client.CurrentUsersFollowedArtists(context.Background()) if err != nil { t.Fatal(err) } exp := 20 if int(artists.Limit) != exp { t.Errorf("Expected limit %d, got %d\n", exp, artists.Limit) } if a := artists.Cursor.After; a != "0aV6DOiouImYTqrR5YlIqx" { t.Error("Invalid 'after' cursor") } if l := len(artists.Artists); l != 1 { t.Fatalf("Expected 1 artist, got %d\n", l) } if n := artists.Artists[0].Name; n != "Afasi & Filthy" { t.Error("Got wrong artist name") } } func TestCurrentUsersFollowedArtistsOpt(t *testing.T) { client, server := testClientString(http.StatusOK, "{}", func(req *http.Request) { if url := req.URL.String(); !strings.HasSuffix(url, "me/following?after=0aV6DOiouImYTqrR5YlIqx&limit=50&type=artist") { t.Error("invalid request url") } }) defer server.Close() _, err := client.CurrentUsersFollowedArtists(context.Background(), Limit(50), After("0aV6DOiouImYTqrR5YlIqx")) if err != nil { t.Errorf("Expected no error, got %v", err) } } func TestCurrentUsersTopArtists(t *testing.T) { client, server := testClientFile(http.StatusOK, "test_data/current_users_top_artists.txt") defer server.Close() artists, err := client.CurrentUsersTopArtists(context.Background()) if err != nil { t.Error(err) } if artists.Endpoint != "https://api.spotify.com/v1/me/top/artists" { t.Error("Endpoint incorrect") } if artists.Limit != 20 { t.Errorf("Expected limit 20, got %d\n", artists.Limit) } if artists.Total != 10 { t.Errorf("Expected total 10, got %d\n", artists.Total) return } if len(artists.Artists) != int(artists.Total) { t.Error("Didn't get expected number of results") return } if artists.Artists[0].Followers.Count != 8437 { t.Errorf("Expected follower count of 8437, got %d\n", artists.Artists[0].Followers.Count) } name := "insaneintherainmusic" if artists.Artists[0].Name != name { t.Errorf("Expected '%s', got '%s'\n", name, artists.Artists[0].Name) fmt.Printf("\n%#v\n", artists.Artists[0]) } } func TestCurrentUsersTopTracks(t *testing.T) { client, server := testClientFile(http.StatusOK, "test_data/current_users_top_tracks.txt") defer server.Close() tracks, err := client.CurrentUsersTopTracks(context.Background()) if err != nil { t.Error(err) } if tracks.Endpoint != "https://api.spotify.com/v1/me/top/tracks" { t.Error("Endpoint incorrect") } if tracks.Limit != 20 { t.Errorf("Expected limit 20, got %d\n", tracks.Limit) } if tracks.Total != 380 { t.Errorf("Expected total 380, got %d\n", tracks.Total) return } if len(tracks.Tracks) != int(tracks.Limit) { t.Errorf("Didn't get expected number of results") return } name := "Adventure Awaits! (Alola Region Theme)" if tracks.Tracks[0].Name != name { t.Errorf("Expected '%s', got '%s'\n", name, tracks.Tracks[0].Name) fmt.Printf("\n%#v\n", tracks.Tracks[0]) } isrc := "QZ4JJ1764466" i := tracks.Tracks[0].ExternalIDs.ISRC if i != isrc { t.Errorf("Wrong ISRC: want %s, got %s\n", isrc, i) } }
zmb3/spotify
1,553
A Go wrapper for the Spotify Web API
Go
zmb3
Zac Bergquist
gravitational
app/build.gradle
Gradle
apply plugin: 'com.android.application' android { compileSdkVersion 21 buildToolsVersion "20.0.0" defaultConfig { applicationId "com.zmb.sunshine" minSdkVersion 21 targetSdkVersion 21 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) }
zmb3/sunshine
1
Sample weather app for Android
Java
zmb3
Zac Bergquist
gravitational
app/src/androidTest/java/com/zmb/sunshine/ApplicationTest.java
Java
package com.zmb.sunshine; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
zmb3/sunshine
1
Sample weather app for Android
Java
zmb3
Zac Bergquist
gravitational
app/src/androidTest/java/com/zmb/sunshine/data/db/test/DbTest.java
Java
package com.zmb.sunshine.data.db.test; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.test.AndroidTestCase; import com.zmb.sunshine.data.db.WeatherContract.LocationEntry; import com.zmb.sunshine.data.db.WeatherContract.WeatherEntry; import com.zmb.sunshine.data.db.WeatherDbHelper; import java.util.Map; /** * Unit tests for the weather database. */ public class DbTest extends AndroidTestCase { static final String TEST_CITY = "North Pole"; static final String TEST_LOCATION = "99705"; static final String TEST_DATE = "20141205"; public void testCreate() throws Throwable { mContext.deleteDatabase(WeatherDbHelper.DATABASE_NAME); SQLiteDatabase db = new WeatherDbHelper(mContext).getWritableDatabase(); assertEquals(true, db.isOpen()); db.close(); } public void testInsertRead() { WeatherDbHelper helper = new WeatherDbHelper(mContext); SQLiteDatabase db = helper.getWritableDatabase(); ContentValues locationValues = createLocationValues(); long locationRowId = db.insert(LocationEntry.TABLE_NAME, null, locationValues); assertTrue(locationRowId != -1); validateCursor(db.query(LocationEntry.TABLE_NAME, null, null, null, null, null, null), locationValues); ContentValues weatherValues = createWeatherValues(locationRowId); long weatherRowId = db.insert(WeatherEntry.TABLE_NAME, null, weatherValues); assertTrue(weatherRowId != -1); validateCursor(db.query(WeatherEntry.TABLE_NAME, null, null, null, null, null, null), weatherValues); helper.close(); } static void validateCursor(Cursor cursor, ContentValues values) { assertTrue(cursor.moveToFirst()); for (Map.Entry<String, Object> entry : values.valueSet()) { String column = entry.getKey(); int idx = cursor.getColumnIndex(column); assertTrue(idx != -1); String expected = entry.getValue().toString(); assertEquals("Expected " + expected + ", got " + cursor.getString(idx), expected, cursor.getString(idx)); } cursor.close(); } static ContentValues createLocationValues() { ContentValues values = new ContentValues(); values.put(LocationEntry.COLUMN_CITY_NAME, TEST_CITY); values.put(LocationEntry.COLUMN_LOCATION_SETTING, TEST_LOCATION); values.put(LocationEntry.COLUMN_LATITUDE, 64.7488); values.put(LocationEntry.COLUMN_LONGITUDE, -147.353); return values; } static ContentValues createWeatherValues(long rowId) { ContentValues weatherValues = new ContentValues(); weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, rowId); weatherValues.put(WeatherEntry.COLUMN_DATETEXT, TEST_DATE); weatherValues.put(WeatherEntry.COLUMN_DEGREES, 1.1); weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, 1.2); weatherValues.put(WeatherEntry.COLUMN_PRESSURE, 1.3); weatherValues.put(WeatherEntry.COLUMN_TEMPERATURE_HIGH, 75); weatherValues.put(WeatherEntry.COLUMN_TEMPERATURE_LOW, 65); weatherValues.put(WeatherEntry.COLUMN_SHORT_DESCRIPTION, "Asteroids"); weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, 5.5); weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, 321); return weatherValues; } }
zmb3/sunshine
1
Sample weather app for Android
Java
zmb3
Zac Bergquist
gravitational
app/src/androidTest/java/com/zmb/sunshine/data/db/test/ProviderTest.java
Java
package com.zmb.sunshine.data.db.test; import android.content.ContentUris; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.test.AndroidTestCase; import com.zmb.sunshine.data.db.WeatherContract.LocationEntry; import com.zmb.sunshine.data.db.WeatherContract.WeatherEntry; import java.util.Map; /** * Unit tests for the weather content provider. */ public class ProviderTest extends AndroidTestCase { @Override protected void setUp() throws Exception { super.setUp(); testDeleteAllRecords(); } public void testDeleteAllRecords() { // passing a null query deletes all records mContext.getContentResolver().delete(WeatherEntry.CONTENT_URI, null, null); mContext.getContentResolver().delete(LocationEntry.CONTENT_URI, null, null); Cursor c = mContext.getContentResolver().query(WeatherEntry.CONTENT_URI, null, null, null, null); assertEquals(c.getCount(), 0); c.close(); c = mContext.getContentResolver().query(LocationEntry.CONTENT_URI, null, null, null, null); assertEquals(c.getCount(), 0); c.close(); } public void testGetType() { // content://com.zmb.sunshine/weather/ String type = mContext.getContentResolver().getType(WeatherEntry.CONTENT_URI); // vnd.android.cursor.dir/com.zmb.sunshine/weather assertEquals(WeatherEntry.CONTENT_TYPE, type); // content://com.zmb.sunshine/weather/94074 type = mContext.getContentResolver().getType( WeatherEntry.buildWeatherLocation(DbTest.TEST_LOCATION)); // vnd.android.cursor.dir/com.zmb.sunshine/weather assertEquals(WeatherEntry.CONTENT_TYPE, type); // content://com.zmb.sunshine/weather/94074/20140612 type = mContext.getContentResolver().getType( WeatherEntry.buildWeatherLocationWithDate(DbTest.TEST_LOCATION, DbTest.TEST_DATE)); // vnd.android.cursor.item/com.zmb.sunshine/weather assertEquals(WeatherEntry.CONTENT_ITEM_TYPE, type); // content://com.zmb.sunshine/location/ type = mContext.getContentResolver().getType(LocationEntry.CONTENT_URI); // vnd.android.cursor.dir/com.zmb.sunshine/location assertEquals(LocationEntry.CONTENT_TYPE, type); // content://com.zmb.sunshine/location/1 type = mContext.getContentResolver().getType(LocationEntry.buildLocationUri(1L)); // vnd.android.cursor.item/com.zmb.sunshine/location assertEquals(LocationEntry.CONTENT_ITEM_TYPE, type); } public void testInsertReadProvider() { ContentValues locationValues = DbTest.createLocationValues(); // instead of inserting directly into the database, use the provider instead Uri insert = mContext.getContentResolver().insert(LocationEntry.CONTENT_URI, locationValues); long locationRowId = ContentUris.parseId(insert); assertNotNull(insert); // this looks just like the test in TestDb but instead of querying the database // directly we use a content resolver to query the content provider validateCursor(mContext.getContentResolver().query( LocationEntry.CONTENT_URI, null, null, null, null), locationValues); // now try to query for a particular row validateCursor((mContext.getContentResolver().query( LocationEntry.buildLocationUri(locationRowId), null, null, null, null)), locationValues); ContentValues weatherValues = DbTest.createWeatherValues(locationRowId); insert = mContext.getContentResolver().insert(WeatherEntry.CONTENT_URI, weatherValues); assertNotNull(insert); validateCursor(mContext.getContentResolver().query( WeatherEntry.CONTENT_URI, null, null, null, null), weatherValues); // test the JOIN addAllContentValues(weatherValues, locationValues); validateCursor(mContext.getContentResolver().query( WeatherEntry.buildWeatherLocation(DbTest.TEST_LOCATION), null, null, null, null), weatherValues); validateCursor(mContext.getContentResolver().query( WeatherEntry.buildWeatherLocationWithStartDate(DbTest.TEST_LOCATION, DbTest.TEST_DATE), null, null, null, null), weatherValues); validateCursor(mContext.getContentResolver().query( WeatherEntry.buildWeatherLocationWithDate(DbTest.TEST_LOCATION, DbTest.TEST_DATE), null, null, null, null), weatherValues); } public void testUpdateLocation() { ContentValues values = DbTest.createLocationValues(); Uri uri = mContext.getContentResolver().insert(LocationEntry.CONTENT_URI, values); long rowId = ContentUris.parseId(uri); assertTrue(rowId != -1); ContentValues newValues = new ContentValues(values); newValues.put(LocationEntry._ID, rowId); newValues.put(LocationEntry.COLUMN_CITY_NAME, "Santa's Village"); int count = mContext.getContentResolver().update(LocationEntry.CONTENT_URI, newValues, LocationEntry._ID + "= ?", new String[] { Long.toString(rowId) }); assertEquals(count, 1); validateCursor(mContext.getContentResolver().query(LocationEntry.buildLocationUri(rowId), null, null, null, null), newValues); } static void validateCursor(Cursor cursor, ContentValues values) { assertTrue(cursor.moveToFirst()); for (Map.Entry<String, Object> entry : values.valueSet()) { String column = entry.getKey(); int idx = cursor.getColumnIndex(column); assertTrue(idx != -1); String expected = entry.getValue().toString(); assertEquals("Expected " + expected + ", got " + cursor.getString(idx), expected, cursor.getString(idx)); } cursor.close(); } static void addAllContentValues(ContentValues destination, ContentValues source) { for (String key : source.keySet()) { destination.put(key, source.getAsString(key)); } } }
zmb3/sunshine
1
Sample weather app for Android
Java
zmb3
Zac Bergquist
gravitational
app/src/main/java/com/zmb/sunshine/DetailActivity.java
Java
package com.zmb.sunshine; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; /** * An activity for displaying a detailed forecast for a particular day. * This activity is only used in the phone (single pane) UI. * In the tablet UI, the forecast list and details vew are shown * in the same activity. */ public class DetailActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); if (savedInstanceState == null) { String date = getIntent().getStringExtra(DetailFragment.DATE_KEY); Bundle dateInfo = new Bundle(); dateInfo.putString(DetailFragment.DATE_KEY, date); DetailFragment details = new DetailFragment(); details.setArguments(dateInfo); getFragmentManager().beginTransaction() .add(R.id.weather_detail_container, details) .commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.detail, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { Intent i = new Intent(this, SettingsActivity.class); startActivity(i); return true; } return super.onOptionsItemSelected(item); } }
zmb3/sunshine
1
Sample weather app for Android
Java
zmb3
Zac Bergquist
gravitational
app/src/main/java/com/zmb/sunshine/DetailFragment.java
Java
package com.zmb.sunshine; import android.app.Fragment; import android.app.LoaderManager; import android.content.CursorLoader; import android.content.Loader; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.zmb.sunshine.data.db.WeatherContract; public class DetailFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> { public static final String LOCATION_KEY = "LOCATION_KEY"; public static final String DATE_KEY = "DATE_KEY"; private static final String[] FORECAST_COLUMNS = { WeatherContract.WeatherEntry.TABLE_NAME + "." + WeatherContract.WeatherEntry._ID, WeatherContract.WeatherEntry.COLUMN_DATETEXT, WeatherContract.WeatherEntry.COLUMN_SHORT_DESCRIPTION, WeatherContract.WeatherEntry.COLUMN_TEMPERATURE_HIGH, WeatherContract.WeatherEntry.COLUMN_TEMPERATURE_LOW, WeatherContract.WeatherEntry.COLUMN_HUMIDITY, WeatherContract.WeatherEntry.COLUMN_PRESSURE, WeatherContract.WeatherEntry.COLUMN_WIND_SPEED, WeatherContract.WeatherEntry.COLUMN_DEGREES, WeatherContract.WeatherEntry.COLUMN_WEATHER_ID, WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING }; private String mLocationSetting; private ImageView mIconView; private TextView mDateTextView; private TextView mDayTextView; private TextView mForecastTextView; private TextView mHighTextView; private TextView mLowTextView; private TextView mHumidityTextView; private TextView mWindTextView; private TextView mPressureTextView; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // grab location if it was previously saved if (savedInstanceState != null) { mLocationSetting = savedInstanceState.getString(LOCATION_KEY); } Bundle args = getArguments(); if (args != null && args.containsKey(DATE_KEY)) { getLoaderManager().initLoader(0, null, this); } } @Override public void onResume() { super.onResume(); // if the location has changed, then we have to reset the loader to listen for changes on a new URI Bundle args = getArguments(); if (args != null && args.containsKey(DATE_KEY) && mLocationSetting != null && !mLocationSetting.equals(Sunshine.getPreferredLocation(getActivity()))) { getLoaderManager().restartLoader(0, null, this); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_detail, container, false); mIconView = (ImageView) view.findViewById(R.id.detail_icon); mForecastTextView = (TextView) view.findViewById(R.id.detail_forecast_textview); mHighTextView = (TextView) view.findViewById(R.id.detail_high_textview); mLowTextView = (TextView) view.findViewById(R.id.detail_low_textview); mDateTextView = (TextView) view.findViewById(R.id.detail_date_textview); mDayTextView = (TextView) view.findViewById(R.id.detail_day_textview); mHumidityTextView = (TextView) view.findViewById(R.id.detail_humitidy_textview); mWindTextView = (TextView) view.findViewById(R.id.detail_wind_textview); mPressureTextView = (TextView) view.findViewById(R.id.detail_pressure_textview); return view; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // save location so we don't lose it when screen is rotated outState.putString(LOCATION_KEY, mLocationSetting); } @Override public Loader<Cursor> onCreateLoader(int i, Bundle bundle) { mLocationSetting = Sunshine.getPreferredLocation(getActivity()); // get the date that was provided in this fragments arguments String date = getArguments().getString(DATE_KEY); Uri weatherUri = WeatherContract.WeatherEntry.buildWeatherLocationWithDate(mLocationSetting, date); String sortOrder = WeatherContract.WeatherEntry.COLUMN_DATETEXT + " ASC"; return new CursorLoader(getActivity(), weatherUri, FORECAST_COLUMNS, null, null, sortOrder); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (data.moveToFirst()) { int weatherId = data.getInt(data.getColumnIndex(WeatherContract.WeatherEntry.COLUMN_WEATHER_ID)); String desc = data.getString(data.getColumnIndex(WeatherContract.WeatherEntry.COLUMN_SHORT_DESCRIPTION)); String date = data.getString(data.getColumnIndex(WeatherContract.WeatherEntry.COLUMN_DATETEXT)); double high = data.getDouble(data.getColumnIndex(WeatherContract.WeatherEntry.COLUMN_TEMPERATURE_HIGH)); double low = data.getDouble(data.getColumnIndex(WeatherContract.WeatherEntry.COLUMN_TEMPERATURE_LOW)); double humidity = data.getDouble(data.getColumnIndex(WeatherContract.WeatherEntry.COLUMN_HUMIDITY)); float windSpeed = data.getFloat(data.getColumnIndex(WeatherContract.WeatherEntry.COLUMN_WIND_SPEED)); float windDir = data.getFloat(data.getColumnIndex(WeatherContract.WeatherEntry.COLUMN_DEGREES)); float pressure = data.getFloat(data.getColumnIndex(WeatherContract.WeatherEntry.COLUMN_PRESSURE)); boolean isMetric = Sunshine.isMetric(getActivity()); mIconView.setImageResource(Sunshine.getArtForWeatherId( WeatherContract.WeatherId.fromInt(weatherId))); mForecastTextView.setText(desc); mDateTextView.setText(Sunshine.formatDate(date)); mDayTextView.setText(Sunshine.dayName(getActivity(), date)); mHighTextView.setText(Sunshine.formatTemperature(getActivity(), high, isMetric)); mLowTextView.setText(Sunshine.formatTemperature(getActivity(), low, isMetric)); mWindTextView.setText(Sunshine.formatWind(getActivity(), windSpeed, windDir)); mPressureTextView.setText(getString(R.string.format_pressure, pressure)); mHumidityTextView.setText(getString(R.string.format_humidity, humidity)); } } @Override public void onLoaderReset(Loader<Cursor> cursorLoader) { getLoaderManager().restartLoader(0, null, this); } }
zmb3/sunshine
1
Sample weather app for Android
Java
zmb3
Zac Bergquist
gravitational
app/src/main/java/com/zmb/sunshine/ForecastAdapter.java
Java
package com.zmb.sunshine; import android.content.Context; import android.database.Cursor; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ImageView; import android.widget.TextView; import com.zmb.sunshine.data.db.WeatherContract; /** * A custom CursorAdapter that allows today's forecast * to use a different layout than the other days. */ public class ForecastAdapter extends CursorAdapter { private static final int VIEW_TYPE_TODAY = 0; private static final int VIEW_TYPE_FUTURE = 1; // determines whether the forecast for today uses a special view private boolean mUseDifferentTodayView = true; public ForecastAdapter(Context context, Cursor c, int flags) { super(context, c, flags); } public void setUseDifferentTodayView(boolean useDifferentView) { mUseDifferentTodayView = useDifferentView; } @Override public int getViewTypeCount() { // 2 different views - one for today, and one for other days return 2; } @Override public int getItemViewType(int position) { // on large devices (multi-pane) we always use the same view // on phones, we make the view for today a little bit bigger if (mUseDifferentTodayView) { return position == 0 ? VIEW_TYPE_TODAY : VIEW_TYPE_FUTURE; } return VIEW_TYPE_FUTURE; } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { int layout = getItemViewType(cursor.getPosition()) == VIEW_TYPE_TODAY ? R.layout.list_item_today : R.layout.list_item_forecast; View root = LayoutInflater.from(context).inflate(layout, parent, false); // create a view holder to avoid repeated findViewById() calls ViewHolder holder = new ViewHolder(root); root.setTag(holder); return root; } @Override public void bindView(View view, Context context, Cursor cursor) { ViewHolder holder = (ViewHolder) view.getTag(); // use the art for the first view (today), // and the regular icon for other days int weatherId = cursor.getInt(ForecastFragment.COL_WEATHER_CONDITION_ID); WeatherContract.WeatherId id = WeatherContract.WeatherId.fromInt(weatherId); int imageId = cursor.getPosition() == 0 ? Sunshine.getArtForWeatherId(id) : Sunshine.getIconForWeatherId(id); holder.mImageView.setImageResource(imageId); String date = cursor.getString(ForecastFragment.COL_WEATHER_DATE); holder.mDateView.setText(Sunshine.friendlyDate(context, date)); String desc = cursor.getString(ForecastFragment.COL_WEATHER_DESC); holder.mForecastView.setText(desc); boolean isMetric = Sunshine.isMetric(context); double maxTemp = cursor.getDouble(ForecastFragment.COL_WEATHER_HIGH); holder.mHighView.setText(Sunshine.formatTemperature(context, maxTemp, isMetric)); double minTemp = cursor.getDouble(ForecastFragment.COL_WEATHER_LOW); holder.mLowView.setText(Sunshine.formatTemperature(context, minTemp, isMetric)); } public static class ViewHolder { public final ImageView mImageView; public final TextView mDateView; public final TextView mForecastView; public final TextView mHighView; public final TextView mLowView; public ViewHolder(View parent) { mImageView = (ImageView) parent.findViewById(R.id.list_item_icon); mDateView = (TextView) parent.findViewById(R.id.list_item_date_textview); mForecastView = (TextView) parent.findViewById(R.id.list_item_forecast_textview); mHighView = (TextView) parent.findViewById(R.id.list_item_high_textview); mLowView = (TextView) parent.findViewById(R.id.list_item_low_textview); } } }
zmb3/sunshine
1
Sample weather app for Android
Java
zmb3
Zac Bergquist
gravitational
app/src/main/java/com/zmb/sunshine/ForecastFragment.java
Java
package com.zmb.sunshine; import android.app.Fragment; import android.app.LoaderManager; import android.content.CursorLoader; import android.content.Intent; import android.content.Loader; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import com.zmb.sunshine.data.db.AndroidDatabaseManager; import com.zmb.sunshine.data.db.WeatherContract; import com.zmb.sunshine.sync.SunshineSyncAdapter; import java.util.Date; /** * A fragment for displaying the overall forecast for * several days of weather data. */ public class ForecastFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>{ private static final String TAG = "ForecastFragment"; private static final String POSITION_KEY = "position"; private static final int LOADER_ID = 0; /** * The database columns that we'll display in this fragment. */ private static final String[] FORECAST_COLUMNS = { WeatherContract.WeatherEntry.TABLE_NAME + "." + WeatherContract.WeatherEntry._ID, WeatherContract.WeatherEntry.COLUMN_DATETEXT, WeatherContract.WeatherEntry.COLUMN_SHORT_DESCRIPTION, WeatherContract.WeatherEntry.COLUMN_TEMPERATURE_HIGH, WeatherContract.WeatherEntry.COLUMN_TEMPERATURE_LOW, WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, WeatherContract.WeatherEntry.COLUMN_WEATHER_ID }; // These indices are tied to the columns above. public static final int COL_WEATHER_ID = 0; public static final int COL_WEATHER_DATE = 1; public static final int COL_WEATHER_DESC = 2; public static final int COL_WEATHER_HIGH = 3; public static final int COL_WEATHER_LOW = 4; public static final int COL_LOCATION_SETTING = 5; public static final int COL_WEATHER_CONDITION_ID = 6; private ListView mForecastList; private ForecastAdapter mAdapter; private String mLocation; private int mSelectedPosition = ListView.INVALID_POSITION; private boolean mUseEnhancedTodayView = false; /** * A callback interface for all activities that * contain this fragment. This allows activities * to be notified of selections. */ public interface Callback { void onItemSelected(String date); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // indicate that we have a menu (otherwise our menu callbacks won't be called) setHasOptionsMenu(true); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // loaders get initialized here instead of in onCreate // because their lifecycles are bound to that of the // activity, not the fragment. getLoaderManager().initLoader(LOADER_ID, null, this); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); mAdapter = new ForecastAdapter(getActivity(), null, 0); mAdapter.setUseDifferentTodayView(mUseEnhancedTodayView); mForecastList = (ListView) rootView.findViewById(R.id.listview_forecast); mForecastList.setAdapter(mAdapter); mForecastList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) { mSelectedPosition = position; Cursor cursor = mAdapter.getCursor(); if (cursor != null && cursor.moveToPosition(position)) { // notify the activity that a day was selected // leave it up to the activity to display the details String date = cursor.getString(COL_WEATHER_DATE); ((Callback) getActivity()).onItemSelected(date); } } }); if (savedInstanceState != null && savedInstanceState.containsKey(POSITION_KEY)) { mSelectedPosition = savedInstanceState.getInt(POSITION_KEY); // we don't scroll to the position yet, because the list view // probably hasn't been populated yet (waiting for data from loader) } return rootView; } @Override public void onResume() { super.onResume(); // fetch new weather data if the location has changed if (mLocation != null && !getPreferredLocation().equals(mLocation)) { getLoaderManager().restartLoader(LOADER_ID, null, this); } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.forecast_fragment, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.action_refresh) { updateWeather(); return true; } else if (item.getItemId() == R.id.action_database) { Intent dbMgr = new Intent(getActivity(), AndroidDatabaseManager.class); startActivity(dbMgr); } else if (item.getItemId() == R.id.action_show_on_map) { Intent intent = new Intent(Intent.ACTION_VIEW); Uri location = Uri.parse("geo:0,0?").buildUpon() .appendQueryParameter("q", Sunshine.getPreferredLocation(getActivity())) .build(); intent.setData(location); // resolveActivity makes sure there is an application that // can handle the intent before we send it if (intent.resolveActivity(getActivity().getPackageManager()) != null) { startActivity(intent); } } return super.onOptionsItemSelected(item); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // save our position so we can ensure that the // selected item is in view when the activity // is recreated if (mSelectedPosition != ListView.INVALID_POSITION) { outState.putInt(POSITION_KEY, mSelectedPosition); } } /** * Configure how the fragment displays today's forecast. * Today's forecast can either use a larger, enhanced view, * or a standard view. * @param useEnhancedView true to use the enhanced view for today, * false otherwise */ public void setUseEnhancedTodayView(boolean useEnhancedView) { mUseEnhancedTodayView = useEnhancedView; if (mAdapter != null) { mAdapter.setUseDifferentTodayView(useEnhancedView); } else { Log.e(TAG, "Adapter hasn't been created yet."); } } private void updateWeather() { SunshineSyncAdapter.syncNow(getActivity()); } private String getPreferredLocation() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); return prefs.getString( getString(R.string.pref_location_key), getString(R.string.pref_location_default)); } /** * Called when a new Loader needs to be created. * The loader is going to use our content provider to query the database. */ @Override public Loader<Cursor> onCreateLoader(int id, Bundle bundle) { // we only want to look for current and future days' forecasts String today = WeatherContract.convertDateToString(new Date()); String orderAscending = WeatherContract.WeatherEntry.COLUMN_DATETEXT + " ASC"; mLocation = getPreferredLocation(); Uri uri = WeatherContract.WeatherEntry.buildWeatherLocationWithStartDate(mLocation, today); return new CursorLoader(getActivity(), uri, FORECAST_COLUMNS, null, null, orderAscending); } @Override public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) { mAdapter.swapCursor(cursor); if (mSelectedPosition != ListView.INVALID_POSITION) { mForecastList.setSelection(mSelectedPosition); } } @Override public void onLoaderReset(Loader<Cursor> cursorLoader) { mAdapter.swapCursor(null); } }
zmb3/sunshine
1
Sample weather app for Android
Java
zmb3
Zac Bergquist
gravitational
app/src/main/java/com/zmb/sunshine/MainActivity.java
Java
package com.zmb.sunshine; import android.app.Activity; import android.app.FragmentManager; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import com.zmb.sunshine.sync.SunshineSyncAdapter; public class MainActivity extends Activity implements ForecastFragment.Callback { private boolean mIsTwoPaneUi = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FragmentManager fm = getFragmentManager(); // check if we're in two pane UI or single pane if (findViewById(R.id.weather_detail_container) != null) { mIsTwoPaneUi = true; // show the detail view in this activity // (we only need to restore the detail fragment if // it wasn't already saved off) if (savedInstanceState== null) { fm.beginTransaction() .replace(R.id.weather_detail_container, new DetailFragment()) .commit(); } } else { mIsTwoPaneUi = false; } ForecastFragment ff = (ForecastFragment)(fm.findFragmentById(R.id.fragment_forecast)); ff.setUseEnhancedTodayView(!mIsTwoPaneUi); SunshineSyncAdapter.initialize(this); SunshineSyncAdapter.syncNow(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { Intent i = new Intent(this, SettingsActivity.class); startActivity(i); return true; } return super.onOptionsItemSelected(item); } /** * Called when a particular day is selected from the forecast list. * @param date */ @Override public void onItemSelected(String date) { if (mIsTwoPaneUi) { // on tablets, we replace the detail fragment DetailFragment details = new DetailFragment(); Bundle dateBundle = new Bundle(); dateBundle.putString(DetailFragment.DATE_KEY, date); details.setArguments(dateBundle); getFragmentManager().beginTransaction() .replace(R.id.weather_detail_container, details) .commit(); } else { // on phones, we launch the detail activity Intent intent = new Intent(this, DetailActivity.class); intent.putExtra(DetailFragment.DATE_KEY, date); startActivity(intent); } } }
zmb3/sunshine
1
Sample weather app for Android
Java
zmb3
Zac Bergquist
gravitational
app/src/main/java/com/zmb/sunshine/SettingsActivity.java
Java
package com.zmb.sunshine; import android.annotation.TargetApi; import android.app.Activity; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.view.MenuItem; public class SettingsActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // display the settings fragment getFragmentManager().beginTransaction() .replace(android.R.id.content, new SettingsFragment()) .commit(); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public Intent getParentActivityIntent() { // add the clear top flag - which checks if the parent (main) // activity is already running and avoids recreating it return super.getParentActivityIntent() .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); } }
zmb3/sunshine
1
Sample weather app for Android
Java
zmb3
Zac Bergquist
gravitational
app/src/main/java/com/zmb/sunshine/SettingsFragment.java
Java
package com.zmb.sunshine; import android.os.Bundle; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import com.zmb.sunshine.data.db.WeatherContract; import com.zmb.sunshine.sync.SunshineSyncAdapter; import com.zmb.sunshine.widget.SunshineWidget; public class SettingsFragment extends PreferenceFragment implements Preference.OnPreferenceChangeListener { boolean mIsBindingPreference = false; public SettingsFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // load preferences from XML resource addPreferencesFromResource(R.xml.preferences); // attach listeners to each preference bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_location_key))); bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_units_key))); bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_weather_provider_key))); } /** * Attaches a listener so the summary is always updated with the * preference value. Also fires the listener once to initialize * the summary (so it shows up before the value is changed). * @param preference */ private void bindPreferenceSummaryToValue(Preference preference) { try { mIsBindingPreference = true; preference.setOnPreferenceChangeListener(this); // trigger the listener immediately onPreferenceChange(preference, PreferenceManager .getDefaultSharedPreferences(preference.getContext()) .getString(preference.getKey(), "")); } finally { mIsBindingPreference = false; } } @Override public boolean onPreferenceChange(Preference preference, Object value) { // if we're not just starting up and binding the preferences if (!mIsBindingPreference) { // if the location setting or weather provider has changed, we need to fetch new data if (preference.getKey().equals(getString(R.string.pref_location_key)) || preference.getKey().equals(getString(R.string.pref_weather_provider_key))) { SunshineSyncAdapter.syncNow(getActivity()); } else { // weather data may need to be updated (ie units changed) getActivity().getContentResolver().notifyChange( WeatherContract.WeatherEntry.CONTENT_URI, null); if (preference.getKey().equals(getString(R.string.pref_units_key))) { // we have to explicitly pass the "isMetric" parameter, since // the preference hasn't actually changed yet // (Sunshine.isMetric() won't return the new value) boolean isMetric = value.toString().equals(getString(R.string.pref_units_metric)); SunshineWidget.updateAllWidgets(getActivity(), isMetric); } } } if (preference instanceof ListPreference) { // for ListPreferences, look up the correct display value // in the preference's 'entries' list ListPreference list = (ListPreference) preference; int index = list.findIndexOfValue(value.toString()); if (index >= 0) { preference.setSummary(list.getEntries()[index]); } } else { // for all other preferences, set the summary to the value preference.setSummary(value.toString()); } return true; } }
zmb3/sunshine
1
Sample weather app for Android
Java
zmb3
Zac Bergquist
gravitational
app/src/main/java/com/zmb/sunshine/Sunshine.java
Java
package com.zmb.sunshine; import android.content.Context; import android.preference.PreferenceManager; import com.zmb.sunshine.data.Convert; import com.zmb.sunshine.data.db.WeatherContract; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class Sunshine { private Sunshine() { } public static final String DEGREE_SYMBOL = "\u00B0"; private static final SimpleDateFormat sDatabaseFormat = new SimpleDateFormat("yyyyMMdd"); private static final SimpleDateFormat sDayFormat = new SimpleDateFormat("EEEE"); private static final SimpleDateFormat sMmonthDayFormat = new SimpleDateFormat("MMMM dd"); private static final SimpleDateFormat sShortDateFormat = new SimpleDateFormat("EEE MMM dd"); /** * Format a temperature for display. * @param context * @param temperature the temperature, ALWAYS METRIC * @param isMetric indicates whether the app is set to display metric units * @return */ public static String formatTemperature(Context context, double temperature, boolean isMetric) { if (!isMetric) { temperature = Convert.toFahrenheit(temperature); } return context.getString(R.string.format_temperature, temperature); } public static String formatDate(String dateText) { return DateFormat.getDateInstance().format(WeatherContract.convertStringToDate(dateText)); } public static String friendlyDate(Context context, String dateText) { Date today = new Date(); String todayString = WeatherContract.convertDateToString(today); Date input = WeatherContract.convertStringToDate(dateText); // 1) check if date is today if (todayString.equals(dateText)) { // format: "Today, June 24" String result = context.getString(R.string.today); return context.getString(R.string.format_full_friendly_date, result, formattedMonthDay(context, dateText)); } // 2) check if date is this week Calendar cal = Calendar.getInstance(); cal.setTime(today); cal.add(Calendar.DATE, 7); String nextWeekString = WeatherContract.convertDateToString(cal.getTime()); if (dateText.compareTo(nextWeekString) < 0) { // format: "Tuesday" return dayName(context, dateText); } // 3) future date return sShortDateFormat.format(input); } public static String shortFriendlyDate(Context context, String dateText) { String day = dayName(context, dateText); // for today and tomorrow, we still return today and tomorrow if (day.equals(context.getString(R.string.today)) || day.equals(context.getString(R.string.tomorrow))) { return day; } // for other days, just return the first 3 letters of the day // ie: "Sun", "Mon", etc. return day.substring(0, 3); } public static String formattedMonthDay(Context context, String date) { try { Date input = sDatabaseFormat.parse(date); return sMmonthDayFormat.format(input); } catch (ParseException e) { return ""; } } public static String dayName(Context context, String dateString) { Date input = WeatherContract.convertStringToDate(dateString); Date today = new Date(); String todayString =WeatherContract.convertDateToString(today); // check if the date is today or tomorrow if (dateString.equals(todayString)) { return context.getString(R.string.today); } Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, 1); String tomorrowString = WeatherContract.convertDateToString(cal.getTime()); if (dateString.equals(tomorrowString)) { return context.getString(R.string.tomorrow); } // if not today or tomorrow, then the day name will do return sDayFormat.format(input); } public static String formatWind(Context c, float speed, float degrees) { int windFormat; if (isMetric(c)) { windFormat = R.string.format_wind_kmh; } else { windFormat = R.string.format_wind_mph; speed *= 0.621371192237334f; } return String.format(c.getString(windFormat), speed, directionFromDegrees(degrees)); } private static String directionFromDegrees(float degrees) { if (degrees >= 337.5 || degrees < 22.5) { return "N"; } else if (degrees >= 22.5 && degrees < 67.5) { return "NE"; } else if (degrees >= 67.5 && degrees < 112.5) { return "E"; } else if (degrees >= 112.5 && degrees < 157.5) { return "SE"; } else if (degrees >= 157.5 && degrees < 202.5) { return"S"; } else if (degrees >= 202.5 && degrees < 247.5) { return"SW"; } else if (degrees >= 247.5 && degrees < 292.5) { return "W"; } else if (degrees >= 292.5 || degrees < 22.5) { return "NW"; } else { return "Unknown"; } } public static String getPreferredLocation(Context c) { return PreferenceManager.getDefaultSharedPreferences(c).getString( c.getString(R.string.pref_location_key), c.getString(R.string.pref_location_default)); } public static boolean isMetric(Context c) { return PreferenceManager.getDefaultSharedPreferences(c).getString( c.getString(R.string.pref_units_key), c.getString(R.string.pref_units_metric)) .equals(c.getString(R.string.pref_units_metric)); } /** * Get the art resource ID for the specified weather condition. * @param weatherId the weather ID * @return the resource id, or -1 if no match is found */ public static int getArtForWeatherId(WeatherContract.WeatherId weatherId) { switch (weatherId) { case CLOUDS: return R.drawable.art_clouds; case LIGHT_CLOUDS: return R.drawable.art_light_clouds; case CLEAR: return R.drawable.art_clear; case FOG: return R.drawable.art_fog; case LIGHT_RAIN: return R.drawable.art_light_rain; case RAIN: return R.drawable.art_rain; case SNOW: return R.drawable.art_snow; case STORM: return R.drawable.art_storm; } return -1; } /** * Get the icon resource ID for the specified weather ID. * @param weatherId the weather ID * @return the resource ID, or -1 if no match is found */ public static int getIconForWeatherId(WeatherContract.WeatherId weatherId) { switch (weatherId) { case CLOUDS: return R.drawable.ic_cloudy; case LIGHT_CLOUDS: return R.drawable.ic_light_clouds; case CLEAR: return R.drawable.ic_clear; case FOG: return R.drawable.ic_fog; case LIGHT_RAIN: return R.drawable.ic_light_rain; case RAIN: return R.drawable.ic_rain; case SNOW: return R.drawable.ic_snow; case STORM: return R.drawable.ic_storm; } return -1; } }
zmb3/sunshine
1
Sample weather app for Android
Java
zmb3
Zac Bergquist
gravitational
app/src/main/java/com/zmb/sunshine/data/AWeatherDataParser.java
Java
package com.zmb.sunshine.data; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.net.Uri; import com.zmb.sunshine.data.db.WeatherContract; public abstract class AWeatherDataParser implements IWeatherDataParser { /** * Insert a location into the database if it doesn't already exist. * * @param locationSetting * @param cityName * @param lat * @param lon * @return the row ID of the specified location */ protected long addLocation(Context c, String locationSetting, String cityName, double lat, double lon) { ContentResolver cr = c.getContentResolver(); Cursor cursor = cr.query( WeatherContract.LocationEntry.CONTENT_URI, new String[] { WeatherContract.LocationEntry._ID }, WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ?", new String[] { locationSetting }, null); try { if (cursor.moveToFirst()) { // the location was already in the database int locationId = cursor.getColumnIndex(WeatherContract.LocationEntry._ID); return cursor.getLong(locationId); } else { // location wasn't in database, must be added ContentValues values = new ContentValues(); values.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting); values.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName); values.put(WeatherContract.LocationEntry.COLUMN_LATITUDE, lat); values.put(WeatherContract.LocationEntry.COLUMN_LONGITUDE,lon); Uri uri = cr.insert(WeatherContract.LocationEntry.CONTENT_URI, values); return ContentUris.parseId(uri); } } finally { cursor.close(); } } }
zmb3/sunshine
1
Sample weather app for Android
Java
zmb3
Zac Bergquist
gravitational
app/src/main/java/com/zmb/sunshine/data/Convert.java
Java
package com.zmb.sunshine.data; /** * Contains various conversions. */ public class Convert { private Convert() { } /** * Convert a temperature in celsius to degrees fahrenheit. * @param celsius * @return */ public static double toFahrenheit(double celsius) { return celsius * 1.8 + 32d; } }
zmb3/sunshine
1
Sample weather app for Android
Java
zmb3
Zac Bergquist
gravitational
app/src/main/java/com/zmb/sunshine/data/DayForecast.java
Java
package com.zmb.sunshine.data; import java.util.Date; /** * An object to represent a single day in the weekly forecast. * All units are metric. */ public class DayForecast { private final double mHighTemperature; private final double mLowTemperature; private final DayOfWeek mDay; private final String mDescription; private final Date mDate; // TODO: add humidity, pressure, wind speed, wind direction public DayForecast(double high, double low, DayOfWeek day, String desc, Date date) { mHighTemperature = high; mLowTemperature = low; mDay = day; mDescription = desc; mDate = date; } /** * Get the high temperature for the day. (degrees Celsius) * @return */ public double getHighTemperature() { return mHighTemperature; } /** * Get the low temperature for the day. (degrees Celsius) * @return */ public double getLowTemperature() { return mLowTemperature; } public DayOfWeek getDay() { return mDay; } public Date getDate() { return mDate; } public String getDescription() { return mDescription; } @Override public String toString() { return toStringImperial(); } public String toStringMetric() { return mDay.toString() + " - " + mDescription + " - " + (int)mHighTemperature + " / " + (int)mLowTemperature; } public String toStringImperial() { return mDay.toString() + " - " + mDescription + " - " + (int)Convert.toFahrenheit(mHighTemperature) + " / " + (int)Convert.toFahrenheit(mLowTemperature); } }
zmb3/sunshine
1
Sample weather app for Android
Java
zmb3
Zac Bergquist
gravitational
app/src/main/java/com/zmb/sunshine/data/DayOfWeek.java
Java
package com.zmb.sunshine.data; /** * A day of the week, such as 'Tuesday'. */ public enum DayOfWeek { MONDAY(1), TUESDAY(2), WEDNESDAY(3), THURSDAY(4), FRIDAY(5), SATURDAY(6), SUNDAY(7); final int mValue; private DayOfWeek(int value) { mValue = value; } /** * Returns the ISO-8601 value for the day. * 1 (Monday) through 7 (Sunday). * @return */ public int getValue() { return mValue; } public String toString() { switch (this) { case MONDAY: return "Monday"; case TUESDAY: return "Tuesday"; case WEDNESDAY: return "Wednesday"; case THURSDAY: return "Thursday"; case FRIDAY: return "Friday"; case SATURDAY: return "Saturday"; case SUNDAY: return "Sunday"; default: return null; } } }
zmb3/sunshine
1
Sample weather app for Android
Java
zmb3
Zac Bergquist
gravitational
app/src/main/java/com/zmb/sunshine/data/IWeatherDataParser.java
Java
package com.zmb.sunshine.data; import android.content.Context; import java.net.MalformedURLException; import java.net.URL; /** * Parses weather data returned by a web service. */ public interface IWeatherDataParser { /** * Builds the URL to query for weather data. * * @param locationSetting the location to query for data * @param daysToFetch the number of days of data to query for * @return the URL to query * @throws MalformedURLException */ public URL buildUrl(String locationSetting, int daysToFetch) throws MalformedURLException; /** * This method is responsible for parsing the API response * and inserting the resulting data into the database. * * @param c * @param data the API response * @param numberOfDays the number of days worth of data to parse * @throws WeatherParseException if an error occurs */ public void parse(Context c, String data, int numberOfDays) throws WeatherParseException; }
zmb3/sunshine
1
Sample weather app for Android
Java
zmb3
Zac Bergquist
gravitational
app/src/main/java/com/zmb/sunshine/data/WeatherParseException.java
Java
package com.zmb.sunshine.data; import java.io.IOException; /** * This exception indicates that the weather data returned * by a web service couldn't be parsed. */ public class WeatherParseException extends IOException { private final String mData; private final Exception mInnerException; public WeatherParseException(String data, Exception innerException) { mData = data; mInnerException = innerException; } }
zmb3/sunshine
1
Sample weather app for Android
Java
zmb3
Zac Bergquist
gravitational