-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscraper.py
More file actions
2474 lines (2131 loc) · 72.9 KB
/
scraper.py
File metadata and controls
2474 lines (2131 loc) · 72.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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import division
import psycopg2
from datetime import datetime, timedelta
import re
from time import sleep, time, ctime
from BeautifulSoup import BeautifulSoup, SoupStrainer
import mechanize
import cookielib
from numpy.random import poisson
from random import sample, shuffle
from os import path, environ
from dateutil.relativedelta import relativedelta
from json import load
from urllib2 import urlopen
ver = '1.0'
class SQLerror(Exception):
def __init__(self, value='SQL error'):
print(value)
with open(settings.errorlog, 'ab') as errorOut:
errorOut.write(unicode(ctime()) + u' \t' + value + '\n')
class proxyerror(Exception):
def __init__(self, value='Proxy error'):
print(value)
with open(settings.errorlog, 'ab') as errorOut:
errorOut.write(unicode(ctime()) + u' \t' + value + '\n')
class DBerror(Exception):
def __init__(self, value='EB error'):
print(value)
with open(settings.errorlog, 'ab') as errorOut:
errorOut.write(unicode(ctime()) + u' \t' + value + '\n')
########################################################################
class Settings:
""""""
class settingsError(Exception):
def __init__(self, value='''Something went wrong while setting the settings.
Probably a bad dropbox path.'''):
print(value)
with open(settings.errorlog, 'ab') as errorOut:
errorOut.write(unicode(ctime()) + u' \t' + value + '\n')
#----------------------------------------------------------------------
def __init__(self):
#Defaults
self.debug = False
self.bannedIP = None
self.runlocal = False
self.runLAN = False
self.delayLambda = 4
self.scrapeUsers = False
self.scrapeMonths = False
self.scrapeLogs = False
self.fillMonths = False
self.fixInfo = False
self.onlyEven = None
self.chkFreq = 60*10
self.iterations = 0
self.ul = None
self.ll = None
self.commitFreq = 1
self.scraped = True
# machine specific variables
try:
self.dropboxPath = environ['DROPBOX_PATH']
except:
self.dropboxPath = '/home/joakim/'
self.computer = environ['COMPUTER_NAME']
if self.computer == 'kontoret': # Kontoret (users, , [0, 0])
self.scrapeUsers = True
#self.onlyEven = True
self.ll = 0
self.ul = 0
self.delayLambda = 7
elif self.computer == 'server': #Server (logs, even, [4 400 001, 4 500 000])
self.scrapeLogs = True
self.onlyEven = True
self.ll = 0
self.ul = 0
self.delayLambda = 5
elif self.computer == 'hemma': # Hemma (logs, odd, [4 100 001, 4 200 000])
self.runlocal = True
self.scrapeLogs = True
self.onlyEven = False
self.ll = 0
self.ul = 0
elif self.computer == 'toshiban': # Toshiban (logs, odd, [4 400 001, 4 500 000])
self.scrapeLogs = True
self.onlyEven = False
self.ll = 0
self.ul = 0
elif self.computer == 'litenvit': # Liten vit Garderoben (logs, even, [5 100 001, 5 200 000])
self.runLAN = True
self.scrapeLogs = True
#self.onlyEven = True
self.ll = 4100001
self.ul = 4150000
self.bannedIP = '60.241.126.187'
elif self.computer == 'garderoben': # Garderoben (logs, odd, [5 100 001, 5 200 000])
self.runLAN = True
self.scrapeLogs = True
#self.onlyEven = False
self.ll = 4150001
self.ul = 4200000
self.bannedIP = '60.241.126.187'
elif self.computer == 'monstret': # Monstret (fixinfo, , [0, 5 000 000])
self.debug = True
self.dropboxPath = '/media/joakim/Storage/Dropbox/'
self.runlocal = True
self.fixInfo = True
#self.onlyEven = False
self.ll = 0
self.ul = 5000000
#VBOXES
elif self.computer == 'vbox1': # Vbox1 (logs, , [4 500 001, 4 600 000])
self.runLAN = True
self.bannedIP = '73.170.245.33'
self.fixInfo = True
#self.onlyEven = False
self.ll = 1
self.ul = 2914445
elif self.computer == 'vbox2': # Vbox2 (logs, odd, [4 600 001, 4 700 000])
self.runLAN = True
self.bannedIP = '73.170.245.33'
self.fixInfo = True
#self.onlyEven = True
self.ll = 2914452
self.ul = 3155289
elif self.computer == 'vbox3': # Vbox3 (logs, odd, [4 000 001, 4 100 000])
self.runLAN = True
self.bannedIP = '73.170.245.33'
self.fixInfo = True
#self.onlyEven = False
self.ll = 3155421
self.ul = 3187935
elif self.computer == 'vbox4': # Vbox4 (logs, even, [4 500 001, 4 600 000])
self.runLAN = True
self.bannedIP = '73.170.245.33'
self.fixInfo = True
#self.onlyEven = True
self.ll = 3187956
self.ul = 3315796
elif self.computer == 'vbox5': # Vbox5 (logs, even, [4 600 001, 4 700 000])
self.runLAN = True
self.bannedIP = '73.170.245.33'
self.fixInfo = True
#self.onlyEven = False
self.ll = 3315817
self.ul = 4000000
elif self.computer == 'vbox6': # Vbox6 (logs, even, [4 300 001, 4 400 000])
self.runLAN = True
self.bannedIP = '60.241.126.187'
self.scrapeLogs = True
#self.onlyEven = True
self.ll = 4815001
self.ul = 5000000
elif self.computer == 'vbox7': # Vbox7 (logs, even, [4 700 001, 4 800 000])
self.runLAN = True
self.bannedIP = '60.241.126.187'
self.scrapeLogs = True
self.onlyEven = True
self.ll = 4700001
self.ul = 4800000
elif self.computer == 'vbox8': # Vbox8 (logs, even, [3 900 001, 4 000 000])
self.runLAN = True
self.bannedIP = '60.241.126.187'
self.scrapeLogs = True
self.onlyEven = True
self.ll = 3900001
self.ul = 4000000
elif self.computer == 'vbox9': # Vbox9 (logs, odd, [5 000 001, 5 100 000])
self.runLAN = True
self.bannedIP = '60.241.126.187'
self.scrapeLogs = True
self.onlyEven = False
self.ll = 5000001
self.ul = 5100000
elif self.computer == 'vbox10': # Vbox10 (logs, odd, [4 700 001, 4 800 000])
self.runLAN = True
self.bannedIP = '60.241.126.187'
self.scrapeLogs = True
self.onlyEven = False
self.ll = 4700001
self.ul = 4800000
elif self.computer == 'vbox11': # Vbox11 (logs, odd, [3 900 001, 4 000 000])
self.runLAN = True
self.bannedIP = '60.241.126.187'
self.scrapeLogs = True
self.onlyEven = False
self.ll = 3900001
self.ul = 4000000
elif self.computer == 'vbox12': # Vbox12 (logs, , [3 200 001, 3 700 000])
self.runLAN = True
self.bannedIP = '60.241.126.187'
self.scrapeLogs = True
self.ll = 3200001
self.ul = 3700000
elif self.computer == 'vbox13': # Vbox13 (logs, , [4 200 001, 4 300 000])
self.runLAN = True
self.bannedIP = '60.241.126.187'
self.scrapeLogs = True
self.ll = 4200001
self.ul = 4300000
elif self.computer == 'vbox14': # Vbox14 (logs, , [3 700 001, 3 800 000])
self.runLAN = True
self.bannedIP = '60.241.126.187'
self.scrapeLogs = True
self.ll = 3700001
self.ul = 3800000
elif self.computer == 'vbox15': # Vbox15 (logs, odd, [4 900 001, 5 000 000])
self.runLAN = True
self.bannedIP = '60.241.126.187'
self.scrapeLogs = True
self.ll = 4900001
self.ul = 5000000
elif self.computer == 'vbox16': # Vbox16 (logs, even, [4 800 001, 4 900 000])
self.bannedIP = '60.241.126.187'
self.scrapeLogs = True
self.onlyEven = True
self.ll = 4800001
self.ul = 4900000
elif self.computer == 'vbox17': # Vbox17 (logs, odd, [4 800 001, 4 900 000])
self.bannedIP = '60.241.126.187'
self.scrapeLogs = True
self.onlyEven = False
self.ll = 4800001
self.ul = 4900000
elif self.computer == 'vbox18': # Vbox18 (logs, even, [4 000 001, 4 100 000])
self.bannedIP = '60.241.126.187'
self.scrapeLogs = True
self.onlyEven = True
self.ll = 4000001
self.ul = 4100000
elif self.computer == 'vbox19': # Vbox19 (logs, odd, [4 300 001, 4 400 000])
self.bannedIP = '60.241.126.187'
self.scrapeLogs = True
self.onlyEven = True
self.onlyEven = False
self.ll = 4300001
self.ul = 4400000
elif self.computer == 'vbox20': # Vbox20 (logs, even, [5 000 001, 5 100 000])
self.bannedIP = '60.241.126.187'
self.scrapeLogs = True
self.onlyEven = True
self.ll = 5000001
self.ul = 5100000
else:
raise settingsError()
self.errorlog = self.dropboxPath + 'Data Incubator/Project/jefit/allusers/errorlogs/' + \
self.computer + datetime.ctime(datetime.now()).replace(' ', '_').replace(':','_') + '.txt'
#database connection
self.setDatabase()
def setDatabase(self):
self.dbconfig = dict()
self.dbconfig[u'database'] = u'jefit'
self.dbconfig[u'user'] = environ['PG_USER']
self.dbconfig[u'password'] = environ['PG_PASS']
self.dbconfig[u'port'] = 5432
if self.runlocal:
self.dbconfig[u'host'] = 'localhost'
elif self.runLAN:
self.dbconfig[u'host'] = u'192.168.0.12'
else:
self.dbconfig[u'host'] = u'60.241.126.187'
self.herokuconfig = dict()
self.herokuconfig[u'host'] = 'ec2-52-71-87-235.compute-1.amazonaws.com'
self.herokuconfig[u'database'] = u'd9dhhg5l7t9cd1'
self.herokuconfig[u'user'] = environ['HEROKU_USER']
self.herokuconfig[u'password'] = environ['HEROKU_PASS']
self.herokuconfig[u'port'] = 5432
# get local settings
settings = Settings()
class database:
""""""
#----------------------------------------------------------------------
def __init__(self, dbconfig, connect=True):
self.dbconfig = dbconfig
self.connected = False
self.alivechk = datetime.now() - timedelta(minutes=30)
self.debug = settings.debug
if connect:
self.connect()
#connect to database
def connect(self):
config = dict()
self.con = psycopg2.connect("dbname={0} user={1} password={2} host={3} port={4}".format(
self.dbconfig[u'database'],
self.dbconfig[u'user'],
self.dbconfig[u'password'],
self.dbconfig[u'host'],
self.dbconfig[u'port']))
self.cur = self.con.cursor()
self.connected = True
#disconnect
def close(self):
if self.con.closed == 0:
self.con.close()
self.connected = False
#make column name safe for database
def safeName(self, x):
y = unicode(x).lower()
y = y.replace(u'\xc5', 'a')
y = y.replace(u'\xc4', 'a')
y = y.replace(u'\xd6', 'o')
y = y.replace(u'\xe5', 'a')
y = y.replace(u'\xe4', 'a')
y = y.replace(u'\xf6', 'o')
y = y.replace(u'\xb5', 'u')
for cr in y:
crN = ord(cr)
if (crN < 97 or crN > 122) and (crN < 48 or crN > 57) and crN != 95:
y = y.replace(cr, u'_')
return y
#make string value safe for database (by escaping apostrophes)
def safeVal(self, x):
if not (isinstance(x, str) or isinstance(x, unicode)):
return x
else:
return x.replace("'", "''")
#insert table
def insertTable(self, table, cols_types_defaults, pkey=0, debug=settings.debug, showError=True):
class Dummy:
def execute(self):
colStr = u''
for n, var in enumerate(self.cols_types_defaults):
var = list(var)
colStr = colStr + var[0] + ' ' + var[1] + ' PRIMARY KEY'*(n==self.pkey)
if len(var) == 3:
colStr = colStr + ' DEFAULT ' + str(var[2])
colStr = colStr + ', '
colStr = colStr.strip(', ')
sql = 'CREATE TABLE {0} ({1})'.format(self.table, colStr)
self.cur.execute(sql)
self.con.commit()
return True
dummy = Dummy()
dummy.table = table
dummy.cols_types_defaults = cols_types_defaults
dummy.pkey = pkey
dummy.con = self.con
dummy.cur = self.cur
if not debug:
return self.timeoutHandler(dummy)
else:
return dummy.execute()
#insert column
def insertColumn(self, table, col, varType = 'TEXT', default = u'', debug=settings.debug):
class Dummy:
def execute(self):
if self.col != self.safeName(self.col):
raise DBerror('Tried to insert unsafe column name')
if self.default != u'':
self.default = u' DEFAULT ' + self.default
self.cur.execute('ALTER TABLE {0} ADD COLUMN {1} {2} {3}'.format(
self.table,
self.col,
self.varType,
self.default))
self.con.commit()
return True
dummy = Dummy()
dummy.table = table
dummy.col = col
dummy.varType = varType
dummy.default = default
dummy.safeName = self.safeName
dummy.con = self.con
dummy.cur = self.cur
if not debug:
return self.timeoutHandler(dummy)
else:
return dummy.execute()
#get existing column names
def getColumns(self, thisTable, thisScema = None, debug = settings.debug):
class Dummy:
def execute(self):
self.cur.execute(
"select column_name from information_schema.columns where table_name = '{0}';".format(
self.thisTable)
)
dmp = self.cur.fetchall()
y = []
for d in dmp:
y.append(d[0])
return y
dummy = Dummy()
dummy.thisTable = thisTable
dummy.thisScema = thisScema
dummy.con = self.con
dummy.cur = self.cur
if not debug:
return self.timeoutHandler(dummy)
else:
return dummy.execute()
#update field in database
def updateField(self, thisTable, changeVar, newVal, selVar, targetVal, debug=settings.debug, commit=True):
class Dummy:
def execute(self):
newVal = unicode(self.newVal)
if isinstance(newVal, bool):
newVal = unicode(newVal)
if isinstance(self.targetVal, int) or isinstance(self.targetVal, float):
self.cur.execute("UPDATE {0} SET {1} = '{2}' WHERE {3} = {4}".format(
self.thisTable,
self.changeVar,
newVal,
self.selVar,
unicode(self.targetVal)))
if self.commit:
self.con.commit()
else:
self.cur.execute("UPDATE {0} SET {1} = '{2}' WHERE {3} = '{4}'".format(
self.thisTable,
self.changeVar,
self.safeVal(newVal),
self.selVar,
self.targetVal))
if self.commit:
self.con.commit()
return True
dummy = Dummy()
dummy.thisTable = thisTable
dummy.changeVar = changeVar
dummy.newVal = newVal
dummy.selVar = selVar
dummy.targetVal = targetVal
dummy.safeVal = self.safeVal
dummy.commit = commit
dummy.con = self.con
dummy.cur = self.cur
if not debug:
return self.timeoutHandler(dummy)
else:
return dummy.execute()
#write to database
def write2db(self, thisDic, thisTable, useTimeStamp = True, insertKeys=False, debug=settings.debug, commit=True):
class Dummy:
def execute(self):
def makeUnicode(val):
if type(val) != unicode:
try:
val = val.decode('utf-8')
except:
try:
val = unicode(val)
except:
pass
return(val)
Keys = self.thisDic.keys()
for k in Keys:
if k != self.safeName(k):
raise SQLerror('Tried to insert unsafe column name ' + k)
if self.insertKeys:
self.insertColumn(self.thisTable, k, 'TEXT')
cols = self.getColumns(self.thisTable)
if self.useTimeStamp:
if u'db_timestamp' not in cols:
self.insertColumn(self.thisTable, u'db_timestamp', varType = 'TIMESTAMP')
self.thisDic[u'db_timestamp'] = 'now'
Keys = thisDic.keys()
Ss = u''
keyStr = u''
inserts = []
for key in Keys:
if self.thisDic[key] != u'null' and self.thisDic[key] is not None:
inserts.append(self.safeVal(self.thisDic[key]))
Ss = Ss + u',%s'
keyStr = keyStr + u',' + key
self.cur.execute(u'INSERT INTO {0} ({1}) VALUES ({2})'.format(
self.thisTable,
keyStr.strip(u','),
Ss.strip(u',')
), tuple(inserts))
if self.commit:
self.con.commit()
return True
dummy = Dummy()
dummy.thisTable = thisTable
dummy.thisDic = thisDic
dummy.useTimeStamp = useTimeStamp
dummy.insertKeys = insertKeys
dummy.safeName = self.safeName
dummy.insertColumn = self.insertColumn
dummy.con = self.con
dummy.cur = self.cur
dummy.getColumns = self.getColumns
dummy.safeVal = self.safeVal
dummy.commit = commit
if not debug:
return self.timeoutHandler(dummy)
else:
return dummy.execute()
def listCols(self, thisTable, debug=settings.debug):
class Dummy:
def execute(self):
self.cur.execute("SELECT * FROM " + self.thisTable + " LIMIT 1")
res = [desc[0] for desc in self.cur.description]
return(res)
dummy = Dummy()
dummy.thisTable = thisTable
dummy.cur = self.cur
if not debug:
return self.timeoutHandler(dummy)
else:
return dummy.execute()
def listTables(self, schema = 'public', debug=settings.debug):
class Dummy:
def execute(self):
self.cur.execute("SELECT table_name FROM information_schema.tables WHERE table_type = 'BASE TABLE' AND table_schema = '{0}'".format(self.schema))
dmp = self.cur.fetchall()
res = []
for d in dmp:
res.append(d[0])
return(res)
dummy = Dummy()
dummy.schema = schema
dummy.cur = self.cur
if not debug:
return self.timeoutHandler(dummy)
else:
return dummy.execute()
#drop table
def dropTable(self, table, debug=settings.debug):
class Dummy:
def execute(self):
self.cur.execute(u'DROP TABLE {0}'.format(self.table))
self.con.commit()
return True
dummy = Dummy()
dummy.table = table
dummy.con = self.con
dummy.cur = self.cur
if not debug:
return self.timeoutHandler(dummy)
else:
return dummy.execute()
# insert list of tuples in table
def insertMany(self, table, cols, values, debug=settings.debug, commit=True):
class Dummy:
def execute(self):
if len(self.values) == 0:
return False
ss = ','.join(['%s'] * len(self.values))
cs = ','.join(self.cols)
insert_query = 'insert into {0} ({1}) values {2}'.format(self.table, cs, ss)
self.cur.execute(insert_query, values)
if self.commit:
self.con.commit()
return True
dummy = Dummy()
dummy.table = table
dummy.cols = cols
dummy.values = values
dummy.con = self.con
dummy.cur = self.cur
dummy.commit = commit
if not debug:
return self.timeoutHandler(dummy)
else:
return dummy.execute()
#Read column values
def getValues(self, thisCol, thisTable, unique = False, sels = [], debug=settings.debug, limit=None):
class Dummy:
def execute(self):
def listMe(x):
if isinstance(x, list) or isinstance(x, tuple):
return(x)
else:
return([x])
selStr = 'WHERE '*(len(self.sels) > 0)
for i, sel in enumerate(listMe(self.sels)):
isString = (isinstance(sel[2], str) or isinstance(sel[2], unicode))
selStr = selStr + "{0} {1} {2}{3}{4} {5}".format(
sel[0],
sel[1],
"'"*isString,
str(sel[2]) if sel[2] is not None else 'Null',
"'"*isString,
' AND '*(i<len(self.sels)-1))
self.thisCol = listMe(self.thisCol)
ncols = len(self.thisCol)
if ncols > 1:
self.thisCol = ', '.join(self.thisCol)
else:
self.thisCol = self.thisCol[0]
sql = 'SELECT {0} {1} FROM {2} {3} {4}'.format(
'DISTINCT'*unique,
self.thisCol,
self.thisTable,
selStr,
(' limit ' + str(limit))*(limit is not None))
self.cur.execute(sql)
x = self.cur.fetchall()
if ncols == 1:
y = []
for xi in x:
y.append(xi[0])
if len(y) == 1:
return y[0]
else:
return(y)
else:
if len(x) == 1:
return x[0]
else:
return(x)
dummy = Dummy()
dummy.thisCol = thisCol
dummy.thisTable = thisTable
dummy.unique = unique
dummy.sels = sels
dummy.con = self.con
dummy.cur = self.cur
if not debug:
return self.timeoutHandler(dummy)
else:
return dummy.execute()
def fillChk(self, ll, ul, lim, debug=settings.debug):
class Dummy:
def execute(self):
sql = '''SELECT userid from {0} WHERE
public = TRUE AND scraped = TRUE AND filled = FALSE
AND userid in
(SELECT DISTINCT userid_id FROM {1} WHERE
userid_id > {2} AND userid_id < {3})
LIMIT {4}'''.format(self.usertable, self.logtable, self.ll, self.ul, self.lim)
self.cur.execute(sql)
dmp = self.cur.fetchall()
return [x[0] for x in dmp]
dummy = Dummy()
dummy.con = self.con
dummy.cur = self.cur
dummy.usertable = tables.users
dummy.logtable = tables.logs
dummy.ll = ll
dummy.ul = ul
dummy.lim = lim
if not debug:
return self.timeoutHandler(dummy)
else:
return dummy.execute()
def getSubset(self, thisCol, thisTable, sels=[], unique=False, limit=None, ul=None, ll=None,
onlyEven=None, limvar=None, debug=settings.debug):
if limvar is None:
if isinstance(thisCol, list) or isinstance(thisCol, tuple):
limvar = thisCol[0]
else:
limvar = thisCol
if ul is not None:
sels.append((limvar, '<=', ul))
if ll is not None:
sels.append((limvar, '>=', ll))
if onlyEven is not None:
sels.append(('mod({0},2)'.format(limvar), '=', 1-onlyEven))
return self.getValues(thisCol, thisTable, unique=unique, sels=sels, debug=debug, limit=limit)
def updateMany(self, thisTable, changeVars, newVals, selVar, targetVal, debug=settings.debug):
class Dummy:
def execute(self):
def listMe(x):
if not (isinstance(x, list) or isinstance(x, tuple)):
x = [x]
return x
self.changeVars = listMe(self.changeVars)
self.newVals = listMe(self.newVals)
changes = ''
for var, val in zip(self.changeVars, self.newVals):
q = '' + "'"*(isinstance(val, str) or isinstance(val, unicode))
changes = "{0}{1} = {2}{3}{4}, ".format(changes, var, q, str(val), q)
changes = changes.strip(', ')
q = '' + "'"*(isinstance(self.targetVal, str) or isinstance(self.targetVal, unicode))
self.cur.execute("UPDATE {0} SET {1} WHERE {2} = {3}{4}{5}".format(
self.thisTable,
changes,
self.selVar,
q,
str(self.targetVal),
q))
self.con.commit()
return True
dummy = Dummy()
dummy.thisTable = thisTable
dummy.changeVars = changeVars
dummy.newVals = newVals
dummy.selVar = selVar
dummy.targetVal = targetVal
dummy.safeVal = self.safeVal
dummy.con = self.con
dummy.cur = self.cur
if not debug:
return self.timeoutHandler(dummy)
else:
return dummy.execute()
#kill user when weird jefit movement happens
def killUser(self, user, debug=settings.debug):
class Dummy:
def execute(self):
# --DELETE SETS
sql = '''DELETE FROM scrape_sets WHERE exid_id IN
(SELECT exid FROM scrape_exercises WHERE logid_id in
(SELECT logid FROM scrape_logs WHERE userid_id={0}))'''.format(str(self.user))
self.cur.execute(sql)
#--DELETE LOGS
sql = '''DELETE FROM scrape_bodystats WHERE logid_id in
(SELECT logid FROM scrape_logs WHERE userid_id={0})'''.format(str(self.user))
self.cur.execute(sql)
sql = '''DELETE FROM scrape_exercises WHERE logid_id in
(SELECT logid FROM scrape_logs WHERE userid_id={0})'''.format(str(self.user))
self.cur.execute(sql)
sql = '''DELETE FROM scrape_logsummary WHERE logid_id in
(SELECT logid FROM scrape_logs WHERE userid_id={0})'''.format(str(self.user))
self.cur.execute(sql)
sql = '''DELETE FROM scrape_notes WHERE logid_id in
(SELECT logid FROM scrape_logs WHERE userid_id={0})'''.format(str(self.user))
self.cur.execute(sql)
sql = 'DELETE FROM scrape_logs WHERE userid_id={0}'.format(str(self.user))
self.cur.execute(sql)
#--DELETE USER
sql = 'DELETE FROM scrape_months WHERE userid_id={0}'.format(str(self.user))
self.cur.execute(sql)
sql = 'DELETE FROM scrape_userinfo WHERE userid_id={0}'.format(str(self.user))
self.cur.execute(sql)
sql = 'DELETE FROM scrape_months WHERE userid_id={0}'.format(str(self.user))
self.cur.execute(sql)
sql = 'UPDATE scrape_users SET scraped = FALSE WHERE userid={0}'.format(str(self.user))
self.cur.execute(sql)
self.con.commit()
return True
dummy = Dummy()
dummy.user = user
dummy.con = self.con
dummy.cur = self.cur
if not debug:
return self.timeoutHandler(dummy)
else:
return dummy.execute()
#tell the database that you're alive
def imStillAlive(self, debug=settings.debug):
class Dummy:
def execute(self):
computers = heroku.getValues('computer_name', 'monitor_computer')
if settings.computer not in computers:
self.write2db(
{
'computer_name':settings.computer,
'ip':br.ip,
'activity':'now',
'email_sent':True,
'speed':0
},
'monitor_computer',
useTimeStamp=False)
else:
br.getIP()
self.updateMany('monitor_computer',
['activity', 'ip', 'speed'],
['now', br.ip, self.speed],
'computer_name',
settings.computer)
return True
settings.iterations = settings.iterations + 1
if (datetime.now() - self.alivechk).total_seconds() > settings.chkFreq:
heroku.connect()
dummy = Dummy()
dummy.speed = round(60*settings.iterations/(datetime.now() - self.alivechk).total_seconds(),2)
settings.iterations = 0
self.alivechk = datetime.now()
dummy.updateField = self.updateField
dummy.updateMany = self.updateMany
dummy.write2db = self.write2db
if not debug:
return self.timeoutHandler(dummy)
else:
return dummy.execute()
heroku.close()
def timeoutHandler(self, obj):
n = 0
while (n < 11):
n = n + 1
try:
if (self.con.closed > 0):
self.connect()
obj.con = self.con
obj.cur = self.cur
return obj.execute()
except Exception as e:
print('Database error:\t{0}').format(str(e))
with open(settings.errorlog, 'ab') as errorOut:
errorOut.write(','.join((ctime(),str(e))))
try:
self.con.rollback()
except:
pass
try:
self.close()
except:
pass
print('Iteration {0}. Sleeping for 1 minute.'.format(str(n)))
sleep(60)
try:
try:
self.close()
except:
pass
self.connect()
except:
pass
##custom exception for moved logs
#try:
#e1 = str(e).split('\n')[0]
#if e1 == 'duplicate key value violates unique constraint "scraper_exercises_pkey"' or e1 == 'insert or update on table "scrape_exercises" violates foreign key constraint "logid_id_fkey"':
#n = 12
#except:
#pass
##custom exception for moved logs
#try:
#e1 = str(e).split('\n')[0]
#if e1 == 'duplicate key value violates unique constraint "scraper_exercises_pkey"':
#db.killUser(user=user)
#return False
#if e1 == 'insert or update on table "scrape_exercises" violates foreign key constraint "logid_id_fkey"':
#return False
#except:
#pass
raise DBerror('Fatal database error.')
def setNoteCounter(self):
dmp = self.getValues('noteid', tables.notes)
n = max(dmp)
n = n + 1
if settings.onlyEven and (n&1 == 1):
n = n + 1
if settings.onlyEven == False and (n&1 == 0):
n = n + 1
settings.note_inc = n
#This guy queues up users
class userqueue:
""""""
#----------------------------------------------------------------------
def __init__(self, k=20000, maxids=4000000, ll=settings.ll, ul=settings.ul, onlyEven=settings.onlyEven):
# get users already in list
self.ll = ll
self.ul = ul
self.onlyEven = onlyEven
sels = [('userid', '>', -1)]
if ll is not None:
sels.append(('userid', '>', ll-1))
if ul is not None:
sels.append(('userid', '<', ul+1))
if onlyEven is not None:
sels.append(('mod(userid,2)', '=', 1-int(onlyEven)))
self.done = set(db.getValues('userid', tables.users, sels=sels))
self.queue = []
self.k = k
self.maxids = maxids
def __call__(self):
return self.queue
def len(self):
return len(self.queue)
def pop(self, n=-1):
try:
return self.queue.pop(n)
except:
if isinstance(self.queue, tuple) and len(self.queue) == 2:
x = self.queue[:]
self.queue = []
return(x)
raise TypeError('Cannot pop')
def isempty(self):
if self.len() == 0:
return True
else:
return False
#def keepEven(self, x, reverse = None, ul=None, ll=None):
#if reverse is None:
#return x
#else:
#y = []
#for xi in x:
#if (xi & 1) and (reverse is True): #odd and looking for odd
#if ul is not None and xi < ul and ll is not None and xi >= ll:
#y.append(xi)
#elif not (xi & 1) and not reverse: #even and looking for even
#if ul is not None and xi < ul and ll is not None and xi >= ll:
#y.append(xi)
#return y
def keepEven(self, x, even = None, ul=None, ll=None):
if even is None:
return x
y = []
for n in x:
if ((n&1)-even) != 0 and n > ll and n < ul:
y.append(n)
return(y)
def addFriends(self, friends, even=None, ul=settings.ul, ll=settings.ll):