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.

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