Debian Codegraph @

client/client.go

raw
1 package client
2
3 import (
4 "fmt"
5 "time"
6
7 "github.com/mitch000001/go-hbci/bankinfo"
8 "github.com/mitch000001/go-hbci/dialog"
9 "github.com/mitch000001/go-hbci/domain"
10 "github.com/mitch000001/go-hbci/element"
11 "github.com/mitch000001/go-hbci/message"
12 "github.com/mitch000001/go-hbci/segment"
13 "github.com/mitch000001/go-hbci/swift"
14 "github.com/mitch000001/go-hbci/transport"
15 )
16
17 // Config defines the basic configuration needed for a Client to work.
18 type Config struct {
19 BankID string `json:"bank_id"`
20 AccountID string `json:"account_id"`
21 PIN string `json:"pin"`
22 URL string `json:"url"`
23 HBCIVersion int `json:"hbci_version"`
24 Transport transport.Transport
25 }
26
27 func (c Config) hbciVersion() (segment.HBCIVersion, error) {
28 version, ok := segment.SupportedHBCIVersions[c.HBCIVersion]
29 if !ok {
30 return version, fmt.Errorf("Unsupported HBCI version. Supported versions are %v", domain.SupportedHBCIVersions)
31 }
32 return version, nil
33 }
34
35 // New creates a new HBCI client. It returns an error if the provided
36 // HBCI-Version of the config is not supported or if there is no entry in the
37 // bank institute database for the provided BankID.
38 //
39 // If the provided Config does not provide a URL or a HBCI-Version it will be
40 // looked up in the bankinfo database.
41 func New(config Config) (*Client, error) {
42 bankID := domain.BankID{
43 CountryCode: 280,
44 ID: config.BankID,
45 }
46 bankInfo := bankinfo.FindByBankID(config.BankID)
47 var (
48 url string
49 hbciVersion segment.HBCIVersion
50 )
51 if config.URL != "" {
52 url = config.URL
53 } else {
54 url = bankInfo.URL
55 }
56 if config.HBCIVersion > 0 {
57 version, err := config.hbciVersion()
58 if err != nil {
59 return nil, err
60 }
61 hbciVersion = version
62 } else {
63 version, ok := segment.SupportedHBCIVersions[bankInfo.HbciVersion()]
64 if !ok {
65 return nil, fmt.Errorf("Unsupported HBCI version. Supported versions are %v", domain.SupportedHBCIVersions)
66 }
67 hbciVersion = version
68 }
69 dcfg := dialog.Config{
70 BankID: bankID,
71 HBCIURL: url,
72 UserID: config.AccountID,
73 HBCIVersion: hbciVersion,
74 Transport: config.Transport,
75 }
76
77 d := dialog.NewPinTanDialog(dcfg)
78 d.SetPin(config.PIN)
79 client := &Client{
80 config: config,
81 hbciVersion: hbciVersion,
82 pinTanDialog: d,
83 }
84 return client, nil
85 }
86
87 // Client is the main entrypoint to perform high level HBCI requests.
88 //
89 // Its methods reflect possible actions and abstract the lower level dialog
90 // methods.
91 type Client struct {
92 config Config
93 hbciVersion segment.HBCIVersion
94 pinTanDialog *dialog.PinTanDialog
95 }
96
97 func (c *Client) init() error {
98 if c.pinTanDialog.BankParameterDataVersion() == 0 {
99 _, err := c.pinTanDialog.SyncClientSystemID()
100 if err != nil {
101 return fmt.Errorf("error while fetching accounts: %v", err)
102 }
103 }
104 return nil
105 }
106
107 // Accounts return the basic account information for the provided client config.
108 func (c *Client) Accounts() ([]domain.AccountInformation, error) {
109 if err := c.init(); err != nil {
110 return nil, err
111 }
112 err := c.pinTanDialog.SyncUserParameterData()
113 if err != nil {
114 return nil, fmt.Errorf("error getting accounts")
115 }
116 return c.pinTanDialog.Accounts, nil
117 }
118
119 // AccountTransactions return all transactions for the provided timeframe.
120 // If allAccouts is true, it will fetch all transactions associated with the
121 // proviced account. For the initial request no continuationReference is
122 // needed, as this method will be called recursivly if the server sends one.
123 func (c *Client) AccountTransactions(account domain.AccountConnection, timeframe domain.Timeframe, allAccounts bool, continuationReference string) ([]domain.AccountTransaction, error) {
124 if err := c.init(); err != nil {
125 return nil, err
126 }
127 requestBuilder := func() (segment.AccountTransactionRequest, error) {
128 builder := segment.NewBuilder(c.pinTanDialog.SupportedSegments())
129 return builder.AccountTransactionRequest(account, allAccounts)
130 }
131 bookedSwiftTransactions, err := c.accountTransactions(requestBuilder, timeframe, continuationReference)
132 if err != nil {
133 return nil, fmt.Errorf("error executing HBCI request: %w", err)
134 }
135 unmarshaler := swift.NewMT940MessagesUnmarshaler()
136 tx, err := unmarshaler.UnmarshalMT940(bookedSwiftTransactions.Data)
137 if err != nil {
138 return nil, fmt.Errorf("error unmarshaling SWIFT transactions: %w", err)
139 }
140 return tx, nil
141 }
142
143 // SepaAccountTransactions return all transactions for the provided timeframe.
144 // If allAccouts is true, it will fetch all transactions associated with the
145 // provided account. For the initial request no continuationReference is
146 // needed, as this method will be called recursivly if the server sends one.
147 func (c *Client) SepaAccountTransactions(account domain.InternationalAccountConnection, timeframe domain.Timeframe, allAccounts bool, continuationReference string) ([]domain.AccountTransaction, error) {
148 if err := c.init(); err != nil {
149 return nil, err
150 }
151 requestBuilder := func() (segment.AccountTransactionRequest, error) {
152 builder := segment.NewBuilder(c.pinTanDialog.SupportedSegments())
153 return builder.SepaAccountTransactionRequest(account, allAccounts)
154 }
155 bookedSwiftTransactions, err := c.accountTransactions(requestBuilder, timeframe, continuationReference)
156 if err != nil {
157 return nil, fmt.Errorf("error executing HBCI request: %w", err)
158 }
159 unmarshaler := swift.NewMT940MessagesUnmarshaler()
160 tx, err := unmarshaler.UnmarshalMT940(bookedSwiftTransactions.Data)
161 if err != nil {
162 return nil, fmt.Errorf("error unmarshaling SWIFT transactions: %w", err)
163 }
164 return tx, nil
165 }
166
167 func (c *Client) accountTransactions(requestBuilder func() (segment.AccountTransactionRequest, error), timeframe domain.Timeframe, continuationReference string) (*swift.MT940Messages, error) {
168 accountTransactionRequest, err := requestBuilder()
169 if err != nil {
170 return nil, fmt.Errorf("error building request: %w", err)
171 }
172 accountTransactionRequest.SetTransactionRange(timeframe)
173 if continuationReference != "" {
174 accountTransactionRequest.SetContinuationReference(continuationReference)
175 }
176 decryptedMessage, err := c.pinTanDialog.SendMessage(
177 message.NewHBCIMessage(c.hbciVersion, c.hbciVersion.TanProcess4Request(segment.IdentificationID), accountTransactionRequest),
178 )
179 if err != nil {
180 return nil, fmt.Errorf("error sending hbci request: %w", err)
181 }
182 var bookedSwiftTransactions []*swift.MT940Messages
183 accountTransactionResponses := decryptedMessage.FindSegments("HIKAZ")
184 for _, unmarshaledSegment := range accountTransactionResponses {
185 seg, ok := unmarshaledSegment.(segment.AccountTransactionResponse)
186 if !ok {
187 return nil, fmt.Errorf("malformed segment found with ID `HIKAZ`")
188 }
189 bookedSwiftTransactions = append(bookedSwiftTransactions, seg.BookedSwiftTransactions())
190 }
191 var newContinuationReference string
192 acknowledgements := decryptedMessage.Acknowledgements()
193 for _, ack := range acknowledgements {
194 if ack.Code == element.AcknowledgementAdditionalInformation {
195 newContinuationReference = ack.Params[0]
196 break
197 }
198 }
199 tx := swift.MergeMT940Messages(bookedSwiftTransactions...)
200 if newContinuationReference == "" {
201 return tx, nil
202 }
203 msg, err := c.accountTransactions(requestBuilder, timeframe, newContinuationReference)
204 if err != nil {
205 return nil, err
206 }
207 return swift.MergeMT940Messages(msg, tx), err
208 }
209
210 // AccountInformation will print all information attached to the provided
211 // account. If allAccounts is true it will fetch also the information
212 // associated with the account.
213 func (c *Client) AccountInformation(account domain.AccountConnection, allAccounts bool) error {
214 if err := c.init(); err != nil {
215 return err
216 }
217 accountInformationRequest := segment.NewAccountInformationRequestSegmentV1(account, allAccounts)
218 decryptedMessage, err := c.pinTanDialog.SendMessage(
219 message.NewHBCIMessage(c.hbciVersion, c.hbciVersion.TanProcess4Request(segment.IdentificationID), accountInformationRequest),
220 )
221 if err != nil {
222 return err
223 }
224 accountInfoResponse := decryptedMessage.FindMarshaledSegment("HIKIF")
225 if accountInfoResponse != nil {
226 fmt.Printf("Account Info: %s\n", accountInfoResponse)
227 return nil
228 }
229 return fmt.Errorf("malformed response: expected HIKIF segment")
230 }
231
232 // AccountBalances retrieves the balance for the provided account.
233 // If allAccounts is true it will fetch also the balances for all accounts
234 // associated with the account.
235 func (c *Client) AccountBalances(account domain.AccountConnection, allAccounts bool) ([]domain.AccountBalance, error) {
236 if err := c.init(); err != nil {
237 return nil, err
238 }
239 builder := segment.NewBuilder(c.pinTanDialog.SupportedSegments())
240 accountBalanceRequest, err := builder.AccountBalanceRequest(account, allAccounts)
241 if err != nil {
242 return nil, err
243 }
244 decryptedMessage, err := c.pinTanDialog.SendMessage(
245 message.NewHBCIMessage(
246 c.hbciVersion,
247 c.hbciVersion.TanProcess4Request(segment.IdentificationID),
248 accountBalanceRequest,
249 ),
250 )
251 if err != nil {
252 return nil, err
253 }
254 var balances []domain.AccountBalance
255 balanceResponses := decryptedMessage.FindMarshaledSegments("HISAL")
256 if balanceResponses != nil {
257 for _, marshaledSegment := range balanceResponses {
258 balanceSegment := &segment.AccountBalanceResponseSegment{}
259 err = balanceSegment.UnmarshalHBCI(marshaledSegment)
260 if err != nil {
261 return nil, fmt.Errorf("error while parsing account balance: %v", err)
262 }
263 balances = append(balances, balanceSegment.AccountBalance())
264 }
265 } else {
266 return nil, fmt.Errorf("malformed response: expected HISAL segment")
267 }
268
269 return balances, nil
270 }
271
272 // Status returns information about open jobs to fetch from the institute.
273 // If a continuationReference is present, the status information attached to it
274 // will be fetched.
275 func (c *Client) Status(from, to time.Time, maxEntries int, continuationReference string) ([]domain.StatusAcknowledgement, error) {
276 if err := c.init(); err != nil {
277 return nil, err
278 }
279 builder := segment.NewBuilder(c.pinTanDialog.SupportedSegments())
280 statusRequest, err := builder.StatusProtocolRequest(from, to, maxEntries, continuationReference)
281 if err != nil {
282 return nil, err
283 }
284 bankMessage, err := c.pinTanDialog.SendMessage(
285 message.NewHBCIMessage(c.hbciVersion, c.hbciVersion.TanProcess4Request(segment.IdentificationID), statusRequest),
286 )
287 if err != nil {
288 return nil, err
289 }
290 var statusAcknowledgements []domain.StatusAcknowledgement
291 statusResponses := bankMessage.FindSegments("HIPRO")
292 for _, seg := range statusResponses {
293 statusResponse := seg.(segment.StatusProtocolResponse)
294 statusAcknowledgements = append(statusAcknowledgements, statusResponse.Status())
295 }
296 return statusAcknowledgements, nil
297 }
298
299 // AnonymousClient wraps a Client and allows anonymous requests to bank
300 // institutes. Examples for those jobs are stock exchange news.
301 type AnonymousClient struct {
302 *Client
303 }
304
305 // CommunicationAccess returns data used to make calls to a given institute.
306 // Not yet properly implemented, therefore only the raw data are returned.
307 func (a *AnonymousClient) CommunicationAccess(from, to domain.BankID, maxEntries int) ([]byte, error) {
308 commRequest := segment.NewCommunicationAccessRequestSegment(from, to, maxEntries, "")
309 decryptedMessage, err := a.pinTanDialog.SendAnonymousMessage(message.NewHBCIMessage(a.hbciVersion, commRequest))
310 if err != nil {
311 return nil, err
312 }
313 return []byte(fmt.Sprintf("%+#v", decryptedMessage)), nil
314 }