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.

140 lines
4.2KB

  1. #!/usr/bin/env python3
  2. # helper for interacting with imgur api
  3. # Now only download images and images from album
  4. # I'll add new features once needed...
  5. import requests
  6. from argparse import ArgumentParser
  7. from os import mkdir
  8. SECRET_FILE="./.imgur_secrets"
  9. BASE_URL = "https://api.imgur.com/3/"
  10. def get_args():
  11. p = ArgumentParser(description="Python helper for interacting with imgur api")
  12. p.add_argument("--no-verify", help="Do not verify ssl certificate", action="store_true", default=False)
  13. p.add_argument("-i", "--image", help="Download an image")
  14. p.add_argument("-a", "--album", help="Download an album")
  15. p.add_argument("-u", "--upload", help="Upload an image")
  16. p.add_argument("-o", "--output", help="Output directory for downloaded content", default=".")
  17. return p.parse_args()
  18. def get_secrets():
  19. CLIENT_ID = CLIENT_SECRET = ""
  20. with open(SECRET_FILE, "r") as f:
  21. lines = f.readlines()
  22. for line in lines:
  23. line = line.replace("\n","")
  24. if line.startswith("CLIENT_ID"):
  25. CLIENT_ID = line.split("=")[1]
  26. elif line.startswith("CLIENT_SECRET"):
  27. CLIENT_SECRET = line.split("=")[1]
  28. return (CLIENT_ID, CLIENT_SECRET)
  29. class Pymgur(object):
  30. def __init__(self, secrets, no_verify):
  31. self.cid, self.csec = secrets
  32. self.verify = not no_verify
  33. self.s = requests.Session()
  34. if not self.verify:
  35. requests.packages.urllib3.disable_warnings()
  36. print("[!] Warning: SSL cert check is disabled.")
  37. def get(self, endpoint, fmt=None):
  38. return self.raw_get(f"{BASE_URL}{endpoint}", {'Authorization': f'Client-ID {self.cid}'}, fmt)
  39. def raw_get(self, url, headers=None, fmt=None):
  40. data = self.s.get(url, headers=headers, verify=self.verify)
  41. if fmt == 'json':
  42. return data.json()
  43. else:
  44. return data.content
  45. def post(self, endpoint, data, fmt=None):
  46. data=self.s.post( \
  47. f"{BASE_URL}{endpoint}", \
  48. headers={'Authorization': f'Client-ID {self.cid}'}, \
  49. data=data, \
  50. verify=self.verify \
  51. )
  52. if fmt == 'json':
  53. return data.json()
  54. else:
  55. return data.content
  56. def get_ext(imgtype):
  57. ext = ""
  58. if imgtype == 'image/jpeg':
  59. ext = "jpg"
  60. elif imgtype == 'image/png':
  61. ext = "png"
  62. return ext
  63. def main():
  64. args = get_args()
  65. pymgur = Pymgur(get_secrets(), args.no_verify)
  66. if args.upload:
  67. print(f"[*] Uploading {args.upload} to imgur...")
  68. with open(args.upload, "rb") as f:
  69. data=f.read()
  70. from base64 import b64encode
  71. b64data = b64encode(data)
  72. ret=pymgur.post("image", {'image': b64data, 'type': 'base64'}, fmt='json')
  73. if ret['success']:
  74. print(f"[+] Successfully uploaded as {ret['data']['link']}")
  75. else:
  76. print("[x] Error while uploading image...")
  77. return
  78. if args.image:
  79. print(f"[*] Downloading image {args.image}...")
  80. imgdata = pymgur.get(f"image/{args.image}", fmt='json')['data']
  81. img = pymgur.raw_get(imgdata["link"])
  82. ext = get_ext(imgdata['type'])
  83. with open(f"{args.output}/{imgdata['id']}.{ext}", "wb") as f:
  84. f.write(img)
  85. print(f"[+] Image saved @ {args.output}/{imgdata['id']}.{ext}")
  86. return
  87. if args.album:
  88. print("[*] Retrieving album images...")
  89. albumdata = pymgur.get(f"album/{args.album}/images", fmt='json')['data']
  90. print(f"[+] Data acquired, total images: {len(albumdata)}")
  91. print(f"[*] Downloaded images will go to {args.output}/{args.album} ...")
  92. try:
  93. mkdir(f"{args.output}/{args.album}")
  94. except FileExistsError:
  95. pass
  96. for imgdata in albumdata:
  97. img = pymgur.raw_get(imgdata["link"])
  98. ext = get_ext(imgdata['type'])
  99. print(f"[*] Downloading image {imgdata['id']} to {args.output}/{args.album}/{imgdata['id']}.{ext} ...")
  100. with open(f"{args.output}/{args.album}/{imgdata['id']}.{ext}", "wb") as f:
  101. f.write(img)
  102. print("[+] All images from album retrived!")
  103. return
  104. if __name__=='__main__':
  105. main()