Skip to content

Suzhou65/Status4HaH

Repository files navigation

Status4HaH

python UA Size

Status check for Hentai@Home Client.

Contents

Development Purpose

  • Supervise operational status of multiple Hentai@Home clients and dispatch alerts upon detecting offline conditions. It transmission the offline alerts either as a one-only notification or continuous mode. Alerts may be dispatched through email or Telegram.
  • Also support export client status data, with the default setting separate data files on client IDs.

Security and Disclaimer

Security
Although the password inside the cookie has been hashed, if someone modifies the script, add a backdoor function to send it back.
It's possible to login to your account without knowing the actual username and password.

Disclaimer
The original Status4HaH won't have those functions or backdoor.
Please make sure you download the clean copy from this repository.

Limitation

Alert function
If the Once-only mode is set for alert function, no more alerts will be delivered. Even if more Hentai@Home clients offline during after alert sending, alert function will enable again after Hentai@Home clients come back online. Same thing happens when webpage parsing errors or network errors happen.

Reduce dependencies about non-default Python modules
To reduce dependencies on non-default module inside Python Standard Library, pandas-related code were removed during OOP refactoring. Currently output at HentaiAtHome.CheckHentaiatHome() is standard Python list object contains dictionary, rather than pandas.DataFrame object.

Usage

E-Hentai

Using cookies to login
If your browser is Chrome-based (ex. Google Chrome or Microsoft Edge), right-click to open Developer Tools and switch to the Network panel. After refreshing the Hentai@Home page, click the element called hentaiathome.php, which tags cookies. You can find ipb_member_id and ipb_pass_hash. please fill into the configuration file.

HTTP User-Agent Header
Pleae copy your browser's User-Agent, fill into the configuration file.

Hentai@Home

You should already running Hentai@Home client.

Scheduling

Using Crontab for job scheduling. systemd also recommended.

#MIM HOUR DAY MONTH WEEK
*/30  *    *    *    *    root  python /script_path/status_notification.py

Avoiding for making heavy server load on E-Hentai
Not recommended for change less then 30 minutes.

Email alert

Using Gmail as default. configuration at line 24 to 25.

# Web and mail config
class Link():
    def __init__(self):
        self.HentaiAtHome = "https://e-hentai.org/hentaiathome.php"
        self.Telegram     = "https://api.telegram.org/bot"
        self.SMTPServer   = "smtp.gmail.com"
        self.SMTPPort     =  587

Mail server configuration
Google account needed, sign in using App passwords, receiver mail address is unlimited.
You may replace it with any other mail server that supports SMTP.

Mail configuration as following parameters:

   "Mail": {
    "Sender": "",
    "Scepter": "",
    "Receiver": ""
   }

Configuration file
Sender is Google account.
Scepter is Google App passwords.
Receiver is receiver mail address.

Telegram alert

Telegram configuration as following parameters:

   "Telegram_BOTs": {
      "Token": "",
      "ChatID": ""
   },

Configuration:
Token is BOTs Token.
ChatID is channel ID.

For using Telegram Bot, contect BotFather create new Bot accounts.

Fail-silent mode
Please notice, even Bot was created, at this point chat channel wasn't created.
So you can't find the ChatID.

Without ChatID, running Alert.Telegram() function will receive 400 Bad Request from Telegram API, following message will printout:

19:19:00 | Telegram ChatID is empty, notifications will not be sent.

You need to start the chat channel with that bot, i.e. say Hello the world to him. Then running Alert.GetTelegramChatID()

import status4haha
ConfigFilePath = "/Documents/script/status4hah.config.json"
Al = status4haha.Alert(ConfigFilePath)
Al.GetTelegramChatID()

Now ChatID will printout:

19:19:18 | You ChatID is: XXXXXXXXX

Configuration file

Using JSON format file storage configuration. Configuration file must include following parameters:

{
  "EHentai": {
    "UserAgent": "",
    "ipb_member_id": "",
    "ipb_pass_hash": "",
    "TableHeader": [
      "Client","ID","Status","Created","Last Seen",
      "Files Served","Client IP","Port","Version","Max Speed",
      "Trust","Quality","Hitrate","Hathrate","Region"]
  },
  "RuntimeStatus": {
    "StatusPath": "/Documents/script/status4hah.runtime.csv"
  },
  "DisplayDrop": { 
    "OutputPath": "/Documents/script/status4hah.status.csv",
    "Filter": ["ID","Created","Client IP","Port"]
  },
  "Recording":{
    "StatusRecord": false,
    "RecordingPath": "/Documents/script/record/"
  },
  "Alert": {
    "Mode": false,
    "ContinuousAlert": true
   },
   "Telegram_BOTs": {
      "Token": "",
      "ChatID": ""
   },
   "Mail": {
    "Sender": "",
    "Scepter": "",
    "Receiver": ""
   }
}

TableHeader
Reference to Hentai@Home page, GM may change the element or sequence of clients status table.

RuntimeStatus
Offline notification script runtime display.

DisplayDrop
Hentai@Home clients status output.
List Filter for dropping sensitive keys.

Recording
Output Hentai@Home clients status, useful when deploy new client.

Import module

# Import as module
import status4hentai
# Alternative
import status4hentai as s4h

Function

Get HentaiAtHome status

import status4hentai as s4h

# Configuration file path
ConfigFilePath = "/Documents/script/status4hah.config.json"

Eh = s4h.EHentai(ConfigFilePath)
Rt = s4h.Runtime(ConfigFilePath)
# Get Hentai@Home status
ClientStatus = Eh.CheckHentaiatHome()
# Error
if isinstance(ClientStatus, bool):
  Rt.StatusRuntime("Error occurred during connect to E-hentai.")
