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.

69 lines
2.0 KiB

  1. import time
  2. import logging as log
  3. import os
  4. import sqlite3
  5. class Database:
  6. def __init__(self, reset_dl):
  7. self.RESET_DL = reset_dl
  8. self.TABLE_FILE = 'files'
  9. self.DB_DIR = os.path.dirname(os.path.realpath(__file__))
  10. self.setup_db()
  11. def connect(self):
  12. """Connect to an existing database instance based on the object
  13. attributes.
  14. """
  15. path = os.path.join(self.DB_DIR, "data.db")
  16. return sqlite3.connect(path)
  17. def setup_db(self):
  18. """Creates a database with tables."""
  19. log.info("check database")
  20. db = self.connect()
  21. crs = db.cursor()
  22. query = "CREATE TABLE IF NOT EXISTS " + self.TABLE_FILE + \
  23. "(id CHAR(32) NOT NULL," + \
  24. "ch_date INT(11) NOT NULL," + \
  25. "PRIMARY KEY(id))"
  26. crs.execute(query)
  27. log.debug(db)
  28. def set_last_file_dl(self, file_id, time):
  29. """Insert a downloaded file to the database.
  30. Parameters:
  31. file_id (string): id of the file downloaded
  32. time(int): time the file was downloaded
  33. """
  34. db = self.connect()
  35. crs = db.cursor()
  36. log.debug('file: ' + file_id + ' time: ' + time)
  37. query = "INSERT INTO " + self.TABLE_FILE + "(`id`,`ch_date`)" + \
  38. "VALUES ( ?, ? )" + \
  39. "ON CONFLICT(`id`) DO UPDATE SET `ch_date` = ?"
  40. crs.execute(query, (file_id, time, time))
  41. db.commit()
  42. def get_last_file_dl(self, file_id):
  43. """Check when a file was downloaded.
  44. Parameters:
  45. file_id(string): id of the file to check
  46. Returns:
  47. int: time when the file was downloaded last. None if it wasnt downloaded.
  48. """
  49. if self.RESET_DL:
  50. return None
  51. db = self.connect()
  52. crs = db.cursor()
  53. query = "SELECT ch_date FROM files WHERE id = ?"
  54. crs.execute(query, (file_id, ))
  55. res = crs.fetchone()
  56. if res != None:
  57. return res[0]
  58. return None