No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

network.py 3.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. #! /usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # Copyright (C) 2011 Sebastian Pipping <sebastian@pipping.org>
  5. # Licensed under GPL v3 or later
  6. from __future__ import print_function
  7. import urllib
  8. import urllib2
  9. import simplejson as json
  10. from decimal import Decimal
  11. import os
  12. import base64
  13. import copy
  14. if __name__ == '__main__':
  15. import sys
  16. sys.path.append('.')
  17. from freitagslib.item import Item
  18. from freitagslib.tools import require_type
  19. DEPOSIT_CASH = 1
  20. DEPOSIT_BANK = 2
  21. _BASE_URL = 'https://k4ever.freitagsrunde.org:443/api2/'
  22. _auth = base64.encodestring('%s:%s' % (os.environ['BARCODE_PLUGIN_USER'], os.environ['BARCODE_PLUGIN_PASS'])).rstrip()
  23. _headers = {'Authorization':'Basic %s' % _auth}
  24. ITEM_ONLY, DEPOSIT_ONLY, ITEM_AND_DEPOSIT = range(3)
  25. if bool(os.environ.get('BARCODE_PLUGIN_DEBUG', False)):
  26. _h = urllib2.HTTPHandler(debuglevel=1)
  27. _opener = urllib2.build_opener(_h)
  28. _urlopen = _opener.open
  29. else:
  30. _urlopen = urllib2.urlopen
  31. def _request(api_rel_url, data, method, headers=None):
  32. url = _BASE_URL + api_rel_url
  33. if isinstance(data, dict):
  34. data = urllib.urlencode(data)
  35. # Add default headers
  36. if headers is None:
  37. final_headers = _headers
  38. else:
  39. final_headers = copy.copy(_headers)
  40. final_headers.update(headers)
  41. if method == 'GET':
  42. url = '%s?%s' % (url, data)
  43. req = urllib2.Request(url, headers=final_headers)
  44. elif method == 'POST':
  45. req = urllib2.Request(url, data=data, headers=final_headers)
  46. else:
  47. raise ValueError('Unsupported method "%s"' % method)
  48. response = _urlopen(req)
  49. return response.read()
  50. def get_user_name_from_auth_blob(authblob):
  51. content = _request('auth/user/', {'authblob':authblob}, method='GET')
  52. d = json.loads(content)
  53. return d['username']
  54. def bulk_buy(buycommands, user_name):
  55. item_ids = tuple(e.item_id() for e in buycommands if e.includes_commodity())
  56. deposit_ids = tuple(e.item_id() for e in buycommands if e.includes_deposit())
  57. if not item_ids and not deposit_ids:
  58. return
  59. request_dict = {
  60. 'user':user_name,
  61. 'items':item_ids,
  62. 'deposits':deposit_ids
  63. }
  64. data = json.dumps(request_dict, sort_keys=True, indent=4 * ' ')
  65. headers = {
  66. 'Content-Type':'application/json',
  67. 'Content-Length':len(data)
  68. }
  69. content = _request('buyable/item/bulkbuy/', data, 'POST', headers=headers)
  70. if content != 'Created':
  71. raise ValueError('Server says "%s"' % content)
  72. def get_item(barcode):
  73. content = _request('buyable/item/',
  74. {'barcode':barcode}, method='GET')
  75. d = json.loads(content)
  76. return Item(d)
  77. def get_balance(user_name):
  78. content = _request('account/balance/',
  79. {'user':user_name}, method='GET')
  80. d = json.loads(content)
  81. return Decimal(d['balance'])
  82. def deposit(amount, transaction_type, user_name):
  83. require_type(Decimal, amount)
  84. require_type(int, transaction_type)
  85. content = _request('account/transactions/transact/',
  86. {'user':user_name, 'amount':amount, 'type':transaction_type}, method='POST')
  87. if content != 'OK':
  88. raise ValueError('Server says "%s"' % content)
  89. if __name__ == '__main__':
  90. user_name = get_user_name_from_auth_blob(os.environ['BARCODE_PLUGIN_TEST_AUTH_BLOB'])
  91. print('User name: ' + user_name)
  92. balance = get_balance(user_name)
  93. print('Balance is %f, type is "%s"' % (balance, type(balance).__name__))
  94. deposit(Decimal('0.01'), DEPOSIT_CASH, user_name)
  95. deposit(Decimal('0.01'), DEPOSIT_BANK, user_name)
  96. def show(item):
  97. print('Item "%s" is %f Euro each' % (item.name, item.price))
  98. item5 = get_item(5)
  99. item6 = get_item(6)
  100. for item in (item5, item6):
  101. show(item)
  102. from freitagslib.commands import BuyCommand
  103. buycommands = (BuyCommand(e) for e in (item5, item6))
  104. bulk_buy(buycommands, user_name)