選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

611 行
24 KiB

  1. # Standard library packages
  2. from pickle import FALSE
  3. import re
  4. import os
  5. import sys
  6. import shutil
  7. import string
  8. import argparse
  9. import html
  10. from urllib.parse import urlparse
  11. import json
  12. import ftplib
  13. # Third-party packages
  14. import requests
  15. from bs4 import BeautifulSoup
  16. from torf import Torrent
  17. from tqdm import tqdm
  18. from langdetect import detect
  19. from pymediainfo import MediaInfo
  20. from pathlib import Path
  21. # JPS-AU files
  22. import jpspy
  23. def asciiart ():
  24. print("""
  25. ██╗██████╗ ███████╗ █████╗ ██╗ ██╗ ████████╗██╗ ██╗
  26. ██║██╔══██╗██╔════╝ ██╔══██╗██║ ██║ ╚══██╔══╝██║ ██║
  27. ██║██████╔╝███████╗█████╗███████║██║ ██║█████╗██║ ██║ ██║
  28. ██ ██║██╔═══╝ ╚════██║╚════╝██╔══██║██║ ██║╚════╝██║ ╚██╗ ██╔╝
  29. ╚█████╔╝██║ ███████║ ██║ ██║╚██████╔╝ ██║ ╚████╔╝
  30. ╚════╝ ╚═╝ ╚══════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝
  31. """)
  32. # Get arguments using argparse
  33. def getargs():
  34. """
  35. Get arguments using argparse
  36. """
  37. parser = argparse.ArgumentParser()
  38. parser.add_argument('-i', '--input', help='Initiate upload on input file', nargs='?', required=True)
  39. parser.add_argument('-d', '--debug', help='Enable debug mode.', action='store_true')
  40. parser.add_argument("-dry", "--dryrun", help="Dryrun will carry out all actions other than the actual upload to SM.", action="store_true")
  41. parser.add_argument("-rt", "--releasetype", help='Set the release type. (PV, Music Performance, TV Music, TV Variety, TV-Drama)', nargs='?')
  42. parser.add_argument("-a", "--artist", help='Set the artist. (Romaji\English). Split multiple with ","', nargs='?')
  43. parser.add_argument("-oa", "--originalartist", help='Set the artist. (Original Language)', nargs='?')
  44. parser.add_argument("-ti", "--title", help='Set the title. (Romaji\English)', nargs='?')
  45. parser.add_argument("-oti", "--originaltitle", help='Set the title. (Original Language)', nargs='?')
  46. parser.add_argument("-t", "--tags", help="Add additional tags to the upload. At least 2 tags are required", nargs='?')
  47. parser.add_argument("-y", "--year", help='Set the torrent year (YYYYMMDD or YYYY).', nargs='?')
  48. parser.add_argument("-fl", "--freeleech", help="Enables freeleech.", action="store_true")
  49. parser.add_argument("-ms", "--mediasource", help='Set the media source. (HDTV, Web)', nargs='?')
  50. parser.add_argument("-im", "--imagepath", help='Set the torrent cover', nargs='?')
  51. parser.add_argument("-tdes", "--torrentdescription", help='Add a torrent description', nargs='?')
  52. parser.add_argument("-tgdes", "--torrentgroupdescription", help='Add a torrent group description. This is a required argument.', nargs='?', required=True)
  53. parser.add_argument("-f", "--formattype", help='Set the media source. (MPEG, MPEG2, AVI, MKV, MP4, h264)', nargs='?')
  54. return parser.parse_args()
  55. # Acquire the authkey used for torrent files from upload.php
  56. def getauthkey():
  57. uploadpage = j.retrieveContent("https://jpopsuki.eu/upload.php")
  58. soup = BeautifulSoup(uploadpage.text, 'html5lib')
  59. rel2 = str(soup.select('#wrapper #content .thin'))
  60. # Regex returns multiple matches, could be optimized.
  61. authkey = re.findall("(?<=value=\")(.*)(?=\")", rel2)[0]
  62. return authkey
  63. def copytree(src, dst, symlinks=False, ignore=None):
  64. for item in os.listdir(src):
  65. s = os.path.join(src, item)
  66. d = os.path.join(dst, item)
  67. if os.path.isdir(s):
  68. shutil.copytree(s, d, symlinks, ignore)
  69. else:
  70. shutil.copy2(s, d)
  71. # Creates torrent file using torf module.
  72. def createtorrent(authkey, filepath, releasedata):
  73. t = Torrent(path=filepath,
  74. trackers=[authkey]) # Torf requires we store authkeys in a list object. This makes it easier to add multiple announce urls.
  75. # Set torrent to private as standard practice for private trackers
  76. t.private = True
  77. t.generate()
  78. ## Format releasedata to bring a suitable torrent name.
  79. # The reason we don't just use the directory name is because of an error in POSTING.
  80. # POSTS do not seem to POST hangul/jp characters alongside files.
  81. filename = f"{releasedata['title']} [{releasedata['media']}-{releasedata['format']}].torrent"
  82. filename = filename.replace("/","/").replace(":",":").replace("?","?").replace("\"","")
  83. try:
  84. t.write(filename)
  85. print("_" * 100)
  86. print("Torrent creation:\n")
  87. print(f"{filename} has been created.")
  88. except:
  89. print("_" * 100)
  90. print("Torrent creation:\n")
  91. os.remove(filename)
  92. print(f"{filename} already exists, existing torrent will be replaced.")
  93. t.write(filename)
  94. print(f"{filename} has been created.")
  95. return filename
  96. def add_to_hangul_dict(hangul , english , category):
  97. hangul = str(hangul)
  98. english = str(english)
  99. categories = ['version','general','artist','genres', 'label', 'distr']
  100. file = f"json_data/dictionary.json"
  101. json_file = open(file, 'r', encoding='utf-8', errors='ignore')
  102. dictionary = json.load(json_file)
  103. json_file.close()
  104. new = dict()
  105. for cats in dictionary:
  106. #== Create the categories in the new temp file
  107. new[cats] = dict()
  108. for key,value in dictionary[cats].items():
  109. #== List all the old items into the new dict
  110. new[cats][key] = value
  111. if hangul in new[category].keys():
  112. if new[category].get(hangul) is None:
  113. if english != 'None':
  114. new[category][hangul] = english
  115. else:
  116. #== Only update if English word has been supplied ==#
  117. if english != 'None':
  118. new[category][hangul] = english
  119. else:
  120. if english == 'None':
  121. new[category][hangul] = None
  122. else:
  123. new[category][hangul] = english
  124. json_write = open(file, 'w+', encoding='utf-8')
  125. json_write.write(json.dumps(new, indent=4, ensure_ascii=False))
  126. json_write.close()
  127. def translate(string, category, result=None, output=None):
  128. file = "json_data/dictionary.json"
  129. with open(file, encoding='utf-8', errors='ignore') as f:
  130. dictionary = json.load(f, strict=False)
  131. category = str(category)
  132. string = str(string)
  133. search = dictionary[category]
  134. string = string.strip()
  135. if string == 'Various Artists':
  136. output = ['Various Artists',None]
  137. else:
  138. #== NO NEED TO SEARCH - STRING HAS HANGUL+ENGLISH or HANGUL+HANGUL ==#
  139. if re.search("\((?P<inside>.*)\)", string):
  140. #== Complete translation, add to dictionary with both values ==#
  141. #== Contains parentheses, need to split
  142. parenthesis = string.split("(")
  143. pre_parenthesis = parenthesis[0].strip()
  144. in_parenthesis = parenthesis[1].replace(")","").strip()
  145. #== Check the order of the parentheses ==#
  146. if re.search("[^\u0000-\u007F]+",pre_parenthesis) and re.search("[^\u0000-\u007F]+",in_parenthesis):
  147. #== Both hangul
  148. first = 'kr'
  149. second = 'kr'
  150. else:
  151. if re.search("[^\u0000-\u007F]+",pre_parenthesis):
  152. first = 'kr'
  153. second = 'eng'
  154. else:
  155. first = 'eng'
  156. second = 'kr'
  157. if first == 'kr' and second == 'eng':
  158. #== Hangul first ==#
  159. hangul = pre_parenthesis
  160. english = in_parenthesis
  161. add_to_hangul_dict(hangul,english,category)
  162. elif first == 'eng' and second == 'kr':
  163. #== English first ==#
  164. hangul = in_parenthesis
  165. english = pre_parenthesis
  166. add_to_hangul_dict(hangul,english,category)
  167. elif first == 'kr' and second == 'kr':
  168. #== Both Hangul ==#
  169. hangul = pre_parenthesis
  170. english = None
  171. add_to_hangul_dict(pre_parenthesis,None,category)
  172. add_to_hangul_dict(hangul,None,category)
  173. else:
  174. #== Both English
  175. hangul = None
  176. english = pre_parenthesis
  177. output = [hangul,english]
  178. #== No parentheses - HANGUL
  179. else:
  180. #== If the input string is a full Hangul word - check dictionary and then add if necessary)
  181. if re.search("[^\u0000-\u007F]+", string):
  182. if string in search.keys():
  183. #== yes
  184. if search.get(string) is None:
  185. #== If the keyword does not have a translation, add it to the dictionary ==#
  186. output = [string,None]
  187. else:
  188. #== Translation already exists, output the result in a list ==#
  189. output = [string,search.get(string)]
  190. else:
  191. output = [string,None]
  192. add_to_hangul_dict(string, None, category)
  193. #== Full English name -- leave it
  194. else:
  195. for key,value in search.items():
  196. if key == string:
  197. output = [value,string]
  198. break
  199. else:
  200. output = [string,string]
  201. return output
  202. def gatherdata():
  203. """
  204. Retrieve data about the upload. Ask for user input if necessary.
  205. :return: releasedata: dict
  206. """
  207. releasedata = {"submit": "true"}
  208. releasedata["album_desc"] = torrentgroupdescription
  209. if torrentdescription:
  210. releasedata['release_desc'] = torrentdescription
  211. list_of_types = ["PV", "Music Performance", "TV Music", "TV Variety", "TV-Drama"]
  212. if releasetype in list_of_types:
  213. if releasetype == "PV":
  214. releasedata["type"] = "PV"
  215. elif releasetype == "TV Music":
  216. releasedata["type"] = "TV-Music"
  217. elif releasetype == "TV Variety":
  218. releasedata["type"] = "TV-Variety"
  219. elif releasetype == "TV-Drama":
  220. releasedata["type"] = "TV-Drama"
  221. else:
  222. while(True):
  223. input_lang = input("\n" + "_" * 100 + "\nEnter a number to choose the upload type. \n1=PV\n2=TV-Music\n3=TV-Variety\n4=TV-Drama\n")
  224. if input_lang == "1":
  225. releasedata["type"] = "PV"
  226. break
  227. elif input_lang == "2":
  228. releasedata["type"] = "TV-Music"
  229. break
  230. elif input_lang == "3":
  231. releasedata["type"] = "TV-Variety"
  232. break
  233. elif input_lang == "4":
  234. releasedata["type"] = "TV-Drama"
  235. break
  236. print("Invalid choice.")
  237. if artist:
  238. releasedata['artist'] = artist
  239. else:
  240. print(artist)
  241. input_english_artist = input("\n" + "_" * 100 + "\nEnter the romaji/english ARTIST name.\n")
  242. releasedata['artist'] = input_english_artist
  243. if originalartist:
  244. releasedata['artistjp'] = originalartist
  245. else:
  246. input_artist = input("\n" + "_" * 100 + "\nEnter the original ARTIST name. Press enter to skip if this torrent has the artist name already in English or already has a artist page.\n")
  247. releasedata['artistjp'] = input_artist
  248. if title:
  249. releasedata['title'] = title
  250. else:
  251. input_english_title = input("\n" + "_" * 100 + "\nEnter the romaji/english TITLE:\n")
  252. releasedata['title'] = input_english_title
  253. if originaltitle:
  254. releasedata['titlejp'] = originaltitle
  255. else:
  256. input_title = input("\n" + "_" * 100 + "\nEnter the original TITLE. Press enter to skip.\n")
  257. releasedata['titlejp'] = input_title
  258. if year:
  259. releasedata["releasedate"] = year
  260. else:
  261. input_year = input("\n" + "_" * 100 + "\nEnter the year as YYYYMMDD or YYYY.\n")
  262. releasedata["releasedate"] = input_year
  263. if formattype:
  264. releasedata['format'] = formattype
  265. else:
  266. while(True):
  267. input_format = input("\n" + "_" * 100 + "\nEnter a number to choose the format. \n1=MPEG\n2=MPEG2\n3=AVI\n4=MKV\n5=MP4\n6=h264\n")
  268. if input_format == "1":
  269. releasedata["format"] = "MPEG"
  270. break
  271. elif input_format == "2":
  272. releasedata["format"] = "MPEG2"
  273. break
  274. elif input_format == "3":
  275. releasedata["format"] = "AVI"
  276. break
  277. elif input_format == "4":
  278. releasedata["format"] = "MKV"
  279. break
  280. elif input_format == "5":
  281. releasedata["format"] = "MP4"
  282. break
  283. elif input_format == "6":
  284. releasedata["format"] = "h264"
  285. break
  286. print("Invalid choice.")
  287. if mediasource:
  288. releasedata['media'] = mediasource
  289. else:
  290. while(True):
  291. input_media = input("\n" + "_" * 100 + "\nEnter a number to choose the media source. \n1=HDTV\n2=Web\n")
  292. if input_media == "1":
  293. releasedata["media"] = "HDTV"
  294. break
  295. elif input_media == "2":
  296. releasedata["media"] = "Web"
  297. break
  298. print("Invalid choice.")
  299. if tags:
  300. releasedata["tags"] = tags
  301. else:
  302. while(True):
  303. input_tags = input("\n" + "_" * 100 + "\nEnter the tags. Separate multiple with \",\". Minimum 1 tag required.\n")
  304. if len(input_tags.split(",")) != 0:
  305. releasedata["tags"] = input_tags
  306. break
  307. else:
  308. print("Please enter at least one tag.")
  309. return releasedata
  310. # MediaInfo.parse doesnt work properly right now. it has duplicate lines
  311. def add_mediainfo_to_releasedata(filename, releasedata):
  312. """
  313. Retrieve mediainfo and append it to the releasedata dictionary.
  314. :return: releasedata: dict
  315. """
  316. mediainfosall = ""
  317. mediainfosall += str(MediaInfo.parse(filename, output="text"))
  318. replacement = str(Path(filename).parent)
  319. mediainfosall = mediainfosall.replace(replacement, '')
  320. #releasedata["release_desc"] += "\n\n" + mediainfosall
  321. print(mediainfosall)
  322. return releasedata
  323. # Simple function to split a string up into characters
  324. def split(word):
  325. return [char for char in word]
  326. def detectlanguage(string):
  327. ## Language Detect
  328. # This is a required check as we don't want to enter non-english/romaji characters into the title field.
  329. characters = split(string)
  330. language_list = []
  331. for c in characters:
  332. try:
  333. language = detect(c)
  334. language_list.append(language)
  335. except:
  336. langauge = "error"
  337. if 'ko' or 'ja' in language_list:
  338. en = False
  339. else:
  340. en = True
  341. return en
  342. def uploadtorrent(torrent, cover, releasedata):
  343. # POST url.
  344. uploadurl = "https://jpopsuki.eu/upload.php"
  345. # Dataset containing all of the information obtained from our FLAC files.
  346. data = releasedata
  347. if debug:
  348. print('_' * 100)
  349. print('Release Data:\n')
  350. print(releasedata)
  351. try:
  352. postDataFiles = {
  353. 'file_input': open(torrent, 'rb'),
  354. 'userfile': open(cover, 'rb')
  355. }
  356. except FileNotFoundError:
  357. print("_" * 100)
  358. print('File not found!\nPlease confirm file locations and names. Cover image or .torrent file could not be found')
  359. sys.exit()
  360. # If dryrun argument has not ben passed we will POST the results to JPopSuki.
  361. if dryrun != True:
  362. JPSres = j.retrieveContent(uploadurl, "post", data, postDataFiles)
  363. print('\nUpload POSTED')
  364. ## TODO Filter through JPSres.text and create error handling based on responses
  365. #print(JPSres.text)
  366. # Function for transferring the contents of the torrent as well as the torrent.
  367. def ftp_transfer(fileSource, fileDestination, directory, folder_name, watch_folder):
  368. # Create session
  369. session = ftplib.FTP(cfg['ftp_prefs']['ftp_server'],cfg['ftp_prefs']['ftp_username'],cfg['ftp_prefs']['ftp_password'])
  370. # Set session encoding to utf-8 so we can properly handle hangul/other special characters
  371. session.encoding='utf-8'
  372. # Successful FTP Login Print
  373. print("_" * 100)
  374. print("FTP Login Successful")
  375. print(f"Server Name: {cfg['ftp_prefs']['ftp_server']} : Username: {cfg['ftp_prefs']['ftp_username']}\n")
  376. if cfg['ftp_prefs']['add_to_downloads_folder']:
  377. # Create folder based on the directory name of the folder within the torrent.
  378. try:
  379. session.mkd(f"{fileDestination}/{folder_name}")
  380. print(f'Created directory {fileDestination}/{folder_name}')
  381. except ftplib.error_perm:
  382. pass
  383. # Notify user we are beginning the transfer.
  384. print(f"Beginning transfer...")
  385. # Set current folder to the users preferred destination
  386. session.cwd(f"{fileDestination}/{folder_name}")
  387. # Transfer each file in the chosen directory
  388. for file in os.listdir(directory):
  389. with open(f"{directory}/{file}",'rb') as f:
  390. filesize = os.path.getsize(f"{directory}/{file}")
  391. ## Transfer file
  392. # tqdm used for better user feedback.
  393. with tqdm(unit = 'blocks', unit_scale = True, leave = False, miniters = 1, desc = f'Uploading [{file}]', total = filesize) as tqdm_instance:
  394. session.storbinary('STOR ' + file, f, 2048, callback = lambda sent: tqdm_instance.update(len(sent)))
  395. print(f"{file} | Complete!")
  396. f.close()
  397. if cfg['ftp_prefs']['add_to_watch_folder']:
  398. with open(fileSource,'rb') as t:
  399. # Set current folder to watch directory
  400. session.cwd(watch_folder)
  401. ## Transfer file
  402. # We avoid tqdm here due to the filesize of torrent files.
  403. # Most connections will upload these within 1-3s, resulting in near useless progress bars.
  404. session.storbinary(f"STOR {torrentfile}", t)
  405. print(f"{torrentfile} | Sent to watch folder!")
  406. t.close()
  407. # Quit session when complete.
  408. session.quit()
  409. def localfileorganization(torrent, directory, watch_folder, downloads_folder):
  410. # Move torrent directory to downloads_folder
  411. if cfg['local_prefs']['add_to_downloads_folder']:
  412. try:
  413. os.mkdir(os.path.join(downloads_folder, os.path.basename(directory)))
  414. except FileExistsError:
  415. pass
  416. copytree(directory, os.path.join(downloads_folder, os.path.basename(directory)))
  417. shutil.rmtree(directory)
  418. if cfg['local_prefs']['add_to_watch_folder']:
  419. os.rename(torrent, f"{watch_folder}/{torrent}")
  420. def addnewline(text):
  421. text = re.sub(r"\\n", "\n", text)
  422. def gettorrentgroupdescription(textfile):
  423. result = ""
  424. with open(textfile,encoding='utf8') as f:
  425. lines = f.readlines()
  426. for line in lines:
  427. result += line
  428. return result
  429. def gettorrentdescription(textfile):
  430. result = ""
  431. with open(textfile,encoding='utf8') as f:
  432. lines = f.readlines()
  433. for line in lines:
  434. result += line
  435. return result
  436. if __name__ == "__main__":
  437. asciiart()
  438. args = getargs()
  439. # TODO consider calling args[] directly, we will then not need this line
  440. dryrun = debug = tags = artist = title = formattype = imagepath = freeleech = None
  441. originalartist = originaltitle = torrentdescription = torrentgroupdescription = year = mediasource = releasetype = None
  442. inputfile = args.input
  443. # torrentgroupdescription = args.torrentgroupdescription
  444. # torrentdescription = args.torrentdescription
  445. torrentgroupdescription = gettorrentgroupdescription(args.torrentgroupdescription)
  446. torrentdescription = gettorrentdescription(args.torrentdescription)
  447. if args.dryrun:
  448. dryrun = True
  449. if args.debug:
  450. debug = True
  451. if args.freeleech:
  452. freeleech = True
  453. if args.releasetype:
  454. releasetype = args.releasetype
  455. if args.title:
  456. title = args.title
  457. if args.artist:
  458. artist = args.artist
  459. if args.originalartist:
  460. originalartist = args.originalartist
  461. if args.originaltitle:
  462. originaltitle = args.originaltitle
  463. if args.year:
  464. year = args.year
  465. if args.mediasource:
  466. mediasource = args.mediasource
  467. if args.formattype:
  468. format_type = args.formattype
  469. if args.tags:
  470. tags = args.tags
  471. if args.imagepath:
  472. imagepath = args.imagepath
  473. # Load login credentials from JSON and use them to create a login session.
  474. with open(f'json_data/config.json') as f:
  475. cfg = json.load(f)
  476. loginData = {'username': cfg['credentials']['username'], 'password': cfg['credentials']['password']}
  477. loginUrl = "https://jpopsuki.eu/login.php"
  478. loginTestUrl = "https://jpopsuki.eu"
  479. successStr = "Latest 5 Torrents"
  480. # j is an object which can be used to make requests with respect to the loginsession
  481. j = jpspy.MyLoginSession(loginUrl, loginData, loginTestUrl, successStr, debug=args.debug)
  482. # Acquire authkey
  483. authkey = getauthkey()
  484. # Gather data of the file
  485. releasedata = gatherdata()
  486. # releasedata_and_mediainfo = add_mediainfo_to_releasedata(inputfile, releasedata)
  487. # Folder_name equals the last folder in the path, this is used to rename .torrent files to something relevant.
  488. # folder_name = os.path.basename(os.path.normpath(directory))
  489. # Identifying cover.jpg path
  490. # cover_path = directory + "/" + cfg['local_prefs']['cover_name']
  491. #= addnewline(releasedata["album_desc"])
  492. #print(releasedata["album_desc"] )
  493. # Create torrent file.
  494. torrentfile = createtorrent(authkey, inputfile, releasedata)
  495. # Upload torrent to JPopSuki
  496. uploadtorrent(torrentfile, imagepath, releasedata)
  497. # Setting variable for watch/download folders
  498. ftp_watch_folder = cfg['ftp_prefs']['ftp_watch_folder']
  499. ftp_downloads_folder = cfg['ftp_prefs']['ftp_downloads_folder']
  500. local_watch_folder = cfg['local_prefs']['local_watch_folder']
  501. local_downloads_folder = cfg['local_prefs']['local_downloads_folder']
  502. # if cfg['ftp_prefs']['enable_ftp']:
  503. # ftp_transfer(fileSource=torrentfile, fileDestination=ftp_downloads_folder, directory=directory, folder_name=folder_name, watch_folder=ftp_watch_folder)
  504. # if cfg['local_prefs']['add_to_watch_folder'] or cfg['local_prefs']['add_to_downloads_folder']:
  505. # localfileorganization(torrent=torrentfile, directory=directory, watch_folder=local_watch_folder, downloads_folder=local_downloads_folder)
  506. if not dryrun:
  507. if cfg['local_prefs']['add_to_watch_folder']:
  508. os.rename(torrentfile, f"{local_watch_folder}/{torrentfile}")