aria2_cutfile.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #!/usr/bin/env python2
  2. # vim:fileencoding=utf-8
  3. """
  4. description: used by aria2c on download stop
  5. usage: append --on-download-stop=aria2_cutfile.py
  6. to aria2c command
  7. or:
  8. call by [aria2c_cutfile.py $1 $2 $LOCATEFILE]
  9. notify: there seems only python2 could handle file
  10. with "read/write/append" options in open file
  11. so, keep useing python2 instead
  12. """
  13. import struct
  14. import sys
  15. import os
  16. TRUNK_SIZE = 16 # trunck flags represent 16KiB each bit
  17. def ipack(sl_4):
  18. return int("%d"%struct.unpack('>I',sl_4))
  19. def lpack(sl_8):
  20. return int("%d"%struct.unpack('>Q',sl_8))
  21. class AriaCtlCfg:
  22. def __init__(self, filename):
  23. fp = open(filename, 'rb')
  24. self.VERSION = fp.read(2)
  25. self.EXTENSION = fp.read(4)
  26. self.INFO_HASH_LENGTH = ipack(fp.read(4))
  27. self.INFO_HASH = fp.read(self.INFO_HASH_LENGTH)
  28. self.PIECES_LENGTH = ipack(fp.read(4))
  29. self.TOTAL_LENGTH = lpack(fp.read(8))
  30. self.UPLOAD_LENGTH = lpack(fp.read(8))
  31. self.BITFIELD_LENGTH = ipack(fp.read(4))
  32. self.BITFIELD = fp.read(self.BITFIELD_LENGTH)
  33. self.NUM_IN_FLIGHT_PIECE = ipack(fp.read(4))
  34. self.INDEX = ipack(fp.read(4))
  35. self.LENGTH = ipack(fp.read(4))
  36. self.BITFIELD_LENGTH = ipack(fp.read(4))
  37. c_flags = 0
  38. for i in range(self.BITFIELD_LENGTH):
  39. flag = ord(fp.read(1))
  40. x = 0
  41. for j in range(8):
  42. if ((flag << x) & 255):
  43. #print("one bit")
  44. x += 1
  45. c_flags += 1
  46. else:
  47. break
  48. print(self.LENGTH)
  49. self.first_block_length = self.INDEX*self.LENGTH + \
  50. c_flags * TRUNK_SIZE * 1024
  51. self.c_flags = c_flags
  52. def echo_info(self):
  53. print(self.c_flags)
  54. print(self.first_block_length)
  55. if __name__ == "__main__":
  56. """call by aria2c"""
  57. tmp1_id = sys.argv[1]
  58. tmp2 = sys.argv[2]
  59. filename = sys.argv[3]
  60. print(filename)
  61. # make sure there is file suffix with ".aria2" exist
  62. a2 = AriaCtlCfg(filename + ".aria2")
  63. a2.echo_info()
  64. fa = open(filename , 'rw+b')
  65. fa.seek(a2.first_block_length)
  66. fa.truncate()
  67. fa.close()
  68. os.remove(filename + ".aria2")