Browse Source

Merge branch 'morejson-barcode' into morejson

Sebastian Pipping 9 years ago
parent
commit
00d4c81b28

+ 5
- 0
client-barcode/freitagskasse.conf.sample View File

@@ -0,0 +1,5 @@
1
+[client-barcode]
2
+SERVER_URL = https://example.org:443/api2/
3
+SERVER_USER = user
4
+SERVER_PASSWORD = password
5
+#CLIENT_DEBUG = 1

+ 5
- 0
client-barcode/freitagskasse.py View File

@@ -8,6 +8,7 @@ from __future__ import print_function
8 8
 import freitagslib.network as net
9 9
 from freitagslib.commands import BuyCommand, DepositCommand
10 10
 from freitagslib.encoding import asciify
11
+from freitagslib.settings import settings, Settings
11 12
 
12 13
 import colorama
13 14
 from colorama import Fore, Style
@@ -519,6 +520,10 @@ def read_line(f, timeout, timeout_func):
519 520
 
520 521
 def main():
521 522
 	colorama.init()
523
+
524
+	if not settings.load("freitagskasse.conf"):
525
+		sys.exit(1)
526
+
522 527
 	status = Status()
523 528
 	global scroll_line1,scroll_line2
524 529
 	global myDisplay

+ 1
- 1
client-barcode/freitagslib/commands.py View File

@@ -53,7 +53,7 @@ class BuyCommand(object):
53 53
 			raise ValueError("BuyCommand in illegal state")
54 54
 
55 55
 	def run(self, user_name):
56
-		net.buy_item(self._item.id, what_about_it=self._what_to_buy(), user_name=user_name)
56
+		raise NotImplementedError('BuyCommand.run(user_name)')
57 57
 
58 58
 	def item_name(self):
59 59
 		return self._item.name

+ 25
- 28
client-barcode/freitagslib/network.py View File

@@ -18,39 +18,43 @@ if __name__ == '__main__':
18 18
 	sys.path.append('.')
19 19
 from freitagslib.item import Item
20 20
 from freitagslib.tools import require_type
21
+from freitagslib.settings import settings, Settings
21 22
 
22 23
 
23 24
 DEPOSIT_CASH = 1
24 25
 DEPOSIT_BANK = 2
25 26
 
26 27
 
27
-_BASE_URL = 'https://k4ever.freitagsrunde.org:443/api2/'
28
+ITEM_ONLY, DEPOSIT_ONLY, ITEM_AND_DEPOSIT = range(3)
28 29
 
29
-_auth = base64.encodestring('%s:%s' % (os.environ['BARCODE_PLUGIN_USER'], os.environ['BARCODE_PLUGIN_PASS'])).rstrip()
30
-_headers = {'Authorization':'Basic %s' % _auth}
31 30
 
32
-ITEM_ONLY, DEPOSIT_ONLY, ITEM_AND_DEPOSIT = range(3)
31
+def _urlopen(*args):
32
+	if settings.CLIENT_DEBUG:
33
+		_h = urllib2.HTTPHandler(debuglevel=1)
34
+		_opener = urllib2.build_opener(_h)
35
+		_func = _opener.open
36
+	else:
37
+		_func = urllib2.urlopen
38
+	return _func(*args)
33 39
 
34 40
 
35
-if bool(os.environ.get('BARCODE_PLUGIN_DEBUG', False)):
36
-	_h = urllib2.HTTPHandler(debuglevel=1)
37
-	_opener = urllib2.build_opener(_h)
38
-	_urlopen = _opener.open
39
-else:
40
-	_urlopen = urllib2.urlopen
41
+def _get_default_headers():
42
+	_auth = base64.encodestring('%s:%s' % (settings.SERVER_USER, settings.SERVER_PASSWORD)).rstrip()
43
+	_headers = {'Authorization':'Basic %s' % _auth}
44
+	return _headers
41 45
 
42 46
 
43 47
 def _request(api_rel_url, data, method, headers=None):
44
-	url = _BASE_URL + api_rel_url
48
+	url = settings.SERVER_URL + api_rel_url
45 49
 
46 50
 	if isinstance(data, dict):
47 51
 		data = urllib.urlencode(data)
48 52
 
49 53
 	# Add default headers
50 54
 	if headers is None:
51
-		final_headers = _headers
55
+		final_headers = _get_default_headers()
52 56
 	else:
53
-		final_headers = copy.copy(_headers)
57
+		final_headers = copy.copy(_get_default_headers())
54 58
 		final_headers.update(headers)
55 59
 
56 60
 	if method == 'GET':
@@ -71,16 +75,6 @@ def get_user_name_from_auth_blob(authblob):
71 75
 	return d['username']
72 76
 
