refresher.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # Copyright (C) 2023 MikuInvidious Team
  2. #
  3. # MikuInvidious is free software; you can redistribute it and/or
  4. # modify it under the terms of the GNU General Public License as
  5. # published by the Free Software Foundation; either version 3 of
  6. # the License, or (at your option) any later version.
  7. #
  8. # MikuInvidious is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. # General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with MikuInvidious. If not, see <http://www.gnu.org/licenses/>.
  15. import toml
  16. from bilibili_api import sync, Credential
  17. def discard_generated_data(fn):
  18. with open(fn, 'r') as file:
  19. lines = file.readlines()
  20. index = None
  21. for i, line in enumerate(lines):
  22. if '## GENERATED DATA, DO NOT WRITE ANYTHING BELOW!!! ##\n' in line:
  23. index = i
  24. break
  25. if index is not None:
  26. with open(fn, 'w') as file:
  27. file.writelines(lines[:index])
  28. return True
  29. else:
  30. return False
  31. def renew_cookies(cred):
  32. if sync(cred.check_refresh()):
  33. sync(cred.refresh())
  34. write_cookies(cred)
  35. print('Cookies refreshed.')
  36. return True
  37. return False
  38. def write_cookies(cred):
  39. buf = '' if discard_generated_data('config.toml') else '\n\n'
  40. buf += '## GENERATED DATA, DO NOT WRITE ANYTHING BELOW!!! ##\n'
  41. buf += '[updatedcred]\n'
  42. for k,v in cred.get_cookies().items():
  43. buf += f'{k.lower()} = \'{v}\'\n'
  44. with open('config.toml', 'a') as f:
  45. f.write(buf)
  46. if __name__ == '__main__':
  47. print('Trying to refresh the cookies...')
  48. appconf = toml.load('config.toml')
  49. credstore = appconf['updatedcred'] if 'updatedcred' in appconf else \
  50. appconf['credential']
  51. appcred = Credential(sessdata=credstore['sessdata'],
  52. bili_jct=credstore['bili_jct'],
  53. buvid3=credstore['buvid3'],
  54. dedeuserid=credstore['dedeuserid'],
  55. ac_time_value=credstore['ac_time_value'])
  56. if renew_cookies(appcred):
  57. print('Successfully refreshed the cookies.')
  58. else:
  59. print('Cookies are already up-to-date.')