# E-Hentai server HTTP error
elif isinstance(ClientStatus, int):
  Rt.StatusRuntime(f"E-Hentai Server Error: {ClientStatus}")
# E-Hentai Logout
elif isinstance(ClientStatus, str):
  Rt.StatusRuntime(ClientStatus)
# Get Hentai@Home status
elif isinstance(ClientStatus, list):
  print(ClientStatus)

Output type:
list object meaning BS4 parsing HTML content correctly, it will send back client status with list contains dictionary.
String meaning account logout.
Integer meaning HTTP status codes, mostly E-Hentai server or Cloudflare CDN issue.
Booleanmeaning undefined error, please review the error handling in error.status4hah.log.

Drop sensitive keys

To hide sensitive data, such as IP addresses and port numbers, using sensitive keys dropping is recommended.

Default
Client ID, Created time, IP address and port are filtered out by default.

Rt = s4h.Runtime(ConfigFilePath)
Rt.StatusKeyDrop(ClientStatus)

Configuration file
Filter parameters can be adjusted in the JSON configuration file.

  "DisplayDrop": { 
    "OutputPath": "/var/www/html/status4hah.status.csv",
    "Filter": ["ID","Created","Client IP","Port"]
  },

Disable
If filtering is not desired, set the corresponding option to false.

  "DisplayDrop": { 
    "OutputPath": "/var/www/html/status4hah.status.csv",
    "Filter": false
  },

Fail-safe
If the configuration is invalid, Minimum sensitive keys dropping will be enable, and a warning will be recorded in error.status4hah.log.

Offline notification

Demonstration script named status_notification.py.

import status4hentai as s4h
from sys import exit

# Configuration file path
ConfigFilePath = "/Documents/script/status4hah.config.json"
# Script
def main():
    Rt = s4h.Runtime(ConfigFilePath)
    Eh = s4h.EHentai(ConfigFilePath)
    Al = s4h.Alert(ConfigFilePath)
    # Get Hentai@Home status
    ClientStatus = Eh.CheckHentaiatHome()
    # Error
    if isinstance(ClientStatus, bool):
        raise Exception()
    # E-Hentai server HTTP error
    elif isinstance(ClientStatus, int):
        raise Exception()
    # E-Hentai Logout
    elif isinstance(ClientStatus, str):
        Al.Alarm(ClientStatus)
        raise Exception()
    # Get Hentai@Home status
    elif isinstance(ClientStatus, list):
        pass
    # Undefined error
    else:
        raise Exception()
    # Check online status
    OfflineClient = Eh.OfflineChecker(ClientStatus)
    if isinstance(OfflineClient, bool):
        raise Exception()
    elif isinstance(OfflineClient, list):
        if len(OfflineClient) == 0:
            # Delete continuous alert blocker
            Al.RemoveObstacle()
        else:
            OfflineNotify = (f"Hentai@Home client offline.\r\nClient Name: {OfflineClient}")
            Al.Alarm(OfflineNotify)
# Runtime
if __name__ == "__main__":
    try:
        main()
    except Exception:
        exit(0)

Mail or Telegram
Support mail or Telegram, by set the Mode option to Mail or Telegram.

  "Alert": {
    "Mode": "Telegram",
    "ContinuousAlert": true
   },

Disable alert
Set the Mode option to false will disable alert function.

  "Alert": {
    "Mode": false,
    "ContinuousAlert": true
   },

Continuous mode
Support once-only or continuous alert mode.
Set the ContinuousAlert option to true will enable continuous mode.

  "Alert": {
    "Mode": "Telegram",
    "ContinuousAlert": true
   },

Once-only mode
Set the ContinuousAlert option to str with CSV file path will enable once-only mode.

  "Alert": {
    "Mode": "Telegram",
    "ContinuousAlert": "/Documents/script/status4hah.obstacle.csv"
   },

Status recorder

Demonstration script named status_recorder.py.

import status4hentai as s4h
from sys import exit

# Configuration file path
ConfigFilePath = "/Documents/script/status4hah.config.json"
# Script
def main():
    Rt = s4h.Runtime(ConfigFilePath)
    Eh = s4h.EHentai(ConfigFilePath)
    # Get Hentai@Home status
    ClientStatus = Eh.CheckHentaiatHome()
    # Error
    if isinstance(ClientStatus, bool):
        raise Exception()
    # E-Hentai server HTTP error
    elif isinstance(ClientStatus, int):
        raise Exception()
    # E-Hentai Logout
    elif isinstance(ClientStatus, str):
        raise Exception()
    # Get Hentai@Home status
    elif isinstance(ClientStatus, list):
        # Drop key
        Rt.StatusKeyDrop(ClientStatus)
        # Writing into CSV file
        Rt.StatusRecorder(ClientStatus)
    # Undefined error
    else:
        Rt.Message(f"Undefined error occurred.")
        raise Exception()
# Runtime
if __name__ == "__main__":
    try:
        main()
    except Exception:
        exit(0)

Web Based Monitor

status_monitor.php is a simple php script webpage to view the status file output via status_notification.py.

Demonstration
See the Demonstration page.

Dependencies

Python version

Testing passed on above Python version:

  • 3.7.3
  • 3.9.2
  • 3.9.6
  • 3.12.11

Python module

Module not included in Python Standard Library are needed.
No longer needed pandas after Commit 24c0b85.

  • logging
  • pathlib
  • json
  • datetime
  • textwrap
  • csv
  • requests
  • beautifulsoup
  • email
  • smtplib
  • pandas

Webpage

Apache or NGINX

PHP

Recommend using php-FPM.

  • 7.3 or above

License

General Public License -3.0

Resources

Beautiful Soup

About Hentai@Home

Install Hentai@Home

Stack Overflow

Screenshot

About

Status check for Hentai@Home Client

Topics

Resources

License

Stars

Watchers

Forks