-
Notifications
You must be signed in to change notification settings - Fork 254
/
PixivDBManager.py
1746 lines (1590 loc) · 67.1 KB
/
PixivDBManager.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
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
#!C:/Python37-32/python
# -*- coding: utf-8 -*-
import codecs
import os
import re
import sqlite3
import sys
from datetime import datetime
# import colorama
from colorama import Back, Fore, Style
import PixivHelper
from PixivListItem import PixivListItem
from PixivException import PixivException
script_path = PixivHelper.module_path()
class PixivDBManager(object):
"""Pixiv Database Manager"""
rootDirectory = "."
def __init__(self, root_directory, target='', timeout=5 * 60):
if target is None or len(target) == 0:
target = script_path + os.sep + "db.sqlite"
PixivHelper.print_and_log(
'info', "Using default DB Path: " + target)
else:
PixivHelper.print_and_log(
'info', "Using custom DB Path: " + target)
self.rootDirectory = root_directory
self.conn = sqlite3.connect(target, timeout)
def close(self):
self.conn.close()
##########################################
# I. Create/Drop Database #
##########################################
def createDatabase(self):
print('Creating database...', end=' ')
try:
c = self.conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS pixiv_master_member (
member_id INTEGER PRIMARY KEY ON CONFLICT IGNORE,
name TEXT,
save_folder TEXT,
created_date DATE,
last_update_date DATE,
last_image INTEGER
)''')
self.conn.commit()
# add column isDeleted
# 0 = false, 1 = true
try:
c.execute(
'''ALTER TABLE pixiv_master_member ADD COLUMN is_deleted INTEGER DEFAULT 0''')
self.conn.commit()
except BaseException:
pass
# add column for artist token
try:
c.execute(
'''ALTER TABLE pixiv_master_member ADD COLUMN member_token TEXT''')
self.conn.commit()
except BaseException:
pass
c.execute('''CREATE TABLE IF NOT EXISTS pixiv_master_image (
image_id INTEGER PRIMARY KEY,
member_id INTEGER,
title TEXT,
save_name TEXT,
created_date DATE,
last_update_date DATE
)''')
# add column isManga
try:
c.execute(
'''ALTER TABLE pixiv_master_image ADD COLUMN is_manga TEXT''')
except BaseException:
pass
# add column caption
try:
c.execute(
'''ALTER TABLE pixiv_master_image ADD COLUMN caption TEXT''')
except BaseException:
pass
c.execute('''CREATE TABLE IF NOT EXISTS pixiv_manga_image (
image_id INTEGER,
page INTEGER,
save_name TEXT,
created_date DATE,
last_update_date DATE,
PRIMARY KEY (image_id, page)
)''')
self.conn.commit()
# Pixiv Tags
c.execute('''CREATE TABLE IF NOT EXISTS pixiv_master_tag (
tag_id VARCHAR(255) PRIMARY KEY,
created_date DATE,
last_update_date DATE
)''')
c.execute('''CREATE TABLE IF NOT EXISTS pixiv_tag_translation (
tag_id VARCHAR(255) REFERENCES pixiv_master_tag(tag_id),
translation_type VARCHAR(255),
translation VARCHAR(255),
created_date DATE,
last_update_date DATE,
PRIMARY KEY (tag_id, translation_type)
)''')
c.execute('''CREATE TABLE IF NOT EXISTS pixiv_image_to_tag (
image_id INTEGER REFERENCES pixiv_master_image(image_id),
tag_id VARCHAR(255) REFERENCES pixiv_master_tag(tag_id),
created_date DATE,
last_update_date DATE,
PRIMARY KEY (image_id, tag_id)
)''')
self.conn.commit()
# FANBOX
c.execute('''CREATE TABLE IF NOT EXISTS fanbox_master_post (
member_id INTEGER,
post_id INTEGER PRIMARY KEY ON CONFLICT IGNORE,
title TEXT,
fee_required INTEGER,
published_date DATE,
updated_date DATE,
post_type TEXT,
last_update_date DATE
)''')
c.execute('''CREATE TABLE IF NOT EXISTS fanbox_post_image (
post_id INTEGER,
page INTEGER,
save_name TEXT,
created_date DATE,
last_update_date DATE,
PRIMARY KEY (post_id, page)
)''')
self.conn.commit()
# Sketch
c.execute('''CREATE TABLE IF NOT EXISTS sketch_master_post (
member_id INTEGER,
post_id INTEGER PRIMARY KEY ON CONFLICT IGNORE,
title TEXT,
published_date DATE,
updated_date DATE,
post_type TEXT,
last_update_date DATE
)''')
c.execute('''CREATE TABLE IF NOT EXISTS sketch_post_image (
post_id INTEGER,
page INTEGER,
save_name TEXT,
created_date DATE,
last_update_date DATE,
PRIMARY KEY (post_id, page)
)''')
# Novel
self.create_update_novel_table(c)
self.conn.commit()
print('done.')
except BaseException:
print('Error at createDatabase():', str(sys.exc_info()))
print('failed.')
raise
finally:
c.close()
def dropDatabase(self):
try:
c = self.conn.cursor()
c.execute('''DROP TABLE IF EXISTS pixiv_image_to_tag''')
c.execute('''DROP TABLE IF EXISTS pixiv_tag_translation''')
c.execute('''DROP TABLE IF EXISTS pixiv_master_tag''')
self.conn.commit()
c.execute('''DROP TABLE IF EXISTS pixiv_master_member''')
self.conn.commit()
c.execute('''DROP TABLE IF EXISTS pixiv_master_image''')
self.conn.commit()
c.execute('''DROP TABLE IF EXISTS pixiv_manga_image''')
self.conn.commit()
c.execute('''DROP TABLE IF EXISTS fanbox_master_post''')
c.execute('''DROP TABLE IF EXISTS fanbox_post_image''')
self.conn.commit()
c.execute('''DROP TABLE IF EXISTS sketch_master_post''')
c.execute('''DROP TABLE IF EXISTS sketch_post_image''')
self.conn.commit()
except BaseException:
print('Error at dropDatabase():', str(sys.exc_info()))
print('failed.')
raise
finally:
c.close()
print('done.')
def compactDatabase(self):
print('Compacting Database, this might take a while...')
try:
c = self.conn.cursor()
c.execute('''VACUUM''')
self.conn.commit()
except BaseException:
print('Error at compactDatabase():', str(sys.exc_info()))
raise
finally:
c.close()
print('done.')
##########################################
# II. Export/Import DB #
##########################################
def importList(self, listTxt):
print('Importing list...', end=' ')
print('Found', len(listTxt), 'items', end=' ')
try:
c = self.conn.cursor()
for item in listTxt:
c.execute('''INSERT OR IGNORE INTO pixiv_master_member VALUES(?, ?, ?, datetime('now'), '1-1-1', -1, 0, '')''',
(item.memberId, str(item.memberId), r'N\A'))
c.execute('''UPDATE pixiv_master_member
SET save_folder = ?
WHERE member_id = ? ''',
(item.path, item.memberId))
self.conn.commit()
except BaseException:
print('Error at importList():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
print('done.')
return 0
def exportImageTable(self, name):
print(f'Exporting {name} table ...', end=' ')
im_list = list()
if name == "Pixiv":
table = "pixiv_master_image"
key = "image_id"
elif name == "Fanbox":
table = "fanbox_master_post"
key = "post_id"
elif name == "Sketch":
table = "sketch_master_post"
key = "post_id"
else:
raise
try:
c = self.conn.cursor()
c.execute(f''' SELECT COUNT(*) FROM {table}''')
result = c.fetchall()
if result[0][0] > 10000:
print('Row count is more than 10000 (actual row count:',
str(result[0][0]), ')')
print('It may take a while to retrieve the data.')
arg = input('Continue [y/n, default is yes]').rstrip("\r") or 'y'
answer = arg.lower()
if answer not in ('y', 'n', 'o'):
PixivHelper.print_and_log("error", f"Invalid args for TODO: {arg}, valid values are [y/n/o].")
return
if answer == 'y':
c = self.conn.cursor()
c.execute(f'''SELECT {key}
FROM {table}
ORDER BY member_id''')
for row in c:
im_list.append(row[0])
else:
c.execute(f'''SELECT {key}
FROM {table}
ORDER BY member_id''')
for row in c:
im_list.append(row[0])
c.close()
print('done.')
return im_list
except BaseException:
print('Error at exportImageTable():', str(sys.exc_info()))
print('failed')
raise
def exportList(self, filename, include_artist_token=True):
print('Exporting list...', end=' ')
try:
c = self.conn.cursor()
c.execute('''SELECT member_id, save_folder, name, member_token
FROM pixiv_master_member
WHERE is_deleted = 0
ORDER BY member_id''')
if not filename.endswith(".txt"):
filename = filename + '.txt'
writer = codecs.open(filename, 'wb', encoding='utf-8')
writer.write('###Export date: {0} ###\r\n'.format(datetime.today()))
for row in c:
if include_artist_token:
data = row[2]
token = row[3]
writer.write(f"# name: {data},token: {token}")
writer.write("\r\n")
writer.write(str(row[0]))
if len(row[1]) > 0:
writer.write(' ' + str(row[1]))
writer.write('\r\n')
writer.write('###END-OF-FILE###')
except BaseException:
print('Error at exportList():', str(sys.exc_info()))
print('failed')
raise
finally:
if writer is not None:
writer.close()
c.close()
print('done.')
def exportDetailedList(self, filename):
print('Exporting detailed list...', end=' ')
try:
c = self.conn.cursor()
c.execute('''SELECT * FROM pixiv_master_member
WHERE is_deleted = 0
ORDER BY member_id''')
filename = filename + '.csv'
writer = codecs.open(filename, 'wb', encoding='utf-8')
writer.write('member_id,name,save_folder,created_date,last_update_date,last_image,is_deleted,member_token\r\n')
for row in c:
for string in row:
# Unicode write!!
data = string
writer.write(data)
writer.write(',')
writer.write('\r\n')
writer.write('###END-OF-FILE###')
writer.close()
except BaseException:
print('Error at exportDetailedList(): ' + str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
print('done.')
def exportFanboxPostList(self, filename, sep=","):
print('Exporting FANBOX post list...', end=' ')
try:
c = self.conn.cursor()
c.execute('''SELECT * FROM fanbox_master_post
ORDER BY member_id, post_id''')
filename = filename + '.csv'
writer = codecs.open(filename, 'wb', encoding='utf-8')
columns = ['member_id', 'post_id', 'title', 'fee_required', 'published_date', 'update_date', 'post_type', 'last_update_date']
writer.write(sep.join(columns))
writer.write('\r\n')
for row in c:
writer.write(sep.join([str(x) for x in row]))
writer.write('\r\n')
writer.write('###END-OF-FILE###')
writer.close()
except BaseException:
print('Error at exportFanboxPostList(): ' + str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
print('done.')
##########################################
# III. Print DB #
##########################################
def printMemberList(self, isDeleted=False):
print('Printing member list:')
try:
c = self.conn.cursor()
c.execute('''SELECT * FROM pixiv_master_member
WHERE is_deleted = ? ORDER BY member_id''', (int(isDeleted), ))
print('%10s %25s %25s %20s %20s %10s %s %s' % ('member_id',
'name',
'save_folder',
'created_date',
'last_update_date',
'last_image',
'is_deleted',
'member_token'))
i = 0
for row in c:
print('%10d %#25s %#25s %20s %20s %10d %5s' %
(row[0], row[1].strip(), row[2], row[3], row[4], row[5], row[6]))
i = i + 1
if i == 79:
select = input('Continue [y/n, default is yes]? ').rstrip("\r")
if select == 'n':
break
else:
print(
'member_id\tname\tsave_folder\tcreated_date\tlast_update_date\tlast_image')
i = 0
except BaseException:
print('Error at printMemberList():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
print('done.')
def printImageList(self):
print('Printing image list:')
try:
c = self.conn.cursor()
c.execute(''' SELECT COUNT(*) FROM pixiv_master_image''')
result = c.fetchall()
if result[0][0] > 10000:
print('Row count is more than 10000 (actual row count:',
str(result[0][0]), ')')
print('It may take a while to retrieve the data.')
answer = input('Continue [y/n, default is no]').rstrip("\r")
if answer == 'y':
c.execute('''SELECT * FROM pixiv_master_image
ORDER BY member_id''')
print('')
for row in c:
for string in row:
print(' ', end=' ')
print(string)
print('')
else:
return
# Yavos: it seems you forgot something ;P
else:
c.execute(
'''SELECT * FROM pixiv_master_image ORDER BY member_id''')
print('')
for row in c:
for string in row:
print(' ', end=' ')
print(string)
print('')
# Yavos: end of change
except BaseException:
print('Error at printImageList():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
print('done.')
##########################################
# IV. CRUD Member Table #
##########################################
def insertNewMember(self, member_id=0, member_token=None):
try:
c = self.conn.cursor()
if member_id == 0:
while True:
temp = input('Member ID: ').rstrip("\r")
try:
member_id = int(temp)
except BaseException:
pass
if member_id > 0:
break
c.execute('''INSERT OR IGNORE INTO pixiv_master_member VALUES(?, ?, ?, datetime('now'), '1-1-1', -1, 0, ?)''',
(member_id, str(member_id), r'N\A', member_token))
self.conn.commit()
except BaseException:
print('Error at insertNewMember():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def selectAllMember(self, isDeleted=False):
members = list()
try:
c = self.conn.cursor()
c.execute('''SELECT member_id, save_folder FROM pixiv_master_member WHERE is_deleted = ? ORDER BY member_id''',
(int(isDeleted), ))
result = c.fetchall()
for row in result:
item = PixivListItem(row[0], row[1])
members.append(item)
except BaseException:
print('Error at selectAllMember():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
return members
def selectMembersByLastDownloadDate(self, difference):
members = list()
try:
c = self.conn.cursor()
try:
int_diff = int(difference)
except ValueError:
int_diff = 7
c.execute('''SELECT member_id, save_folder, (julianday(Date('now')) - julianday(last_update_date)) as diff
FROM pixiv_master_member
WHERE is_deleted <> 1 AND ( last_update_date == '1-1-1' OR diff > ? ) ORDER BY member_id''', (int_diff, ))
result = c.fetchall()
for row in result:
item = PixivListItem(row[0], row[1])
members.append(item)
except BaseException:
print('Error at selectMembersByLastDownloadDate():',
str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
return members
def selectMemberByMemberId(self, member_id):
try:
c = self.conn.cursor()
c.execute(
'''SELECT * FROM pixiv_master_member WHERE member_id = ? ''', (member_id, ))
return c.fetchone()
except BaseException:
print('Error at selectMemberByMemberId():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def selectMemberByMemberId2(self, member_id):
try:
c = self.conn.cursor()
c.execute(
'''SELECT member_id, save_folder FROM pixiv_master_member WHERE member_id = ? ''', (member_id, ))
row = c.fetchone()
if row is not None:
return PixivListItem(row[0], row[1])
else:
return PixivListItem(int(member_id), '')
except BaseException:
print('Error at selectMemberByMemberId2():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def printMembersByLastDownloadDate(self, difference):
rows = self.selectMembersByLastDownloadDate(difference)
for row in rows:
for string in row:
print(' ', end=' ')
print(string)
print('\n')
def updateMemberName(self, memberId, memberName, member_token):
try:
c = self.conn.cursor()
c.execute('''UPDATE pixiv_master_member
SET name = ?, member_token = ?
WHERE member_id = ?
''', (memberName, member_token, memberId))
self.conn.commit()
except BaseException:
print('Error at updateMemberName():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def updateSaveFolder(self, memberId, saveFolder):
try:
c = self.conn.cursor()
c.execute('''UPDATE pixiv_master_member
SET save_folder = ?
WHERE member_id = ?
''', (saveFolder, memberId))
self.conn.commit()
except BaseException:
print('Error at updateSaveFolder():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def updateLastDownloadedImage(self, memberId, imageId):
try:
c = self.conn.cursor()
c.execute('''UPDATE pixiv_master_member
SET last_image = ?, last_update_date = datetime('now')
WHERE member_id = ?''', (imageId, memberId))
self.conn.commit()
except BaseException:
print('Error at updateLastDownloadedImage:', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def updateLastDownloadDate(self, memberId):
try:
c = self.conn.cursor()
c.execute("""UPDATE pixiv_master_member
SET last_update_date = datetime('now')
WHERE member_id = ?""", (memberId,))
self.conn.commit()
except BaseException:
print('Error at updateLastDownloadDate():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def deleteMemberByMemberId(self, memberId):
try:
c = self.conn.cursor()
c.execute('''DELETE FROM pixiv_master_member
WHERE member_id = ?''', (memberId, ))
self.conn.commit()
except BaseException:
print('Error at deleteMemberByMemberId():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def deleteMembersByList(self):
list_name = input("Members filename = ").rstrip("\r")
if len(list_name) == 0:
list_name = "members.txt"
listTxt = PixivListItem.parseList(list_name)
print('Reading list...', end=' ')
print('Found', len(listTxt), 'items', end=' ')
try:
c = self.conn.cursor()
for item in listTxt:
c.execute('''DELETE FROM pixiv_manga_image
WHERE EXISTS (SELECT * FROM pixiv_master_image WHERE member_id = ?)''', (item.memberId, ))
c.execute('''DELETE FROM pixiv_master_image
WHERE member_id = ?''', (item.memberId, ))
c.execute('''DELETE FROM pixiv_master_member
WHERE member_id = ?''', (item.memberId, ))
self.conn.commit()
except BaseException:
print('Error at deleteMembersByList():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def keepMembersByList(self):
def parseMembersList(filename):
memberList = list()
reader = PixivHelper.open_text_file(filename)
line_no = 1
try:
for line in reader:
original_line = line
if line.startswith('#') or len(line) < 1:
continue
if len(line.strip()) == 0:
continue
line = line.strip()
memberList.append(line)
line_no = line_no + 1
original_line = ""
except UnicodeDecodeError:
PixivHelper.get_logger().exception("PixivDBManager.parseMembersList(): Invalid value when parsing list")
PixivHelper.print_and_log('error', 'Invalid value: {0} at line {1}, try to save the list.txt in UTF-8.'.format(
original_line, line_no))
except BaseException:
PixivHelper.get_logger().exception("PixivDBManager.parseMembersList(): Invalid value when parsing list")
PixivHelper.print_and_log('error', 'Invalid value: {0} at line {1}'.format(original_line, line_no))
finally:
reader.close()
return memberList
list_name = input("Members filename = ").rstrip("\r")
if len(list_name) == 0:
list_name = "members.txt"
if os.path.exists(list_name):
listTxt = parseMembersList(list_name)
else:
msg = f"List file not found: {list_name}"
raise PixivException("File doesn't exists or no permission to read: " + list_name,
errorCode=PixivException.FILE_NOT_EXISTS_OR_NO_WRITE_PERMISSION)
print('Reading list...', end=' ')
print('Found', len(listTxt), 'items', end=' ')
try:
c = self.conn.cursor()
c.execute('''SELECT * FROM pixiv_master_member''')
result = c.fetchall()
for row in result:
if str(row[0]) not in listTxt:
c.execute('''DELETE FROM pixiv_manga_image
WHERE EXISTS (SELECT * FROM pixiv_master_image WHERE member_id = ?)''', (row[0], ))
c.execute('''DELETE FROM pixiv_master_image
WHERE member_id = ?''', (row[0], ))
c.execute('''DELETE FROM pixiv_master_member
WHERE member_id = ?''', (row[0], ))
self.conn.commit()
except BaseException:
print('Error at keepMembersByList():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def deleteCascadeMemberByMemberId(self, memberId):
try:
c = self.conn.cursor()
c.execute('''DELETE FROM pixiv_manga_image
WHERE EXISTS (SELECT * FROM pixiv_master_image WHERE member_id = ?)''', (memberId, ))
c.execute('''DELETE FROM pixiv_master_image
WHERE member_id = ?''', (memberId, ))
c.execute('''DELETE FROM pixiv_master_member
WHERE member_id = ?''', (memberId, ))
self.conn.commit()
except BaseException:
print('Error at deleteCascadeMemberByMemberId():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def setIsDeletedFlagForMemberId(self, memberId):
try:
c = self.conn.cursor()
c.execute('''UPDATE pixiv_master_member
SET is_deleted = 1, last_update_date = datetime('now')
WHERE member_id = ?''', (memberId,))
self.conn.commit()
except BaseException:
print('Error at setIsDeletedFlagForMemberId():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
##########################################
# V. CRUD Image Table #
##########################################
def insertTag(self, tag_id):
try:
c = self.conn.cursor()
c.execute('''INSERT OR IGNORE INTO pixiv_master_tag VALUES (?, datetime('now'), datetime('now'))''',
(tag_id,))
self.conn.commit()
except BaseException:
print('Error at insertTag():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def insertImageToTag(self, image_id, tag_id):
try:
c = self.conn.cursor()
image_id = int(image_id)
c.execute('''INSERT OR IGNORE INTO pixiv_image_to_tag(image_id, tag_id, created_date, last_update_date)
VALUES (?, ?, datetime('now'), datetime('now'))
ON CONFLICT(image_id, tag_id) DO UPDATE SET last_update_date = datetime('now')''',
(image_id, tag_id))
self.conn.commit()
except BaseException:
print('Error at insertImageToTag():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def insertTagTranslation(self, tag_id, translation_type, translation):
try:
c = self.conn.cursor()
c.execute('''INSERT OR IGNORE INTO pixiv_tag_translation(tag_id, translation_type, translation, created_date, last_update_date)
VALUES (?, ?, ?, datetime('now'), datetime('now'))
ON CONFLICT(tag_id, translation_type) DO UPDATE SET
translation = excluded.translation,
last_update_date = datetime('now')''',
(tag_id, translation_type, translation))
self.conn.commit()
except BaseException:
print('Error at insertImageToTag():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def selectImagesByTagId(self, tag_id):
try:
c = self.conn.cursor()
c.execute(
'''SELECT pixiv_master_image.*
FROM pixiv_master_image
JOIN pixiv_image_to_tag ON pixiv_master_image.image_id = pixiv_image_to_tag.image_id
WHERE pixiv_image_to_tag.tag_id = ?
''', (tag_id,))
return c.fetchall()
except BaseException:
print('Error at selectImagesByTagId():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def selectTagsByImageId(self, image_id):
try:
c = self.conn.cursor()
c.execute(
'''SELECT pixiv_master_tag.*
FROM pixiv_master_tag
JOIN pixiv_image_to_tag ON pixiv_image_to_tag.tag_id = pixiv_master_tag.tag_id
WHERE pixiv_image_to_tag.image_id = ?
''', (image_id,))
return c.fetchall()
except BaseException:
print('Error at selectTagsByImageId():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def deleteImagesByTag(self, tag_id):
try:
c = self.conn.cursor()
c.execute('''DELETE FROM pixiv_master_image
WHERE image_id IN (SELECT image_id FROM pixiv_image_to_tag WHERE tag_id = ?)''',
(tag_id, ))
c.execute('''DELETE FROM pixiv_manga_image
WHERE image_id IN (SELECT image_id FROM pixiv_image_to_tag WHERE tag_id = ?)''',
(tag_id, ))
c.execute('''DELETE FROM pixiv_image_to_tag WHERE tag_id = ?''', (tag_id, ))
self.conn.commit()
except BaseException:
print('Error at deleteImage():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def insertImage(self, member_id, image_id, isManga="", caption=""):
try:
c = self.conn.cursor()
member_id = int(member_id)
image_id = int(image_id)
c.execute('''INSERT OR IGNORE INTO pixiv_master_image VALUES(?, ?, 'N/A' ,'N/A' , datetime('now'), datetime('now'), ?, ? )''',
(image_id, member_id, isManga, caption))
self.conn.commit()
except BaseException:
print('Error at insertImage():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def insertMangaImages(self, manga_files):
try:
c = self.conn.cursor()
c.executemany('''INSERT OR IGNORE INTO pixiv_manga_image
VALUES(?, ?, ?, datetime('now'), datetime('now'))''', manga_files)
self.conn.commit()
except BaseException:
print('Error at insertMangaImages():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def blacklistImage(self, memberId, ImageId):
try:
c = self.conn.cursor()
c.execute('''INSERT OR REPLACE INTO pixiv_master_image
VALUES(?, ?, '**BLACKLISTED**' ,'**BLACKLISTED**' , datetime('now'), datetime('now') )''',
(ImageId, memberId))
self.conn.commit()
except BaseException:
print('Error at blacklistImage():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def selectImageByMemberId(self, member_id):
try:
c = self.conn.cursor()
c.execute(
'''SELECT * FROM pixiv_master_image WHERE member_id = ? ''', (member_id,))
return c.fetchall()
except BaseException:
print('Error at selectImageByMemberId():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def selectImageByMemberIdAndImageId(self, member_id, image_id):
try:
c = self.conn.cursor()
c.execute('''SELECT image_id FROM pixiv_master_image
WHERE image_id = ? AND save_name != 'N/A' AND member_id = ?''', (image_id, member_id))
return c.fetchone()
except BaseException:
print('Error at selectImageByMemberIdAndImageId():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def selectImageByImageId(self, image_id, cols='*'):
try:
c = self.conn.cursor()
c.execute(
'''SELECT %s FROM pixiv_master_image WHERE image_id = ? AND save_name != 'N/A' ''' % (cols,), (image_id,))
return c.fetchone()
except BaseException:
print('Error at selectImageByImageId():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def selectImageByImageIdAndPage(self, imageId, page):
try:
c = self.conn.cursor()
c.execute(
'''SELECT * FROM pixiv_manga_image WHERE image_id = ? AND page = ? ''', (imageId, page))
return c.fetchone()
except BaseException:
print('Error at selectImageByImageIdAndPage():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def updateImage(self, imageId, title, filename, isManga=None, caption=None):
try:
c = self.conn.cursor()
c.execute('''UPDATE pixiv_master_image
SET title = ?, save_name = ?, last_update_date = datetime('now'), is_manga = COALESCE(?, is_manga), caption = COALESCE(?, caption)
WHERE image_id = ?''', (title, filename, isManga, caption, imageId))
self.conn.commit()
except BaseException:
print('Error at updateImage():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def deleteImage(self, imageId):
try:
c = self.conn.cursor()
c.execute('''DELETE FROM pixiv_master_image WHERE image_id = ?''', (imageId, ))
c.execute('''DELETE FROM pixiv_manga_image WHERE image_id = ?''', (imageId, ))
c.execute('''DELETE FROM pixiv_image_to_tag WHERE image_id = ?''', (imageId, ))
self.conn.commit()
except BaseException:
print('Error at deleteImage():', str(sys.exc_info()))
print('failed')
raise