Sourcery Starbot ⭐ refactored haruo75/WZML#1
Sourcery Starbot ⭐ refactored haruo75/WZML#1SourceryAI wants to merge 1 commit intoharuo75:masterfrom
Conversation
SourceryAI
left a comment
There was a problem hiding this comment.
Sourcery timed out performing refactorings.
Due to GitHub API limits, only the first 60 comments can be shown.
| batch = drive.new_batch_http_request() | ||
|
|
||
| aa = glob.glob('%s/*.json' % acc_dir) | ||
| aa = glob.glob(f'{acc_dir}/*.json') |
There was a problem hiding this comment.
Lines 60-60 refactored with the following changes:
- Replace interpolated string formatting with f-string (
replace-interpolation-with-fstring)
| batch.add(service.projects().serviceAccounts().create(name='projects/' + project, body={'accountId': aid, | ||
| 'serviceAccount': { | ||
| 'displayName': aid}})) | ||
| batch.add( | ||
| service.projects() | ||
| .serviceAccounts() | ||
| .create( | ||
| name=f'projects/{project}', | ||
| body={ | ||
| 'accountId': aid, | ||
| 'serviceAccount': {'displayName': aid}, | ||
| }, | ||
| ) | ||
| ) |
There was a problem hiding this comment.
Function _create_accounts refactored with the following changes:
- Use f-string instead of string concatenation (
use-fstring-for-concatenation)
| print('Creating accounts in %s' % project) | ||
| print(f'Creating accounts in {project}') |
There was a problem hiding this comment.
Function _create_remaining_accounts refactored with the following changes:
- Replace interpolated string formatting with f-string (
replace-interpolation-with-fstring)
| print(str(exception)) | ||
| print(exception) |
There was a problem hiding this comment.
Function _def_batch_resp refactored with the following changes:
- Remove unnecessary call to
str()withinprint()(remove-str-from-print)
| print(str(exception)) | ||
| print(exception) |
There was a problem hiding this comment.
Function _pc_resp refactored with the following changes:
- Remove unnecessary call to
str()withinprint()(remove-str-from-print)
| if bool(url1) == True: | ||
| if bool(url1): | ||
| return bool(url1) | ||
| elif bool(url) == True: | ||
| elif bool(url): |
There was a problem hiding this comment.
Function is_unified_link refactored with the following changes:
- Simplify comparison to boolean [×2] (
simplify-boolean-comparison)
| else: | ||
| url = re_match(r'https?://(hubdrive|katdrive|kolop|drivefire|drivebuzz)\.\S+', url) | ||
| return bool(url) | ||
| url = re_match(r'https?://(hubdrive|katdrive|kolop|drivefire|drivebuzz)\.\S+', url) | ||
| return bool(url) |
There was a problem hiding this comment.
Function is_udrive_link refactored with the following changes:
- Remove unnecessary else after guard condition (
remove-unnecessary-else)
| LOGGER.info("Remname : "+file_) | ||
| if PREFIX: | ||
| if not file_.startswith(PREFIX): | ||
| file_ = f"{PREFIX}{file_}" | ||
| LOGGER.info(f"Remname : {file_}") | ||
| if PREFIX and not file_.startswith(PREFIX): | ||
| file_ = f"{PREFIX}{file_}" |
There was a problem hiding this comment.
Function change_filename refactored with the following changes:
- Use f-string instead of string concatenation [×2] (
use-fstring-for-concatenation) - Merge nested if conditions (
merge-nested-ifs) - Move assignment closer to its usage within a block (
move-assign-in-block) - Swap if/else branches of if expression to remove negation (
swap-if-expression) - Simplify if expression by using or (
or-if-exp-identity)
| if user_id in user_data: | ||
| return user_data[user_id].get('is_sudo') | ||
| return False | ||
| return user_data[user_id].get('is_sudo') if user_id in user_data else False |
There was a problem hiding this comment.
Function is_sudo refactored with the following changes:
- Lift code into else after jump in control flow (
reintroduce-else) - Replace if statement with if expression (
assign-if-exp)
| if user_id in user_data and user_data[user_id].get('is_paid'): | ||
| ex_date = user_data[user_id].get('expiry_date') | ||
| if ex_date: | ||
| odate = datetime.strptime(ex_date, '%d-%m-%Y') | ||
| ndate = datetime.today() | ||
| if odate.year <= ndate.year: | ||
| if odate.month <= ndate.month: | ||
| if odate.day < ndate.day: | ||
| return False | ||
| return True | ||
| else: return False | ||
| if user_id not in user_data or not user_data[user_id].get('is_paid'): | ||
| return False | ||
| if ex_date := user_data[user_id].get('expiry_date'): | ||
| odate = datetime.strptime(ex_date, '%d-%m-%Y') | ||
| ndate = datetime.now() | ||
| if ( | ||
| odate.year <= ndate.year | ||
| and odate.month <= ndate.month | ||
| and odate.day < ndate.day | ||
| ): | ||
| return False | ||
| return True |
There was a problem hiding this comment.
Function is_paid refactored with the following changes:
- Add guard clause (
last-if-guard) - Use named expression to simplify assignment and conditional (
use-named-expression) - Merge nested if conditions [×2] (
merge-nested-ifs) - Replace datetime.datetime.today() with datetime.datetime.now() (
use-datetime-now-not-today)
| DLs: {num_active} | ULs: {num_upload} | SEEDING: {num_seeding} | ||
| ZIP: {num_zip} | UNZIP: {num_unzip} | SPLIT: {num_split} | ||
| """ | ||
| return stats |
There was a problem hiding this comment.
Function bot_sys_stats refactored with the following changes:
- Remove unreachable code (
remove-unreachable-code)
| CallbackQueryHandler(pop_up_stats, pattern="^" + str(THREE) + "$") | ||
| CallbackQueryHandler(pop_up_stats, pattern=f"^{str(THREE)}$") |
There was a problem hiding this comment.
Lines 601-601 refactored with the following changes:
- Use f-string instead of string concatenation [×2] (
use-fstring-for-concatenation)
| dbval = value | ||
| else: | ||
| dbval = False | ||
| dbval = value if value is not None else False |
There was a problem hiding this comment.
Function DbManger.update_userval refactored with the following changes:
- Replace if statement with if expression (
assign-if-exp)
| def get_base_name(orig_path: str): | ||
| ext = [ext for ext in ARCH_EXT if orig_path.lower().endswith(ext)] | ||
| if ext: | ||
| if ext := [ext for ext in ARCH_EXT if orig_path.lower().endswith(ext)]: |
There was a problem hiding this comment.
Function get_base_name refactored with the following changes:
- Use named expression to simplify assignment and conditional (
use-named-expression)
| if not noMap: | ||
| listener.suproc = Popen(["ffmpeg", "-hide_banner", "-loglevel", "error", "-ss", str(start_time), | ||
| "-i", path, "-fs", str(split_size), "-map", "0", "-map_chapters", "-1", | ||
| "-c", "copy", out_path]) | ||
| else: | ||
| listener.suproc = Popen(["ffmpeg", "-hide_banner", "-loglevel", "error", "-ss", str(start_time), | ||
| "-i", path, "-fs", str(split_size), "-map_chapters", "-1", "-c", "copy", | ||
| out_path]) | ||
| listener.suproc = ( | ||
| Popen( | ||
| [ | ||
| "ffmpeg", | ||
| "-hide_banner", | ||
| "-loglevel", | ||
| "error", | ||
| "-ss", | ||
| str(start_time), | ||
| "-i", | ||
| path, | ||
| "-fs", | ||
| str(split_size), | ||
| "-map_chapters", | ||
| "-1", | ||
| "-c", | ||
| "copy", | ||
| out_path, | ||
| ] | ||
| ) | ||
| if noMap | ||
| else Popen( | ||
| [ | ||
| "ffmpeg", | ||
| "-hide_banner", | ||
| "-loglevel", | ||
| "error", | ||
| "-ss", | ||
| str(start_time), | ||
| "-i", | ||
| path, | ||
| "-fs", | ||
| str(split_size), | ||
| "-map", | ||
| "0", | ||
| "-map_chapters", | ||
| "-1", | ||
| "-c", | ||
| "copy", | ||
| out_path, | ||
| ] | ||
| ) | ||
| ) |
There was a problem hiding this comment.
Function split_file refactored with the following changes:
- Replace if statement with if expression (
assign-if-exp) - Swap if/else branches of if expression to remove negation (
swap-if-expression)
| flink = info_parsed["gdrive_link"] | ||
| return flink | ||
|
|
||
| return info_parsed["gdrive_link"] | ||
| elif urlparse(url).netloc == "driveapp.in": | ||
| res = client.get(info_parsed["gdrive_link"]) | ||
| drive_link = etree.HTML(res.content).xpath("//a[contains(@class,'btn')]/@href")[ | ||
| 0 | ||
| ] | ||
| flink = drive_link | ||
| return flink | ||
|
|
||
| return etree.HTML(res.content).xpath( | ||
| "//a[contains(@class,'btn')]/@href" | ||
| )[0] | ||
| else: | ||
| res = client.get(info_parsed["gdrive_link"]) | ||
| drive_link = etree.HTML(res.content).xpath( | ||
| return etree.HTML(res.content).xpath( | ||
| "//a[contains(@class,'btn btn-primary')]/@href" | ||
| )[0] | ||
| flink = drive_link | ||
| return flink |
There was a problem hiding this comment.
Function unified refactored with the following changes:
- Simplify conditional into switch-like form [×3] (
switch) - Hoist repeated code outside conditional statement (
hoist-statement-from-if) - Inline variable that is immediately returned [×2] (
inline-immediately-returned-variable) - Lift return into if (
lift-return-into-if)
| info_parsed = {} | ||
| if 'drivebuzz' in url: | ||
| info_chunks = re_findall('<td\salign="right">(.*?)<\/td>', res.text) | ||
| else: | ||
| info_chunks = re_findall(">(.*?)<\/td>", res.text) | ||
| for i in range(0, len(info_chunks), 2): | ||
| info_parsed[info_chunks[i]] = info_chunks[i + 1] | ||
| return info_parsed | ||
| return { | ||
| info_chunks[i]: info_chunks[i + 1] | ||
| for i in range(0, len(info_chunks), 2) | ||
| } |
There was a problem hiding this comment.
Function parse_info refactored with the following changes:
- Move assignment closer to its usage within a block (
move-assign-in-block) - Convert for loop into dictionary comprehension (
dict-comprehension) - Inline variable that is immediately returned (
inline-immediately-returned-variable)
| if 'katdrive' or 'hubdrive' in url: | ||
| client = requests.Session() | ||
| else: | ||
| client = cloudscraper.create_scraper(delay=10, browser='chrome') | ||
|
|
||
| client = requests.Session() |
There was a problem hiding this comment.
Function udrive refactored with the following changes:
- Remove redundant conditional [×2] (
remove-redundant-if) - Merge duplicate blocks in conditional (
merge-duplicate-blocks) - Inline variable that is immediately returned [×3] (
inline-immediately-returned-variable)
| def sharer_pw_dl(url: str)-> str: | ||
| def sharer_pw_dl(url: str) -> str: | ||
|
|
||
| client = cloudscraper.create_scraper(delay=10, browser='chrome') | ||
| client.cookies["XSRF-TOKEN"] = config_dict['XSRF_TOKEN'] | ||
| client.cookies["laravel_session"] = config_dict['laravel_session'] | ||
|
|
||
| res = client.get(url) | ||
| token = re_findall("_token\s=\s'(.*?)'", res.text, DOTALL)[0] | ||
| data = { '_token': token, 'nl' :1} | ||
| headers={ 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8', 'x-requested-with': 'XMLHttpRequest'} | ||
|
|
||
| try: | ||
| response = client.post(url+'/dl', headers=headers, data=data).json() | ||
| response = client.post(f'{url}/dl', headers=headers, data=data).json() | ||
| drive_link = response | ||
| return drive_link['url'] | ||
|
|
||
| except: | ||
| if drive_link["message"] == "OK": | ||
| raise DirectDownloadLinkException("Something went wrong. Could not generate GDrive URL for your Sharer Link") | ||
| else: | ||
| finalMsg = BeautifulSoup(drive_link["message"], "lxml").text | ||
| raise DirectDownloadLinkException(finalMsg) | ||
| finalMsg = BeautifulSoup(drive_link["message"], "lxml").text | ||
| raise DirectDownloadLinkException(finalMsg) |
There was a problem hiding this comment.
Function sharer_pw_dl refactored with the following changes:
- Use f-string instead of string concatenation (
use-fstring-for-concatenation) - Remove unnecessary else after guard condition (
remove-unnecessary-else)
|
|
||
| resp = scrapper.post(f'https://{urlparse(url).netloc}/post', headers=headers, data=data, cookies=cookies) | ||
| toJson = resp.json() | ||
|
|
||
| if toJson['message'] in successMsgs: | ||
| return toJson['redirect'] | ||
| if directLogin==True: | ||
| if toJson['message'] in successMsgs: | ||
| driveUrl = toJson['redirect'] | ||
| return driveUrl | ||
| else: | ||
| shareDrive(url,directLogin=False) | ||
| shareDrive(url,directLogin=False) | ||
| else: | ||
| if toJson['message'] in successMsgs: | ||
| driveUrl = toJson['redirect'] | ||
| return driveUrl | ||
| else: | ||
| raise DirectDownloadLinkException("ERROR! File Not Found or User rate exceeded !!") | ||
| raise DirectDownloadLinkException("ERROR! File Not Found or User rate exceeded !!") |
There was a problem hiding this comment.
Function shareDrive refactored with the following changes:
- Hoist nested repeated code outside conditional statements (
hoist-similar-statement-from-if) - Remove unnecessary else after guard condition (
remove-unnecessary-else) - Inline variable that is immediately returned (
inline-immediately-returned-variable)
| flink = prun(playwright, link) | ||
| return flink | ||
| return prun(playwright, link) |
There was a problem hiding this comment.
Function filepress refactored with the following changes:
- Inline variable that is immediately returned (
inline-immediately-returned-variable)
| msg += f'\n#Buy Paid Service' | ||
| __onDownloadError(msg, client, tor) | ||
| return | ||
| limit = None |
There was a problem hiding this comment.
Function __check_limits refactored with the following changes:
- Remove unreachable code (
remove-unreachable-code)
| except (KeyError, IndexError): | ||
| msg = "Google Drive ID could not be found in the provided link" | ||
| return msg | ||
| return "Google Drive ID could not be found in the provided link" |
There was a problem hiding this comment.
Function GoogleDriveHelper.deletefile refactored with the following changes:
- Inline variable that is immediately returned (
inline-immediately-returned-variable)
| LOGGER.info("Created G-Drive Folder:\nName: {}\nID: {} ".format(file.get("name"), file_id)) | ||
| LOGGER.info( | ||
| f'Created G-Drive Folder:\nName: {file.get("name")}\nID: {file_id} ' | ||
| ) |
There was a problem hiding this comment.
Function GoogleDriveHelper.__create_directory refactored with the following changes:
- Replace call to format with f-string (
use-fstring-for-formatting)
| download_url = self.__G_DRIVE_BASE_DOWNLOAD_URL.format(drive_file.get('id')) | ||
| return download_url | ||
| return self.__G_DRIVE_BASE_DOWNLOAD_URL.format(drive_file.get('id')) |
There was a problem hiding this comment.
Function GoogleDriveHelper.__upload_file refactored with the following changes:
- Inline variable that is immediately returned [×2] (
inline-immediately-returned-variable)
| size /= power | ||
| n += 1 | ||
| return str(round(size, 2)) + " " + Dic_powerN[n] + "iB" | ||
| return f"{str(round(size, 2))} {Dic_powerN[n]}iB" |
There was a problem hiding this comment.
Function HumanBytes refactored with the following changes:
- Use f-string instead of string concatenation [×3] (
use-fstring-for-concatenation)
| seconds, milliseconds = divmod(int(milliseconds), 1000) | ||
| seconds, milliseconds = divmod(milliseconds, 1000) | ||
| minutes, seconds = divmod(seconds, 60) | ||
| hours, minutes = divmod(minutes, 60) | ||
| days, hours = divmod(hours, 24) | ||
| tmp = ((str(days) + "d, ") if days else "") + \ | ||
| ((str(hours) + "h, ") if hours else "") + \ | ||
| ((str(minutes) + "m, ") if minutes else "") + \ | ||
| ((str(seconds) + "s, ") if seconds else "") + \ | ||
| ((str(milliseconds) + "ms, ") if milliseconds else "") | ||
| tmp = ( | ||
| (f"{str(days)}d, " if days else "") | ||
| + (f"{str(hours)}h, " if hours else "") | ||
| + (f"{str(minutes)}m, " if minutes else "") | ||
| + (f"{str(seconds)}s, " if seconds else "") | ||
| + (f"{str(milliseconds)}ms, " if milliseconds else "") | ||
| ) |
There was a problem hiding this comment.
Function TimeFormatter refactored with the following changes:
- Remove unnecessary casts to int, str, float or bool (
remove-unnecessary-cast) - Use f-string instead of string concatenation [×5] (
use-fstring-for-concatenation)
| file = None | ||
| media_array = [mediamessage.document, mediamessage.video, mediamessage.audio, mediamessage.document, \ | ||
| mediamessage.video, mediamessage.photo, mediamessage.audio, mediamessage.voice, \ | ||
| mediamessage.animation, mediamessage.video_note, mediamessage.sticker] | ||
| for i in media_array: | ||
| if i is not None: | ||
| file = i | ||
| break | ||
| file = next((i for i in media_array if i is not None), None) |
There was a problem hiding this comment.
Function hash refactored with the following changes:
- Replace assignment and augmented assignment with single assignment (
merge-assign-and-aug-assign) - Move assignment closer to its usage within a block (
move-assign-in-block) - Replace call to format with f-string [×7] (
use-fstring-for-formatting) - Use the built-in function
nextinstead of a for-loop (use-next)
This removes the following comments ( why? ):
# hash text
| movie = imdb.get_movie(movieid) | ||
| if not movie: | ||
| if movie := imdb.get_movie(movieid): | ||
| buttons.sbutton(f"🎬 {movie.get('title')} ({movie.get('year')})", f"imdb {user_id} movie {movieid}") | ||
| else: | ||
| return editMessage("<i>No Results Found</i>", k) | ||
| buttons.sbutton(f"🎬 {movie.get('title')} ({movie.get('year')})", f"imdb {user_id} movie {movieid}") |
There was a problem hiding this comment.
Function imdb_search refactored with the following changes:
- Use named expression to simplify assignment and conditional (
use-named-expression) - Lift code into else after jump in control flow (
reintroduce-else) - Swap if/else branches (
swap-if-else-branches)
| plot = plot[0] | ||
| else: | ||
| plot = movie.get('plot outline') | ||
| plot = plot[0] if plot and len(plot) > 0 else movie.get('plot outline') |
There was a problem hiding this comment.
Function get_poster refactored with the following changes:
- Replace if statement with if expression (
assign-if-exp)
Thanks for starring sourcery-ai/sourcery ✨ 🌟 ✨
Here's your pull request refactoring your most popular Python repo.
If you want Sourcery to refactor all your Python repos and incoming pull requests install our bot.
Review changes via command line
To manually merge these changes, make sure you're on the
masterbranch, then run: