This program downloads all files of a Stud.IP users current semester.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
2.4 KiB

  1. import time
  2. import logging as log
  3. import pymysql
  4. class Database:
  5. def __init__(self, host, port, name, user, passwd, reset_dl):
  6. self.HOST = host
  7. self.PORT = port
  8. self.NAME = name
  9. self.USER = user
  10. self.PASSWD = passwd
  11. self.RESET_DL = reset_dl
  12. self.TABLE_FILE = 'files'
  13. self.setup_db()
  14. def connect(self):
  15. """Connect to an existing database instance based on the object attributes.
  16. """
  17. return pymysql.connect(
  18. host=self.HOST,
  19. port=self.PORT,
  20. user=self.USER,
  21. password=self.PASSWD,
  22. charset='utf8mb4',
  23. cursorclass=pymysql.cursors.DictCursor
  24. )
  25. def setup_db(self):
  26. """Creates a database with tables.
  27. """
  28. db = self.connect()
  29. crs = db.cursor()
  30. sql_query = "CREATE DATABASE IF NOT EXISTS " + self.NAME
  31. crs.execute(sql_query)
  32. db.select_db(self.NAME)
  33. query = "CREATE TABLE IF NOT EXISTS " + self.TABLE_FILE + \
  34. "(id CHAR(32) NOT NULL," + \
  35. "ch_date INT(11) NOT NULL," + \
  36. "PRIMARY KEY(id))"
  37. crs.execute(query)
  38. log.debug(db)
  39. def set_last_file_dl(self, file_id, time):
  40. """Insert a downloaded file to the database.
  41. Parameters:
  42. file_id (string): id of the file downloaded
  43. time(int): time the file was downloaded
  44. """
  45. db = self.connect()
  46. db.select_db(self.NAME)
  47. crs = db.cursor()
  48. log.debug('file: ' + file_id + ' time: ' + time)
  49. query = "INSERT INTO " + self.TABLE_FILE + "(`id`,`ch_date`)" + \
  50. "VALUES ('" + file_id + "','" + time + "')" + \
  51. "ON DUPLICATE KEY UPDATE `ch_date` = '" + time + "'"
  52. crs.execute(query)
  53. db.commit()
  54. def get_last_file_dl(self, file_id):
  55. """Check when a file was downloaded.
  56. Parameters:
  57. file_id(string): id of the file to check
  58. Returns:
  59. int: time when the file was downloaded last. None if it wasnt downloaded.
  60. """
  61. if self.RESET_DL:
  62. return None
  63. db = self.connect()
  64. db.select_db(self.NAME)
  65. crs = db.cursor()
  66. query = "SELECT ch_date FROM files WHERE id ='" + file_id + "'"
  67. crs.execute(query)
  68. res = crs.fetchone()
  69. if res != None:
  70. return res['ch_date']
  71. return None