73 77
 
74
-def buy_item(item_id, what_about_it, user_name):
75
-	require_type(int, item_id)
76
-	assert(what_about_it in (ITEM_ONLY, DEPOSIT_ONLY, ITEM_AND_DEPOSIT))
77
-
78
-	content = _request('buyable/item/' + urllib.quote(str(item_id)),
79
-			{'user':user_name, 'deposit':what_about_it, 'amount':1}, method='POST')
80
-	if content != 'Created':
81
-		raise ValueError('Server says "%s"' % content)
82
-
83
-
84 78
 def bulk_buy(buycommands, user_name):
85 79
 	item_ids = tuple(e.item_id() for e in buycommands if e.includes_commodity())
86 80
 	deposit_ids = tuple(e.item_id() for e in buycommands if e.includes_deposit())
@@ -99,7 +93,8 @@ def bulk_buy(buycommands, user_name):
99 93
 		'Content-Length':len(data)
100 94
 	}
101 95
 	content = _request('buyable/item/bulkbuy/', data, 'POST', headers=headers)
102
-	if content != 'Created':
96
+	d = json.loads(content)
97
+	if not d['success']:
103 98
 		raise ValueError('Server says "%s"' % content)
104 99
 
105 100
 
@@ -123,15 +118,17 @@ def deposit(amount, transaction_type, user_name):
123 118
 
124 119
 	content = _request('account/transactions/transact/',
125 120
 			{'user':user_name, 'amount':amount, 'type':transaction_type}, method='POST')
126
-	if content != 'OK':
121
+	d = json.loads(content)
122
+	if not d['success']:
127 123
 		raise ValueError('Server says "%s"' % content)
128 124
 
129 125
 
130 126
 if __name__ == '__main__':
131
-	user_name = get_user_name_from_auth_blob(os.environ['BARCODE_PLUGIN_TEST_AUTH_BLOB'])
132
-	print('User name: ' + user_name)
127
+	if not settings.load('freitagskasse.conf', (('TEST_AUTH_BLOB', str, None), )):
128
+		sys.exit(1)
133 129
 
134
-	buy_item(1, True, user_name)
130
+	user_name = get_user_name_from_auth_blob(settings.TEST_AUTH_BLOB)
131
+	print('User name: ' + user_name)
135 132
 
136 133
 	balance = get_balance(user_name)
137 134
 	print('Balance is %f, type is "%s"' % (balance, type(balance).__name__))

+ 63
- 0
client-barcode/freitagslib/settings.py View File

@@ -0,0 +1,63 @@
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
+
7
+from __future__ import print_function
8
+import sys
9
+import ConfigParser
10
+
11
+
12
+_SECTION = 'client-barcode'
13
+
14
+_KEYS = (
15
+	# Key, type, default
16
+	('CLIENT_DEBUG', bool, False),  # Should go first to enable debugging as early as possible
17
+	('SERVER_URL', str, None),
18
+	('SERVER_USER', str, None),
19
+	('SERVER_PASSWORD', str, None),
20
+)
21
+
22
+_DEFAULTS = dict([(key, str(default))
23
+	for (key, _type, default)
24
+	in _KEYS
25
+	if default is not None])
26
+
27
+
28
+class Settings:
29
+	def __init__(self):
30
+		pass
31
+
32
+	def load(self, filename, _additional_keys=None):
33
+		additional_keys = () if _additional_keys is None else _additional_keys
34
+
35
+		cp = ConfigParser.ConfigParser(_DEFAULTS)
36
+		if not cp.read(filename):
37
+			print('FATAL: Config file "%s" could not be parsed.' % (filename), file=sys.stderr)
38
+			return False
39
+
40
+		valid = True
41
+		for key, _type, dummy in _KEYS + additional_keys:
42
+			try:
43
+				if _type is bool:
44
+					value = cp.getboolean(_SECTION, key)
45
+				else:
46
+					value = cp.get(_SECTION, key)
47
+			except ValueError:
48
+				print('ERROR: Key "%s" in config file "%s" must be of type "%s".' \
49
+						% (key, filename, _type.__name__), file=sys.stderr)
50
+				valid = False
51
+			except ConfigParser.NoOptionError:
52
+				print('ERROR: Config file "%s" misses required key "%s.%s".' \
53
+						% (filename, _SECTION, key), file=sys.stderr)
54
+				valid = False
55
+			else:
56
+				setattr(self, key, value)
57
+				if self.CLIENT_DEBUG:
58
+					print('DEBUG: CONFIG: %s.%s=%s("%s")' % (_SECTION, key, type(value).__name__, value))
59
+
60
+		return valid
61
+
62
+
63
+settings = Settings()

Loading…
Cancel
Save