Keep track of the followed users and help avoid excessive follow of the same user
(operation, username, limit, logger)
| 1219 | |
| 1220 | |
| 1221 | def follow_restriction(operation, username, limit, logger): |
| 1222 | """Keep track of the followed users and help avoid excessive follow of |
| 1223 | the same user""" |
| 1224 | |
| 1225 | conn = None |
| 1226 | |
| 1227 | try: |
| 1228 | # get a DB and start a connection |
| 1229 | db, profile_id = get_database() |
| 1230 | conn = sqlite3.connect(db) |
| 1231 | |
| 1232 | with conn: |
| 1233 | conn.row_factory = sqlite3.Row |
| 1234 | cur = conn.cursor() |
| 1235 | |
| 1236 | cur.execute( |
| 1237 | "SELECT * FROM followRestriction WHERE profile_id=:id_var " |
| 1238 | "AND username=:name_var", |
| 1239 | {"id_var": profile_id, "name_var": username}, |
| 1240 | ) |
| 1241 | data = cur.fetchone() |
| 1242 | follow_data = dict(data) if data else None |
| 1243 | |
| 1244 | if operation == "write": |
| 1245 | if follow_data is None: |
| 1246 | # write a new record |
| 1247 | cur.execute( |
| 1248 | "INSERT INTO followRestriction (profile_id, " |
| 1249 | "username, times) VALUES (?, ?, ?)", |
| 1250 | (profile_id, username, 1), |
| 1251 | ) |
| 1252 | else: |
| 1253 | # update the existing record |
| 1254 | follow_data["times"] += 1 |
| 1255 | sql = ( |
| 1256 | "UPDATE followRestriction set times = ? WHERE " |
| 1257 | "profile_id=? AND username = ?" |
| 1258 | ) |
| 1259 | cur.execute(sql, (follow_data["times"], profile_id, username)) |
| 1260 | |
| 1261 | # commit the latest changes |
| 1262 | conn.commit() |
| 1263 | |
| 1264 | elif operation == "read": |
| 1265 | if follow_data is None: |
| 1266 | return False |
| 1267 | |
| 1268 | elif follow_data["times"] < limit: |
| 1269 | return False |
| 1270 | |
| 1271 | else: |
| 1272 | exceed_msg = "" if follow_data["times"] == limit else "more than " |
| 1273 | logger.info( |
| 1274 | "--> {} has already been followed {}{} times".format( |
| 1275 | username, exceed_msg, str(limit) |
| 1276 | ) |
| 1277 | ) |
| 1278 | return True |
no test coverage detected