]> git.lizzy.rs Git - go-anidb.git/blob - anidb.go
Modernize
[go-anidb.git] / anidb.go
1 // Attempt at high level client library for AniDB's APIs
2 package anidb
3
4 import (
5         "io/ioutil"
6         "log"
7         "time"
8 )
9
10 // Main struct for the client, contains all non-shared state.
11 //
12 // All ObjectByKey methods (AnimeByID, GroupByName, etc) first try to read
13 // from the cache. If the sought object isn't cached, or if the cache is
14 // stale, then the appropriate API is queried.
15 //
16 // Queries return their results using channels. Most queries only have one result,
17 // but some have 0 or more. All result channels are closed after sending their data.
18 //
19 // Queries that depend on the UDP API can't be used without first authenticating
20 // to the API server. This uses the credentials stored by SetCredentials, or
21 // by a previous Auth() call.
22 type AniDB struct {
23         Timeout time.Duration // Timeout for the various calls (default: 45s)
24         Logger  *log.Logger   // Logger where HTTP/UDP traffic is logged
25
26         udp *udpWrap
27 }
28
29 // Initialises a new AniDB.
30 func NewAniDB() *AniDB {
31         ret := &AniDB{
32                 Timeout: 45 * time.Second,
33                 Logger:  log.New(ioutil.Discard, "", log.LstdFlags),
34         }
35         ret.udp = newUDPWrap(ret)
36         return ret
37 }
38
39 func (adb *AniDB) User() *User {
40         if adb != nil && adb.udp != nil {
41                 if adb.udp.user != nil {
42                         return adb.udp.user
43                 } else if adb.udp.credentials != nil {
44                         // see if we can get it from the cache (we don't care if it's stale)
45                         adb.udp.user = UserByName(decrypt(adb.udp.credentials.username))
46                         if adb.udp.user != nil {
47                                 return adb.udp.user
48                         }
49                         // we have to go through the slow path
50                         adb.udp.user = <-adb.GetUserByName(decrypt(adb.udp.credentials.username))
51                         return adb.udp.user
52                 }
53         }
54         return nil
55 }