aboutsummaryrefslogtreecommitdiffstats
path: root/partmgr/pricefetch/pricefetch.py
blob: 9e3899598d2295170d73023455f9a9d8ebc05148 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# -*- coding: utf-8 -*-
#
# PartMgr - Price fetching
#
# Copyright 2015-2022 Michael Buesch <m@bues.ch>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#

from partmgr.core.parameter import *
from partmgr.core.util import *

import http.client
import urllib.parse


class PriceFetcher:
	"""Part price fetcher."""

	class Error(Exception):
		pass

	class Result:
		FOUND = True
		NOTFOUND = False

		def __init__(self,
			     orderCode = None,
			     price = 0.0,
			     status = FOUND,
			     currency = Param_Currency.CURR_EUR):
			self.orderCode = orderCode
			self.price = price
			self.status = status
			self.currency = currency

		def __repr__(self):
			if self.status == self.FOUND:
				curr = Param_Currency.CURRNAMES[self.currency][0]
				return "%s: %.2f %s" % (
					self.orderCode, self.price, curr)
			else:
				return "%s: not found" % self.orderCode

	supplierNames = None
	host = None

	_registeredFetchers = []

	_defaultHttpHeaders = {
		"User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:105.0) Gecko/20100101 Firefox/105.0",
		"Accept" : "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
		"Accept-Language" : "*",
		"Accept-Charset" : "utf-8,*;q=0.9",
	}

	@classmethod
	def register(cls):
		PriceFetcher._registeredFetchers.append(cls)

	@classmethod
	def get(cls, wantedSupplierName):
		stripCs = "/\\_-,.;:\"'()|"
		wantedSupplierName = wantedSupplierName.lower().strip().strip(stripCs).strip()
		for fetcher in cls._registeredFetchers:
			if wantedSupplierName in (n.lower().strip().strip(stripCs).strip()
						  for n in fetcher.supplierNames):
				return fetcher
		return None

	def __init__(self, tls = True):
		self.conn = None
		self.tls = tls

	def __del__(self):
		try:
			self.disconnect()
		except Exception as e:
			pass

	def _relax(self):
		pass

	def _sendRequest(self, method, url, body=None, headers={}):
		if not headers:
			headers = self._defaultHttpHeaders
		self.conn.request(method, url, body, headers)
		self._relax()

	def _getResponse(self, withHeaders = False):
		self._relax()
		response = self.conn.getresponse()
		self._relax()
		data = response.read()
		self._relax()
		if withHeaders:
			return data, response.getheaders()
		return data

	def connect(self):
		if not self.conn:
			try:
				if self.tls:
					self.conn = http.client.HTTPSConnection(self.host)
				else:
					self.conn = http.client.HTTPConnection(self.host)
			except http.client.HTTPException as e:
				raise self.Error("Error while connecting to %s:\n%s" % (
					self.supplierNames[0], str(e)))

	def disconnect(self):
		if self.conn:
			try:
				self.conn.close()
			except http.client.HTTPException as e:
				pass
			self.conn = None

	def _getPrice(self, orderCode):
		raise NotImplementedError

	def getPrices(self, orderCodes,
		      preCallback=None,
		      postCallback=None):
		for orderCode in orderCodes:
			tries = 0
			while 1:
				tries += 1
				try:
					if preCallback:
						preCallback(orderCode)
					yield self._getPrice(orderCode)
					if postCallback:
						postCallback(orderCode)
				except http.client.HTTPException as e:
					if tries < 5:
						print("Price fetch %s '%s' failed. Retrying..." % (
						      self.supplierNames[0], orderCode))
						self.disconnect()
						continue
					raise self.Error("Error while processing %s '%s':\n%s" % (
						self.supplierNames[0], orderCode, str(e)))
				except self.Error as e:
					raise self.Error("Error while processing %s '%s':\n%s" % (
						self.supplierNames[0], orderCode, str(e)))
				break
bues.ch cgit interface