vidconv.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. # /* vidconv.py
  2. # * Copyright (C) 2023 MikuInvidious Team
  3. # *
  4. # * This software is free software; you can redistribute it and/or
  5. # * modify it under the terms of the GNU General Public License as
  6. # * published by the Free Software Foundation; either version 3 of
  7. # * the License, or (at your option) any later version.
  8. # *
  9. # * This software is distributed in the hope that it will be useful,
  10. # * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. # * General Public License for more details.
  13. # *
  14. # * You should have received a copy of the GNU General Public License
  15. # * along with this library. If not, see <http://www.gnu.org/licenses/>.
  16. # */
  17. # The following algorithm is adopted from bilibili-API-collect.
  18. # https://github.com/SocialSisterYi/bilibili-API-collect/blob/master/other/bvid_desc.md
  19. import unittest
  20. table = 'fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF'
  21. itable = { table[i]: i for i in range(len(table)) }
  22. s = [11, 10, 3, 8, 4, 6]
  23. XOR = 177451812
  24. ADD = 8728348608
  25. def bv2av(x):
  26. r = 0
  27. for i in range(6):
  28. r += itable[x[s[i]]] * 58 ** i
  29. return (r - ADD) ^ XOR
  30. def av2bv(x):
  31. x = (x ^ XOR) + ADD
  32. r = list('BV1 4 1 7 ')
  33. for i in range(6):
  34. r[s[i]] = table[x // 58 ** i % 58]
  35. return ''. join(r)
  36. class AvBvConversionTest(unittest.TestCase):
  37. def test_bv2av(self):
  38. self.assertEqual(av2bv(170001), 'BV17x411w7KC')
  39. def test_av2bv(self):
  40. self.assertEqual(bv2av('BV17x411w7KC'), 170001)
  41. if __name__ == '__main__':
  42. unittest.main()