-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
398 lines (362 loc) · 10.6 KB
/
app.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
# Imports
from flask import Flask, g, render_template,request,session,redirect,flash, url_for, abort, jsonify
import psycopg2
import os
import re
import numpy as np
import pandas as pd
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from instagrapi.types import Usertag, Location
from instagrapi import Client
import textwrap
import json
import os
import base64
import random
import string
from datetime import datetime
from config import username, password, sheet_url
# encode to pass the string in database
def encodeString(str):
ret = ""
for i in range(0, len(str)):
if(str[i] == '\''):
ret += '\''
ret += str[i]
return ret
# decode String to readable format
def decodeString(str):
return str
# postgresql database connect
connection = psycopg2.connect(
host = "localhost",
database = "autopost",
user = "postgres",
password = "1141",
port = 5432
)
connection.autocommit = True
cursor = connection.cursor()
# Initiate app
app = Flask(__name__)
#instagram login
# If instaCache.json is not already present, create an empty instaCache.json file and dump the configs
# Otherwise, load the config settings from instaCache.json file
bot = Client()
instaCache = open('instaCache.json', 'r')
if(instaCache.read() == ''):
bot.login(username, password)
bot.dump_settings('instaCache.json')
else:
bot.load_settings('instaCache.json')
bot.login(username, password)
# font, size and colour
fontSize = 30
myFont = ImageFont.truetype('OpenSans-SemiBold.ttf', fontSize, encoding='unic')
# myFont = ImageFont.truetype('OpenSansEmoji.ttf', fontSize, encoding='unic')
bodyColor = (255, 0, 0)
headingColor = (0, 0, 255)
instaHandleCorner = (250, 1030)
# Verifying the session id
def verifySid(sessionId):
cursor.execute("""SELECT session_id from sessions;""")
sessionsList = cursor.fetchall()
if(sessionId in sessionsList):
return True
else:
return False
#create post and post it on instagram
def createPost(id):
print(id)
cursor.execute(f"SELECT entry FROM entries WHERE id = {id};")
l = cursor.fetchall()
print(type(l))
print(len(l))
print(l)
if(len(l) != 1):
return "Something went wrong in createPost1"
text = decodeString(l[0][0])
paragraphs = text.splitlines()
Lines = [textwrap.wrap(j, 50) for j in paragraphs]
lines = []
lines.append('#'+str(id))
lines.append('')
lines.append('')
for l in Lines:
if(len(l) == 0):
lines.append('')
else:
lines.extend(l)
while(lines[len(lines)-1] == ''):
lines = lines[:-1]
print(lines)
#template open
img = Image.open('template.jpg')
I1 = ImageDraw.Draw(img)
I1.text(instaHandleCorner, username, font=myFont, fill=(0, 0, 0))
w,h = img.size
#single photo post
if(len(lines) <= 20):
currHeight = 100+20*(20-len(lines))
for line in lines:
if(line == ''):
currHeight += 30
continue
width,height = myFont.getsize(line)
print(line)
I1.text((200, currHeight+height), line, font=myFont, fill=bodyColor)
currHeight += height
filename="posts/"+id+".jpg"
img.save(filename)
print(text)
bot.photo_upload(path=filename,
caption='#'+str(id)+"\n"+text
# ,usertags=[Usertag(user=bot.user_info_by_username(username), x=1, y=1)]
)
# #multiple_pages album post
elif(len(lines) > 20):
swipePhoto = Image.open('swipe.png').convert("RGBA")
totalPages = 1+(len(lines)-1)/20
subCount = 1
photos = []
while(len(lines) > 20):
currHeight = 100
for j in range(0, 20):
line = lines[j]
if(line == ''):
currHeight += 30
continue
width,height = myFont.getsize(line)
I1.text((200, currHeight+height), line, font=myFont, fill=bodyColor)
currHeight += height
filename="posts/"+id+"-"+str(subCount)+".jpg"
photos.append(filename)
img.paste(swipePhoto, (900, 900), swipePhoto)
img.save(filename)
img = Image.open('template.jpg')
I1 = ImageDraw.Draw(img)
I1.text(instaHandleCorner, username, font=myFont, fill=(0, 0, 0))
subCount+=1
lines = lines[20:]
#last page
currHeight = 100+20*(20-len(lines))
for line in lines:
if(line == ''):
currHeight += 30
continue
width,height = myFont.getsize(line)
I1.text((200, currHeight+height), line, font=myFont, fill=bodyColor)
currHeight += height
filename="posts/"+id+"-"+str(subCount)+".jpg"
photos.append(filename)
img.save(filename)
#upload album post
bot.album_upload(paths=photos,
caption='#'+str(id)+"\n"+text
,usertags=[Usertag(user=bot.user_info_by_username(username), x=1, y=1)]
)
def insertQueue():
print("calling insertQueue")
url_1 = sheet_url.replace('/edit', '/export?format=csv&')
p = pd.read_csv(url_1, usecols= ['Submit your ticket'])
Entries = [i[0] for i in p.values]
cursor.execute(f"SELECT MAX(id) from accepted;")
idList = cursor.fetchall()
id1 = 0
if(len(idList) == 1):
if(idList[0][0] is None):
id1 = 0
else:
id1 = int(idList[0][0])
cursor.execute(f"SELECT MAX(id) from declined;")
idList = cursor.fetchall()
id2 = 0
if(len(idList) == 1):
if(idList[0][0] is None):
id2 = 0
else:
id2 = int(idList[0][0])
cursor.execute(f"SELECT MAX(id) from skipped;")
idList = cursor.fetchall()
id3 = 0
if(len(idList) == 1):
if(idList[0][0] is None):
id3 = 0
else:
id3 = int(idList[0][0])
print("DONE ")
maxId = max(id1, max(id2, id3))
queue = []
for i in range(maxId, len(Entries)):
queue.append(Entries[i]);
print("queue is : ")
print(queue)
for s in queue:
st = encodeString(s)
print(st)
cursor.execute(f"INSERT INTO entries (entry) VALUES ('{st}');")
# cursor.commit()
def createSessionId():
cursor.execute(f"SELECT session_id from sessions")
sessionsList = cursor.fetchall()
sessionsList = [a[0] for a in sessionsList]
while (True):
sessionId = ''.join(random.choices(string.ascii_uppercase +
string.digits, k = 26))
if sessionId in sessionsList:
continue
return sessionId
@app.route('/login', methods=['GET', 'POST'])
def login():
if(request.method == request.method):
username = request.args.get('username')
print(username)
cursor.execute(f"SELECT password from accounts WHERE accounts.username = '{username}';")
passList = cursor.fetchall()
print(passList)
if len(passList) != 1:
return "0"
else:
if(passList[0][0] == request.args.get('password')):
sessionId = createSessionId()
cursor.execute(f"INSERT INTO sessions (session_id, username, login_time) VALUES ('{sessionId}', '{username}', current_timestamp);")
return sessionId
return "0"
return "0"
# receive a new entry from database
@app.route('/getEntry', methods=['GET', 'POST'])
def getEntry():
if(request.method=='GET'):
print("Get request in getEntry received")
entries = []
cursor.execute(f"SELECT MAX(id) from accepted;")
idList = cursor.fetchall()
id1 = 0
if(len(idList) == 1):
if(idList[0][0] is None):
id1 = 0
else:
id1 = int(idList[0][0])
cursor.execute(f"SELECT MAX(id) from declined;")
idList = cursor.fetchall()
id2 = 0
if(len(idList) == 1):
if(idList[0][0] is None):
id2 = 0
else:
id2 = int(idList[0][0])
cursor.execute(f"SELECT MAX(id) from skipped;")
idList = cursor.fetchall()
id3 = 0
if(len(idList) == 1):
if(idList[0][0] is None):
id3 = 0
else:
id3 = int(idList[0][0])
print("DONE ")
maxId = max(id1, max(id2, id3))
cursor.execute(f"SELECT id, entry from entries WHERE id > {maxId} ORDER BY id limit 1;")
entries = cursor.fetchall()
print(entries)
if(len(entries) != 1):
insertQueue()
cursor.execute(f"SELECT id, entry from entries WHERE id > {maxId} ORDER BY id limit 1;")
entries = cursor.fetchall()
if(len(entries) != 1):
return jsonify({
"id" : "-1",
"text" : "No new Entries! Please come back later",
})
return jsonify({
"id" : str(entries[0][0]),
"text" : decodeString(entries[0][1]),
})
elif(request.method == 'POST'):
print("post request in getEntry received")
id = request.args.get('id')
print(id)
print(type(id))
if(request.args.get('status') == 'approve'):
print("approval")
cursor.execute(f"INSERT INTO accepted (id) VALUES ({id});")
createPost(id)
return "Posted on Instagram"
elif(request.args.get('status') == 'decline'):
cursor.execute(f"INSERT INTO declined (id) VALUES ({id});")
return "Declined"
elif(request.args.get('status') == 'skip'):
cursor.execute(f"INSERT INTO skipped (id) VALUES ({id});")
return "Skipped"
else:
return "Something went wrong in getEntry POST"
else:
return "Invalid request type in getEntry"
# receive entries which were skipped earlier
@app.route('/getEntrySkipped', methods=['GET', 'POST'])
def getEntrySkipped():
if(request.method=='GET'):
print("Get request in getEntrySkipped received")
entries = []
cursor.execute(f"SELECT id from skipped limit 1;")
entries = cursor.fetchall()
if(len(entries) != 1):
return jsonify({
"id" : "-1",
"text" : "No new Entries! Please come back later",
})
id = entries[0][0]
cursor.execute(f"SELECT id, entry from entries WHERE id = {id};")
entries = cursor.fetchall()
return jsonify({
"id" : str(entries[0][0]),
"text" : decodeString(entries[0][1]),
})
else:
print("post request in getEntrySkipped received")
id = request.args.get('id')
print(id)
print(type(id))
cursor.execute(f"DELETE FROM skipped WHERE id = {id};")
if(request.args.get('status') == 'approve'):
cursor.execute(f"INSERT INTO accepted (id) VALUES ({id});")
print(createPost(id))
return "Posted on Instagram"
elif(request.args.get('status') == 'decline'):
cursor.execute(f"INSERT INTO declined (id) VALUES ({id});")
return "Declined"
elif(request.args.get('status') == 'skip'):
cursor.execute(f"INSERT INTO skipped (id) VALUES ({id});")
return "Skipped"
else:
return "Something went wrong in getEntrySkipped POST"
# Sample api for testing
@app.route('/', methods=['GET', 'POST'])
def index():
return "Hello World"
# API to verify the session id everytime the user opens the app
@app.route('/verify', methods=['GET', 'POST'])
def verifySessionId():
cursor.execute(f"SELECT session_id from sessions;")
sessionsList = cursor.fetchall()
sessionId = request.args.get('session_id')
print(sessionsList)
sessionsList = [a[0] for a in sessionsList]
if(sessionId in sessionsList):
cursor.execute(f"UPDATE sessions SET login_time = current_timestamp WHERE session_id = '{sessionId}';")
return "1"
else:
return "0"
# API for logging out the account of auto instagram confessions app session
@app.route('/logout', methods=['GET', 'POST'])
def logout():
sid = request.args.get('session_id')
print("logging out ")
print(sid)
cursor.execute(f"DELETE FROM sessions where session_id = '{sid}';")
# connection.commit()
return "1"
# This initiates the server
if __name__ == "__main__":
app.run(port=5000, debug=True)