forked from walmat/Off-White-Monitor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ow.py
329 lines (272 loc) · 10.2 KB
/
ow.py
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
import requests
import json
from bs4 import BeautifulSoup as soup
from log import log as log
import time
from datetime import datetime
import random
import sqlite3
from discord_hooks import Webhook
import slackweb
from threading import Thread
import urllib.request
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3107.4 Safari/537.36'
headers = {}
headers['User-Agent'] = user_agent
headers['Content-Type'] = 'application/json'
class Product():
def __init__(self, title, link, stock, keyword, image_url, stock_options):
self.title = title
self.stock = stock
self.link = link
self.keyword = keyword
self.image_url = image_url
self.stock_options = stock_options
def read_from_txt(path):
# Initialize variables
raw_lines = []
lines = []
# Load data from the txt file
try:
f = open(path, "r")
raw_lines = f.readlines()
f.close()
# Raise an error if the file couldn't be found
except:
log('e', "Couldn't locate: " + path)
raise FileNotFound()
if(len(raw_lines) == 0):
log('w', "No data found in: " + path)
raise NoDataLoaded()
# Parse the data
for line in raw_lines:
lines.append(line.strip("\n"))
# Return the data
return lines
def add_to_db(product):
# Initialize variables
title = product.title
stock = str(product.stock)
link = product.link
keyword = product.keyword
alert = False
# log('i', stock)
# Create database
conn = sqlite3.connect('products.db')
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS products(title TEXT, link TEXT UNIQUE, stock TEXT, keywords TEXT)""")
# Add product to database if it's unique
try:
c.execute("""INSERT INTO products (title, link, stock, keywords) VALUES (?, ?, ?, ?)""", (title, link, stock, keyword))
log('s', "Found new product with keyword " + keyword + ". Link = " + link)
alert = True
except:
# Product already exists, let's check for stock updates
try:
# this is messy as fuck and I'm sorry.. :(
d = (link,)
c.execute('SELECT (stock) FROM products WHERE link=?', d)
old_stock = c.fetchone()
stock_str = str(old_stock)[2:-3]
if str(stock_str).strip() == str(product.stock).strip():
log('w', "Product at URL: " + link + " already exists in the database.")
pass
else:
# update table for that product with new stock
log('s', "Product at URL: " + link + " changed stock.")
c.execute("""UPDATE products SET stock = ? WHERE link= ?""", (stock_str, link))
alert = True
except sqlite3.Error as e:
log('e', "database error: " + str(e))
# Close connection to the database
conn.commit()
c.close()
conn.close()
# Return whether or not it's a new product
return alert
def notify(product, slack, discord):
times = []
today = datetime.now()
times.append(today)
sizes = ""
for size in product.stock_options:
sizes+= (size + " ")
if slack:
sc = slackweb.Slack(url=slack)
attachments = []
attachment = {
"title": product.title,
"color":"#EAF4EC",
"text": product.link,
"fields": [
{
"title": "Sizes",
"value": sizes,
"short": False
}
],
"mrkdwn_in": ["text"],
"thumb_url": product.image_url,
"footer": "BBGR",
"footer_icon": "https://platform.slack-edge.com/img/default_application_icon.png",
"ts": time.time()
}
attachments.append(attachment)
sc.notify(attachments=attachments)
if discord:
embed = Webhook(discord, color=0xEAF4EC)
embed.set_title(title=product.title, url=product.link)
embed.set_thumbnail(url=product.image_url)
embed.add_field(name="Sizes", value=sizes)
embed.set_footer(text='BBGR', icon='https://cdn.discordapp.com/embed/avatars/0.png', ts=True)
embed.post()
def monitor(link, keywords, slack, discord):
log('i', "Checking site: " + link + "...")
isEarlyLink = False
links = []
pages = []
# Parse the site from the link
pos_https = link.find("https://")
pos_http = link.find("https://")
pos_omia = link.find('omia')
if(pos_https == 0):
site = link[8:]
end = site.find("/")
if(end != -1):
site = site[:end]
site = "https://" + site
else:
site = link[7:]
end = site.find("/")
if(end != -1):
site = site[:end]
site = "https://" + site
if pos_omia > 0:
isEarlyLink = True
# build search links
if (link.endswith('=')):
for word in keywords:
links.append(link + word)
else:
links.append(link)
for l in links:
# go ahead and make the request
if isEarlyLink:
# parse the page to collect data
stock_data = []
try:
r = requests.get(l+"?admin=True", timeout=5, verify=False)
except:
log('e', 'Connection to URL: ' + l + " failed. Retrying...")
time.sleep(5)
try:
r.requests.get(l+"?admin=True", timeout=8, verify=False)
except:
log('e', 'Connection to URL: ' + l + " failed.")
return
if r.status_code == 404:
log('e', "Unable to parse that link..")
page = soup(r.text, "html.parser")
product = page.findAll('article', class_='product')
title = page.findAll('span', class_='prod-title')[0].text.strip()
image= page.findAll('img', class_="js-scroll-gallery-snap-target")
# paddings
if not image:
image = "N/A"
if not title:
title: "N/A"
# get the data
url = (l+".json"+"?admin=True")
req = urllib.request.Request(url, headers=headers)
resp = urllib.request.urlopen(req).read()
size_opts = json.loads(resp.decode('utf-8'))['available_sizes']
# parse through the list
if not size_opts:
stock_data.append('Unavailable')
else:
for size in size_opts:
stock_data.append(size['name'])
product = Product(title, l, stock_data, "N/A", str(image), stock_data)
alert = add_to_db(product)
if alert:
notify(product, slack, discord)
# let's do some magic to see if it's a valid link
else:
try:
r = requests.get(l, timeout=5, verify=False)
pages.append(r)
except:
log('e', 'Connection to URL: ' + l + " failed. Retrying...")
time.sleep(5)
try:
r.requests.get(l, timeout=8, verify=False)
pages.append(r)
except:
log('e', 'Connection to URL: ' + l + " failed.")
return
for p in pages:
page = soup(p.text, "html.parser")
hrefs = []
raw_links = page.findAll("article", class_="product")
captions = page.findAll("div", class_='brand-name')
images = page.findAll('img', class_='top')
for raw_link in raw_links:
link = raw_link.find('a', attrs={"itemprop": "url"})
try:
hrefs.append(link["href"])
except:
pass
index = 0
for href in hrefs:
found = False
if len(keywords) > 0:
for keyword in keywords:
if keyword.upper() in captions[index].text.upper():
found = True
stock_data = []
url = (site+hrefs[index]+'.json')
req = urllib.request.Request(url, headers=headers)
resp = urllib.request.urlopen(req).read()
size_opts = json.loads(resp.decode('utf-8'))['available_sizes']
# parse through the list
if not size_opts:
stock_data.append('Unavailable')
else:
for size in size_opts:
stock_data.append(size['name'])
product = Product(captions[index].text, (site + hrefs[index]), stock_data, keyword, str(images[index]['src']), stock_data)
alert = add_to_db(product)
if alert:
notify(product, slack, discord)
index = index + 1
def __main__():
# Ignore insecure messages (for now)
requests.packages.urllib3.disable_warnings()
with open('config.json') as config:
j = json.load(config)
######### CHANGE THESE #########
# KEYWORDS: (seperated by -) #
keywords = [ #
"converse",
"UNC",
"Jordan",
"Mercurial",
"Zoom-Fly",
"Nike"
]
slack = j['slack']
discord = j['discord']
# Load sites from file
sites = read_from_txt("ow-pages.txt")
# Start monitoring sites
while(True):
threads = []
for site in sites:
# skip over blank lines and shit
if not site.strip():
pass
else :
t = Thread(target=monitor, args=(site, keywords, slack, discord))
threads.append(t)
t.start()
time.sleep(2)