Based off JPS-AU
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

autoupload.py 27 KiB

vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
vor 4 Jahren
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. # Standard library packages
  2. import re
  3. import os
  4. import sys
  5. import shutil
  6. import string
  7. import argparse
  8. import html
  9. from urllib.parse import urlparse
  10. import json
  11. import ftplib
  12. # Third-party packages
  13. import requests
  14. from bs4 import BeautifulSoup
  15. from mutagen.flac import FLAC
  16. from mutagen.mp3 import MP3
  17. from torf import Torrent
  18. from tqdm import tqdm
  19. from langdetect import detect
  20. # JPS-AU files
  21. import jpspy
  22. def asciiart ():
  23. print("""
  24. ██╗██████╗ ███████╗ █████╗ ██╗ ██╗
  25. ██║██╔══██╗██╔════╝ ██╔══██╗██║ ██║
  26. ██║██████╔╝███████╗█████╗███████║██║ ██║
  27. ██ ██║██╔═══╝ ╚════██║╚════╝██╔══██║██║ ██║
  28. ╚█████╔╝██║ ███████║ ██║ ██║╚██████╔╝
  29. ╚════╝ ╚═╝ ╚══════╝ ╚═╝ ╚═╝ ╚═════╝
  30. """)
  31. # Get arguments using argparse
  32. def getargs():
  33. parser = argparse.ArgumentParser()
  34. parser.add_argument('-dir', '--directory', help='Initiate upload on directory', nargs='?', required=True)
  35. parser.add_argument("-f", "--freeleech", help="Enables freeleech", action="store_true")
  36. parser.add_argument("-t", "--tags", help="Add additional tags to the upload", nargs='?')
  37. parser.add_argument('-d', '--debug', help='Enable debug mode', action='store_true')
  38. parser.add_argument("-dry", "--dryrun", help="Dryrun will carry out all actions other than the actual upload to JPS.", action="store_true")
  39. return parser.parse_args()
  40. # Acquire the authkey used for torrent files from upload.php
  41. def getauthkey():
  42. # uploadpage = j.retrieveContent("https://sugoimusic.me/upload.php")
  43. # soup = BeautifulSoup(uploadpage.text, 'html5lib')
  44. # rel2 = str(soup.select('#wrapper #content .thin'))
  45. # # Regex returns multiple matches, could be optimized.
  46. # authkey = re.findall("(?<=value=\")(.*)(?=\")", rel2)[0]
  47. # return authkey
  48. smpage = sm.retrieveContent("https://sugoimusic.me/torrents.php?id=118") # Arbitrary page on JPS that has authkey
  49. soup = BeautifulSoup(smpage.text, 'html5lib')
  50. rel2 = str(soup.select('#content .thin .main_column .torrent_table tbody'))
  51. authkey = re.findall('authkey=(.*)&amp;torrent_pass=', rel2)
  52. return authkey
  53. def copytree(src, dst, symlinks=False, ignore=None):
  54. for item in os.listdir(src):
  55. s = os.path.join(src, item)
  56. d = os.path.join(dst, item)
  57. if os.path.isdir(s):
  58. shutil.copytree(s, d, symlinks, ignore)
  59. else:
  60. shutil.copy2(s, d)
  61. # Creates torrent file using torf module.
  62. def createtorrent(authkey, directory, filename, releasedata):
  63. t = Torrent(path=directory,
  64. trackers=[authkey]) # Torf requires we store authkeys in a list object. This makes it easier to add multiple announce urls.
  65. # Set torrent to private as standard practice for private trackers
  66. t.private = True
  67. t.source = "SugoiMusic"
  68. t.generate()
  69. ## Format releasedata to bring a suitable torrent name.
  70. # The reason we don't just use the directory name is because of an error in POSTING.
  71. # POSTS do not seem to POST hangul/jp characters alongside files.
  72. filename = f"{releasedata['artist']} - {releasedata['title']} [{releasedata['media']}-{releasedata['format']}].torrent"
  73. #filename = filename.replace("\\","")
  74. try:
  75. t.write(filename)
  76. print("_" * 100)
  77. print("Torrent creation:\n")
  78. print(f"{filename} has been created.")
  79. except:
  80. print("_" * 100)
  81. print("Torrent creation:\n")
  82. os.remove(filename)
  83. print(f"{filename} already exists, existing torrent will be replaced.")
  84. t.write(filename)
  85. print(f"{filename} has been created.")
  86. return filename
  87. # Reads FLAC file and returns metadata.
  88. def readflac(filename):
  89. read = FLAC(filename)
  90. # Create dict containing all meta fields we'll be using.
  91. tags={
  92. "ALBUM": read.get('album'),
  93. "ALBUMARTIST": read.get('albumartist'),
  94. "ARTIST": read.get('artist'),
  95. "DATE": read.get('date')[0],
  96. "GENRE": "",#read.get('genre'),
  97. "TITLE": read.get('title'),
  98. "COMMENT": read.get('comment'),
  99. "TRACKNUMBER": read.get('tracknumber')[0].zfill(2),
  100. "DISCNUMBER": read.get('discnumber')}
  101. # Not further looked into this but some FLACs hold a grouping key of contentgroup instead of grouping.
  102. tags['GROUPING'] = read.get('grouping')
  103. ## If grouping returns None we check contentgroup.
  104. # If it still returns none we will ignore it and handle on final checks
  105. if tags['GROUPING'] == None:
  106. tags['GROUPING'] = read.get('contentgroup')
  107. required_tags = ['ALBUM', 'ALBUMARTIST','DATE','TRACKNUMBER']
  108. for k,v in tags.items():
  109. if v == None:
  110. if k in required_tags:
  111. print(f"{k} has returned {v}, this is a required tag")
  112. sys.exit()
  113. return tags
  114. # Reads MP3 file and returns metadata.
  115. def readmp3(filename):
  116. read = MP3(filename)
  117. # Create dict containing all meta fields we'll be using.
  118. tags={
  119. "ALBUM": read.get('TALB'), # Album Title
  120. "ALBUMARTIST": read.get('TPE2'), # Album Artist
  121. "ARTIST": read.get('TPE1'), # Track Artist
  122. "DATE": str(read.get('TDRC')), # Date YYYYMMDD (Will need to add a try/except for other possible identifiers)
  123. "GENRE": read.get('TCON').text, # Genre
  124. "TITLE": read.get('TIT2'), # Track Title
  125. "COMMENT": read.get('COMM::eng'), # Track Comment
  126. "GROUPING": read.get('TIT1'), # Grouping
  127. "TRACKNUMBER": re.sub(r"\/.*", "", str(read.get('TRCK'))).zfill(2), # Tracknumber (Format #/Total) Re.sub removes /#
  128. "DISCNUMBER": re.sub(r"\/.*", "", str(read.get('TPOS')))} # Discnumber (Format #/Total) Re.sub removes /#
  129. required_tags = ['ALBUM', 'ALBUMARTIST','DATE','TRACKNUMBER']
  130. for k,v in tags.items():
  131. if v == None:
  132. if k in required_tags:
  133. print(f"{k} has returned {v}, this is a required tag")
  134. sys.exit()
  135. return tags
  136. # Generates new log file based on directory contents
  137. def generatelog(track_titles, log_filename, log_directory):
  138. # Seperate each tracklist entry in the list with a newline
  139. track_titles = '\n'.join([str(x) for x in track_titles])
  140. # Format tracklist layout
  141. log_contents = f"""[size=5][b]Tracklist[/b][/size]\n{track_titles}
  142. """
  143. # If we have chosen to save the tracklist then we write log_contents to a .log file within the log directory specified
  144. if cfg['local_prefs']['save_tracklist']:
  145. # Write to {album_name}.log
  146. with open(f"{log_directory}/{log_filename}.log", "w+") as f:
  147. f.write(log_contents)
  148. # Reset position to first line and read
  149. f.seek(0)
  150. log_contents = f.read()
  151. f.close()
  152. # If debug mode is enabled we will print the log contents.
  153. if debug:
  154. print("_" * 100)
  155. print(f"Log Contents/Tracklisting: {log_contents}")
  156. return log_contents
  157. def readlog(log_name, log_directory):
  158. with open(f"{log_directory}/{log_name}.log", "r+") as f:
  159. log_contents = f.read()
  160. f.close()
  161. return log_contents
  162. def add_to_hangul_dict(hangul , english , category):
  163. hangul = str(hangul)
  164. english = str(english)
  165. categories = ['version','general','artist','genres', 'label', 'distr']
  166. file = f"json_data/dictionary.json"
  167. json_file = open(file, 'r', encoding='utf-8', errors='ignore')
  168. dictionary = json.load(json_file)
  169. json_file.close()
  170. new = dict()
  171. for cats in dictionary:
  172. #== Create the categories in the new temp file
  173. new[cats] = dict()
  174. for key,value in dictionary[cats].items():
  175. #== List all the old items into the new dict
  176. new[cats][key] = value
  177. if hangul in new[category].keys():
  178. if new[category].get(hangul) is None:
  179. if english != 'None':
  180. new[category][hangul] = english
  181. else:
  182. #== Only update if English word has been supplied ==#
  183. if english != 'None':
  184. new[category][hangul] = english
  185. else:
  186. if english == 'None':
  187. new[category][hangul] = None
  188. else:
  189. new[category][hangul] = english
  190. json_write = open(file, 'w+', encoding='utf-8')
  191. json_write.write(json.dumps(new, indent=4, ensure_ascii=False))
  192. json_write.close()
  193. def translate(string, category, result=None, output=None):
  194. file = "json_data/dictionary.json"
  195. with open(file, encoding='utf-8', errors='ignore') as f:
  196. dictionary = json.load(f, strict=False)
  197. category = str(category)
  198. string = str(string)
  199. search = dictionary[category]
  200. string = string.strip()
  201. if string == 'Various Artists':
  202. output = ['Various Artists',None]
  203. else:
  204. #== NO NEED TO SEARCH - STRING HAS HANGUL+ENGLISH or HANGUL+HANGUL ==#
  205. if re.search("\((?P<inside>.*)\)", string):
  206. #== Complete translation, add to dictionary with both values ==#
  207. #== Contains parentheses, need to split
  208. parenthesis = string.split("(")
  209. pre_parenthesis = parenthesis[0].strip()
  210. in_parenthesis = parenthesis[1].replace(")","").strip()
  211. #== Check the order of the parentheses ==#
  212. if re.search("[^\u0000-\u007F]+",pre_parenthesis) and re.search("[^\u0000-\u007F]+",in_parenthesis):
  213. #== Both hangul
  214. first = 'kr'
  215. second = 'kr'
  216. else:
  217. if re.search("[^\u0000-\u007F]+",pre_parenthesis):
  218. first = 'kr'
  219. second = 'eng'
  220. else:
  221. first = 'eng'
  222. second = 'kr'
  223. if first == 'kr' and second == 'eng':
  224. #== Hangul first ==#
  225. hangul = pre_parenthesis
  226. english = in_parenthesis
  227. add_to_hangul_dict(hangul,english,category)
  228. elif first == 'eng' and second == 'kr':
  229. #== English first ==#
  230. hangul = in_parenthesis
  231. english = pre_parenthesis
  232. add_to_hangul_dict(hangul,english,category)
  233. elif first == 'kr' and second == 'kr':
  234. #== Both Hangul ==#
  235. hangul = pre_parenthesis
  236. english = None
  237. add_to_hangul_dict(pre_parenthesis,None,category)
  238. add_to_hangul_dict(hangul,None,category)
  239. else:
  240. #== Both English
  241. hangul = None
  242. english = pre_parenthesis
  243. output = [hangul,english]
  244. #== No parentheses - HANGUL
  245. else:
  246. #== If the input string is a full Hangul word - check dictionary and then add if necessary)
  247. if re.search("[^\u0000-\u007F]+", string):
  248. if string in search.keys():
  249. #== yes
  250. if search.get(string) is None:
  251. #== If the keyword does not have a translation, add it to the dictionary ==#
  252. output = [string,None]
  253. else:
  254. #== Translation already exists, output the result in a list ==#
  255. output = [string,search.get(string)]
  256. else:
  257. output = [string,None]
  258. add_to_hangul_dict(string, None, category)
  259. #== Full English name -- leave it
  260. else:
  261. for key,value in search.items():
  262. if key == string:
  263. output = [value,string]
  264. break
  265. else:
  266. output = [string,string]
  267. return output
  268. def gatherdata(directory):
  269. # Lists for storing some
  270. list_album_artists = []
  271. list_track_artists = []
  272. list_album = []
  273. list_genre = []
  274. translated_genre = []
  275. translated_album_artists = []
  276. tracklist_entries = []
  277. # Creation of releasedata dict, this will store formatted meta used for the POST.
  278. releasedata = {}
  279. ## Set no log as default value.
  280. # This will be set to True is a .log file is found, in turn this will allow us to determine if WEB or CD.
  281. log_available = False
  282. flac_present = False
  283. mp3_present = False
  284. # Read directory contents, grab metadata of .FLAC files.
  285. for file in os.listdir(directory):
  286. file_location = os.path.join(directory, file)
  287. if file.endswith(".flac"):
  288. # Read FLAC file to grab meta
  289. tags = readflac(file_location)
  290. flac_present = True
  291. # If Discnumber isn't present then we omit it from the tracklist entry
  292. if tags['DISCNUMBER'] == None:
  293. tracklist_entry = f"[b]{tags['TRACKNUMBER']}[/b]. {tags['TITLE'][0]}"
  294. else:
  295. tracklist_entry = f"[b]{tags['DISCNUMBER'][0]}-{tags['TRACKNUMBER']}[/b]. {tags['TITLE'][0]}"
  296. tracklist_entries.append(tracklist_entry)
  297. if debug:
  298. print ("_" * 100)
  299. print(f"Tags for {file}:\n{tags}")
  300. if file.endswith(".mp3"):
  301. # Read MP3 file to grab meta
  302. tags = readmp3(file_location)
  303. mp3_present = True
  304. # If Discnumber isn't present then we omit it from the tracklist entry
  305. if tags['DISCNUMBER'] == "None":
  306. tracklist_entry = f"[b]{tags['TRACKNUMBER']}[/b]. {tags['TITLE'][0]}"
  307. else:
  308. tracklist_entry = f"[b]{tags['DISCNUMBER']}-{tags['TRACKNUMBER']}[/b]. {tags['TITLE'][0]}"
  309. tracklist_entries.append(tracklist_entry)
  310. if debug:
  311. print ("_" * 100)
  312. print(f"Tags for {file}:\n{tags}")
  313. # If only one genre in list attempt to split as there's likely more.
  314. if len(tags['GENRE']) == 1:
  315. tags['GENRE'] = tags['GENRE'][0].split(";")
  316. for aa in tags['ALBUMARTIST']:
  317. list_album_artists.append(aa)
  318. for a in tags['ARTIST']:
  319. list_track_artists.append(a)
  320. list_album.append(tags['ALBUM'][0])
  321. # for g in tags['GENRE']:
  322. # list_genre.append(g)
  323. # Check files to make sure there's no multi-format.
  324. if flac_present:
  325. format = 'FLAC'
  326. bitrate = 'Lossless'
  327. if mp3_present:
  328. format = 'MP3'
  329. bitrate = '320'
  330. if flac_present and mp3_present:
  331. print("Mutt detected, exiting.")
  332. sys.exit()
  333. if file.endswith(".log"):
  334. log_available = True
  335. if log_available == True:
  336. media = 'CD'
  337. else:
  338. media = 'WEB'
  339. # Load Dict.json for translations
  340. file = "json_data/dictionary.json"
  341. with open(file, encoding='utf-8', errors='ignore') as f:
  342. dictionary = json.load(f, strict=False)
  343. # Split additional genre's at comma and append to existing genre tags
  344. if additional_tags != None:
  345. split_tags = additional_tags.split(",")
  346. for s in split_tags:
  347. list_genre.append(s)
  348. # Translate genre's using dict and append to translated_genre
  349. for g in set(list_genre):
  350. translation = translate(g, "genres")[0]
  351. translated_genre.append(translation)
  352. # Translate artist's using dict and append to translated_album_artists
  353. for a in set(list_album_artists):
  354. if tags['ALBUMARTIST'][0] == 'Various Artists':
  355. translated_artist_name = 'V.A.'
  356. translated_album_artists.append("V.A.")
  357. else:
  358. translated_artist_name = translate(string=tags['ALBUMARTIST'][0], category="artist")
  359. translated_album_artists.append(translated_artist_name[0])
  360. ## Identify unique values using sets.
  361. unique_album_artists = ','.join(set(translated_album_artists))
  362. unique_track_artists = ','.join(set(list_track_artists))
  363. unique_genre = ','.join(set(translated_genre))
  364. unique_album = set(list_album)
  365. ## Acquire contents of our log file to be used for album description
  366. # Comments store the album id which matches our log names, so we can use the comment tag to find our album descriptions.
  367. log_directory = cfg['local_prefs']['log_directory']
  368. # Album description taken from log file.
  369. if cfg['local_prefs']['generate_tracklist']:
  370. log_filename = f"{unique_album_artists} - {tags['ALBUM'][0]}"
  371. album_description = generatelog(tracklist_entries, log_filename, log_directory)
  372. else:
  373. log_filename = tags['COMMENT'][0]
  374. album_description = readlog(log_filename, log_directory)
  375. ## If release description is enabled we apply comments to the bugs album url
  376. # Note that this is dependant on the album being sourced from bugs so should be changed per user.
  377. if cfg['local_prefs']['enable_release_description']:
  378. try:
  379. release_description = f"Sourced from [url=https://music.bugs.co.kr/album/{tags['COMMENT'][0]}]Bugs[/url]"
  380. # If any exceptions occur we will return to no release description
  381. except:
  382. release_description = ""
  383. # If release description is not enabled we will use no release description
  384. else:
  385. release_description = ""
  386. ## Assign all our unique values into releasedata{}. We'll use this later down the line for POSTING.
  387. # POST values can be found by inspecting JPS HTML
  388. releasedata['submit'] = 'true'
  389. # List of accepted upload types
  390. accepted_types = ['Album', 'Single']
  391. # If type errors then we ask for user input
  392. try:
  393. releasedata['type'] = translate(tags['GROUPING'][0], "release_types")[0]
  394. except TypeError:
  395. releasedata['type'] = input("\n" + "_" * 100 + "\nGrouping is empty or has received an error, please enter manually (Album/Single)\n")
  396. # If type is still not in accepted_types we ask for user input again and do not break loop until correct
  397. if releasedata['type'] not in accepted_types:
  398. while True:
  399. releasedata['type'] = input("\n" + "_" * 100 + "\nGrouping tag did not return an album type, please enter manually (Album/Single)\n")
  400. if releasedata['type'] not in accepted_types:
  401. continue
  402. else:
  403. break
  404. releasedata['title'] = tags['ALBUM'][0]
  405. releasedata['artist'] = unique_album_artists
  406. # If the value of album artist and artist is the same, we don't need to POST original artist.
  407. if unique_album_artists != unique_track_artists:
  408. releasedata['artistjp'] = unique_track_artists
  409. #re.sub removes any date separators, jps doesn't accept them
  410. releasedata['releasedate'] = re.sub(r"[^0-9]", "", tags['DATE'])
  411. releasedata['format'] = format
  412. releasedata['bitrate'] = bitrate
  413. releasedata['media'] = media
  414. releasedata['album_desc'] = album_description
  415. releasedata['release_desc'] = release_description
  416. releasedata['tags'] = unique_genre
  417. # Enable freeleech if arg is passed
  418. if freeleech:
  419. releasedata['freeleech'] = "true"
  420. ## Language Checks
  421. # This is a required check as we don't want to enter non-english/romaji characters into the title/artist field.
  422. en = detectlanguage(releasedata['title'])
  423. if debug:
  424. print("_" * 100)
  425. print("Title/Artist Language:\n")
  426. print(f"{releasedata['title']} < English = {en}")
  427. if en == False:
  428. input_english_title = input("\n" + "_" * 100 + "\nKorean/Japanese Detected. Please enter the romaji/english title:\n")
  429. # Create new key called titlejp and assign the old title to it
  430. releasedata['titlejp'] = releasedata['title']
  431. # Replace title with the user input.
  432. releasedata['title'] = input_english_title
  433. en = detectlanguage(releasedata['artist'])
  434. if debug:
  435. print(f"{releasedata['artist']} < English = {en}")
  436. if en == False:
  437. input_english_artist = input("\n" + "_" * 100 + "\nKorean/Japanese Detected. Please enter the romaji/english artist name:\n")
  438. # Create new key called titlejp and assign the old title to it
  439. # Replace title with the user input.
  440. releasedata['artist'] = input_english_artist
  441. return releasedata
  442. # Simple function to split a string up into characters
  443. def split(word):
  444. return [char for char in word]
  445. def detectlanguage(string):
  446. ## Language Detect
  447. # This is a required check as we don't want to enter non-english/romaji characters into the title field.
  448. characters = split(string)
  449. language_list = []
  450. for c in characters:
  451. try:
  452. language = detect(c)
  453. language_list.append(language)
  454. except:
  455. langauge = "error"
  456. if 'ko' or 'ja' in language_list:
  457. en = False
  458. else:
  459. en = True
  460. return en
  461. def uploadtorrent(torrent, cover, releasedata):
  462. languages = ('Japanese', 'English', 'Korean', 'Chinese', 'Vietnamese')
  463. # POST url.
  464. uploadurl = "https://sugoimusic.me/upload.php"
  465. # Dataset containing all of the information obtained from our FLAC files.
  466. data = releasedata
  467. if debug:
  468. print('_' * 100)
  469. print('Release Data:\n')
  470. print(releasedata)
  471. try:
  472. postDataFiles = {
  473. 'file_input': open(torrent, 'rb'),
  474. 'userfile': open(cover, 'rb')
  475. }
  476. except FileNotFoundError:
  477. print("_" * 100)
  478. print('File not found!\nPlease confirm file locations and names. Cover image or .torrent file could not be found')
  479. sys.exit()
  480. # If dryrun argument has not ben passed we will POST the results to JPopSuki.
  481. if dryrun != True:
  482. JPSres = j.retrieveContent(uploadurl, "post", data, postDataFiles)
  483. print('\nUpload POSTED')
  484. ## TODO Filter through JPSres.text and create error handling based on responses
  485. #print(JPSres.text)
  486. # Function for transferring the contents of the torrent as well as the torrent.
  487. def ftp_transfer(fileSource, fileDestination, directory, folder_name, watch_folder):
  488. # Create session
  489. session = ftplib.FTP(cfg['ftp_prefs']['ftp_server'],cfg['ftp_prefs']['ftp_username'],cfg['ftp_prefs']['ftp_password'])
  490. # Set session encoding to utf-8 so we can properly handle hangul/other special characters
  491. session.encoding='utf-8'
  492. # Successful FTP Login Print
  493. print("_" * 100)
  494. print("FTP Login Successful")
  495. print(f"Server Name: {cfg['ftp_prefs']['ftp_server']} : Username: {cfg['ftp_prefs']['ftp_username']}\n")
  496. if cfg['ftp_prefs']['add_to_downloads_folder']:
  497. # Create folder based on the directory name of the folder within the torrent.
  498. try:
  499. session.mkd(f"{fileDestination}/{folder_name}")
  500. print(f'Created directory {fileDestination}/{folder_name}')
  501. except ftplib.error_perm:
  502. pass
  503. # Notify user we are beginning the transfer.
  504. print(f"Beginning transfer...")
  505. # Set current folder to the users preferred destination
  506. session.cwd(f"{fileDestination}/{folder_name}")
  507. # Transfer each file in the chosen directory
  508. for file in os.listdir(directory):
  509. with open(f"{directory}/{file}",'rb') as f:
  510. filesize = os.path.getsize(f"{directory}/{file}")
  511. ## Transfer file
  512. # tqdm used for better user feedback.
  513. with tqdm(unit = 'blocks', unit_scale = True, leave = False, miniters = 1, desc = f'Uploading [{file}]', total = filesize) as tqdm_instance:
  514. session.storbinary('STOR ' + file, f, 2048, callback = lambda sent: tqdm_instance.update(len(sent)))
  515. print(f"{file} | Complete!")
  516. f.close()
  517. if cfg['ftp_prefs']['add_to_watch_folder']:
  518. with open(fileSource,'rb') as t:
  519. # Set current folder to watch directory
  520. session.cwd(watch_folder)
  521. ## Transfer file
  522. # We avoid tqdm here due to the filesize of torrent files.
  523. # Most connections will upload these within 1-3s, resulting in near useless progress bars.
  524. session.storbinary(f"STOR {torrentfile}", t)
  525. print(f"{torrentfile} | Sent to watch folder!")
  526. t.close()
  527. # Quit session when complete.
  528. session.quit()
  529. def localfileorganization(torrent, directory, watch_folder, downloads_folder):
  530. # Move torrent directory to downloads_folder
  531. if cfg['local_prefs']['add_to_downloads_folder']:
  532. try:
  533. os.mkdir(os.path.join(downloads_folder, os.path.basename(directory)))
  534. except FileExistsError:
  535. pass
  536. copytree(directory, os.path.join(downloads_folder, os.path.basename(directory)))
  537. shutil.rmtree(directory)
  538. if cfg['local_prefs']['add_to_watch_folder']:
  539. os.rename(torrent, f"{watch_folder}/{torrent}")
  540. if __name__ == "__main__":
  541. asciiart()
  542. args = getargs()
  543. # TODO consider calling args[] directly, we will then not need this line
  544. dryrun = freeleech = tags = directory = debug = None
  545. directory = args.directory
  546. additional_tags = args.tags
  547. if args.dryrun:
  548. dryrun = True
  549. if args.debug:
  550. debug = True
  551. if args.freeleech:
  552. freeleech = True
  553. # Load login credentials from JSON and use them to create a login session.
  554. with open(f'json_data/config.json') as f:
  555. cfg = json.load(f)
  556. loginData = {'username': cfg['credentials']['username'], 'password': cfg['credentials']['password']}
  557. loginUrl = "https://jpopsuki.eu/login.php"
  558. loginTestUrl = "https://jpopsuki.eu"
  559. successStr = "Latest 5 Torrents"
  560. # j is an object which can be used to make requests with respect to the loginsession
  561. j = jpspy.MyLoginSession(loginUrl, loginData, loginTestUrl, successStr, debug=args.debug)
  562. # Acquire authkey
  563. authkey = getauthkey()
  564. # Gather data of FLAC file
  565. releasedata = gatherdata(directory)
  566. # Folder_name equals the last folder in the path, this is used to rename .torrent files to something relevant.
  567. folder_name = os.path.basename(os.path.normpath(directory))
  568. # Identifying cover.jpg path
  569. cover_path = directory + "/" + cfg['local_prefs']['cover_name']
  570. # Create torrent file.
  571. torrentfile = createtorrent(authkey, directory, folder_name, releasedata)
  572. # Upload torrent to JPopSuki
  573. uploadtorrent(torrentfile, cover_path, releasedata)
  574. # Setting variable for watch/download folders
  575. ftp_watch_folder = cfg['ftp_prefs']['ftp_watch_folder']
  576. ftp_downloads_folder = cfg['ftp_prefs']['ftp_downloads_folder']
  577. local_watch_folder = cfg['local_prefs']['local_watch_folder']
  578. local_downloads_folder = cfg['local_prefs']['local_downloads_folder']
  579. if cfg['ftp_prefs']['enable_ftp']:
  580. ftp_transfer(fileSource=torrentfile, fileDestination=ftp_downloads_folder, directory=directory, folder_name=folder_name, watch_folder=ftp_watch_folder)
  581. if cfg['local_prefs']['add_to_watch_folder'] or cfg['local_prefs']['add_to_downloads_folder']:
  582. localfileorganization(torrent=torrentfile, directory=directory, watch_folder=local_watch_folder, downloads_folder=local_downloads_folder)