-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
348 lines (311 loc) · 10.9 KB
/
main.py
File metadata and controls
348 lines (311 loc) · 10.9 KB
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
import json
import os
import mysql
import mysql.connector
from bs4 import BeautifulSoup
from flask import Flask, render_template, request, redirect, url_for, session
import siteSubmission
import testingtool
import queueHandler
from flask_session import Session
app = Flask(__name__)
@app.route('/blog/<parameter_name>')
def testTool(parameter_name):
return render_template('blog.html', regdata=parameter_name.capitalize())
@app.route('/fetchData')
def fetchData():
db_connection = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
database="scrapiusdb"
)
db_cursor = db_connection.cursor(buffered=True)
query = "select Site,data from scrapeddata where user=(%s)"
db_cursor.execute(query, (session['loggedInEmail'],))
myresult = db_cursor.fetchall()
username = str(session['loggedInEmail'])
file_name = 'userbase/' + username
if not os.path.exists(file_name):
os.makedirs(file_name)
file_name = file_name + "/schema.json"
if not os.path.exists(file_name):
# Create the file if it doesn't exist
with open(file_name, 'w') as file:
file.write("{}")
with open(file_name, 'r') as file:
loadedData = json.load(file)
cr_filename = 'userbase/' + username + "/created.json"
if not os.path.exists(cr_filename):
# Create the file if it doesn't exist
with open(cr_filename, 'w') as file:
file.write("{}")
with open(cr_filename, 'r') as file:
cr_loadedData = json.load(file)
mTableData = []
for key in loadedData.keys():
mstr = ""
for mkey in loadedData[key].keys():
if mkey != "parent" :
if mstr == "":
mstr = mkey.capitalize()
else:
mstr = mstr + ", " + mkey.capitalize()
innerData = {
"site" : key,
"schema" : mstr,
"siteTotalScraped" : sum(1 for item in myresult if item[0] == key),
"created" : cr_loadedData[key]
}
mTableData.append(innerData)
mData = {
"totalScraped": len(myresult),
"lastScraped": "2m",
"totalSites": len(loadedData.keys()),
"totalView": "2.5K",
"totalSubs": "50",
"data": str(json.dumps(mTableData))
}
return f'{str(json.dumps(mData,indent=4))}'
# Edit Below
@app.route('/testing', methods=['GET','POST'])
def testing():
# print("Accessed testing")
if request.method == 'POST':
data = request.json
paramKey = request.json.keys()
sData = {}
for key in paramKey:
if key == 'url':
sData["url"] = data.get(key)
elif data.get(key) != "":
soup = BeautifulSoup(data.get(key), 'html.parser')
outerTag = soup.find()
sData[key] = {
"type": outerTag.name,
"atr": {
"id": outerTag.get('id'),
"class": outerTag.get('class')[0] if outerTag.get('class') is not None else ""
}
}
# if not attrValidator(request.form[key]):
# return f'{request.form[key]} do not contains id or class attribute.'
# else:
testScrap = testingtool.TestMyScraping(sData)
# print("reaced out of loop 1")
return str(json.dumps(testScrap.getReturnValue()))
return ""
# {
# url : {
# "parent" : {
# "type" : outerTag,
# "atr" : {
# "id" : outerTag.get('id'),
# "class" : outerTag.get('class')
# }
# },
# "heading" : {
# ....
# }
# }
# }
#
# {
# "url" : url,
# "parent" : {
# "type" : outerTag,
# "atr" : {
# "id" : outerTag.get('id'),
# "class" : outerTag.get('class')
# }
# },
# "heading" : {
# ....
# }
# }
# Edit above
@app.route('/fetchblog/<parameter_name>')
def fetchblog(parameter_name):
db_connection = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
database="scrapiusdb"
)
param = parameter_name
db_cursor = db_connection.cursor(buffered=True)
usernamequery = "select email from userbase where username=(%s) Limit 1"
db_cursor.execute(usernamequery, (param,))
umyresult = db_cursor.fetchall()
if len(umyresult) == 0:
return f'No User Found'
else:
print(umyresult[0])
query = "select data from scrapeddata where user=(%s) ORDER BY createdTime DESC"
db_cursor.execute(query, umyresult[0])
myresult = db_cursor.fetchall()
if len(myresult) == 0:
return f'No Data Found';
else:
mblogdata = []
for row in myresult:
mblogdata.append(row[0])
return f'{str(json.dumps(mblogdata))}'
@app.route('/userRegister', methods=['GET', 'POST'])
def userRegister():
if request.method == 'POST':
email = request.form['mail']
password = request.form['password']
username = request.form['username']
db_connection = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
database="scrapiusdb"
)
db_cursor = db_connection.cursor(buffered=True)
# if db_connection.is_connected():
# print('Connected to MySQL database')
query = "Select * from userbase where email=(%s) OR username=(%s) Limit 1"
db_cursor.execute(query, (email, username))
myresult = db_cursor.fetchall()
if len(myresult) == 0:
query = "Insert into userbase (name, email, password, username) values (%s, %s, %s, %s)"
db_cursor.execute(query, ('aa', email, password, username))
db_connection.commit()
session['loggedInEmail'] = email;
session['loggedInUserName'] = username
return redirect('/dashboard')
else:
param = {"isUniqueUser": "True"}
for item in myresult:
if item[1] == email:
param["isUniqueUser"] = 'False'
return redirect(url_for('/', messages=json.dumps(param)))
@app.route('/userLogin', methods=['GET', 'POST'])
def userLogin():
if request.method == 'POST':
email = request.form['mail']
password = request.form['password']
# print("Login => " + email + " " + password)
db_connection = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
database="scrapiusdb"
)
db_cursor = db_connection.cursor(buffered=True)
query = "select email,password,username from userbase"
db_cursor.execute(query)
myresult = db_cursor.fetchall()
isVerified = 0
mUsername = "";
for item in myresult:
if item[0] == email:
if item[1] == password:
isVerified = 2
mUsername = item[2]
else:
isVerified = 1
if isVerified == 2:
session['loggedInEmail'] = email
session['loggedInUserName'] = mUsername
return redirect('/dashboard')
elif isVerified == 1:
# param = [str(isVerified),str(isVerified),str(isVerified)]
return render_template('index.html', regData='Incorrect password')
else:
return render_template('index.html', regData='Email not found')
@app.route('/manageSite', methods=['GET', 'POST'])
def manageSite():
# print(session['loggedInEmail'])
# json_file = "sitedata.json"
# existing_data = []
# try:
# with open(json_file) as file:
# existing_data = json.load(file)
# except FileNotFoundError:
# pass
return render_template('newmanage.html')
def attrValidator(element1):
soup = BeautifulSoup(element1, 'html.parser')
outerTag = soup.find()
if outerTag.has_attr('class'):
if len(outerTag.get('class')) > 0:
return True
elif outerTag.has_attr('id'):
if len(outerTag.get('id')) > 0:
return True
else:
return False
@app.route('/addSite', methods=['GET', 'POST'])
def addSite():
userEmail = session['loggedInEmail']
mUrl = request.form['url']
msg = ""
paramKey = request.form.keys()
# print(str(paramKey))
if 'parent' in paramKey and not attrValidator(request.form['parent']):
msg = "Parent do not contains id or class attribute."
# elif 'heading' in paramKey and not attrValidator(request.form['heading']):
# msg = "Heading do not contains id or class attribute."
# elif 'link' in paramKey and not attrValidator(request.form['link']):
# msg = "Link do not contains id or class attribute."
# elif 'img' in paramKey and not attrValidator(request.form['img']):
# msg = "Image do not contains id or class attribute."
if msg == "":
sData = {}
for key in paramKey :
if request.form[key].strip() != "" and key != 'url':
sData[key] = request.form[key];
addSiteObj = siteSubmission.addSiteSubmission(userEmail, mUrl, sData)
return redirect('/dashboard')
else:
print(msg)
return render_template('manage.html', regData=msg)
@app.route('/dashboard', methods=['GET', 'POST'])
def dashboard():
data = {
"email": session['loggedInEmail'],
"username": session['loggedInUserName']
}
return render_template('newdash.html', my_data=data)
@app.route('/submit', methods=['GET', 'POST'])
def submit():
if request.method == 'POST':
json_file = "sitedata.json"
new_data = {
"url": request.form['siteBox'],
"schema": request.form['schemaBox']
}
existing_data = []
try:
with open(json_file) as file:
existing_data = json.load(file)
except FileNotFoundError:
pass
# Append the new dictionary to the existing data
existing_data.append(new_data)
# Write the updated data back to the JSON file
with open(json_file, "w") as file:
json.dump(existing_data, file)
return redirect('/manageSite')
@app.route('/', methods=['GET', 'POST'])
def index():
# existing_data = []
# json_file = "sitedata.json"
# try:
# with open(json_file) as file:
# existing_data = json.load(file)
# except FileNotFoundError:
# pass
# return render_template('index.html', regData=existing_data)
if session.get('loggedInEmail') is not None:
print(session['loggedInEmail'])
return render_template('index.html')
if __name__ == "__main__":
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
queueHandler.queuehandlerStarted()
app.run()