Compare commits

..

6 Commits

Author SHA1 Message Date
5a59ee60f3 [Change] Changed documentation after applying dacav's patches. 2025-04-22 23:49:15 +01:00
dacav
034d4a58d5 Add curl options: -S and -f
-S = show error, very useful with -s
-f = fail on error
2025-04-22 22:54:56 +01:00
dacav
0cff8e7c41 Drop unnecessary trap
If we are using a file, the trap is not defined in the first place,
so we don't need to undefined it.
2025-04-22 22:54:56 +01:00
dacav
86fbb6daba Wayland support
The clipboard= configuration file determines what clipboard manager should be
used, if xclip or wl-copy/wl-paste.  The variable defaults to the value of
XDG_SESSION_TYPE which is considered a reliable method to determine what
graphical session is currently being used[1]

[1] https://unix.stackexchange.com/a/355476
2025-04-22 22:54:56 +01:00
dacav
da20b17526 Add 'die' function
Candidate replacement of multiple instances of the same error
handling sequence.
2025-04-22 22:54:56 +01:00
dacav
14c467a764 Replace ~/.config/imgbb_uploader/api_key with generic config file
The configuration is stored under ~/.config/imgbb_uploader.conf.
The file is simply sourced, so the configuration file can be
a shell script. It just needs to assign the required variables.
2025-04-22 22:54:56 +01:00
2 changed files with 128 additions and 66 deletions

View File

@ -6,6 +6,8 @@ Ideal for quickly sharing screenshots or images in environments like IRC without
**Author:** Ritchie Cunningham <ritchie@ritchiecunningham.co.uk> **Author:** Ritchie Cunningham <ritchie@ritchiecunningham.co.uk>
**Contributors:** dacav <dacav@fastmail.com>
**Version:** 1.0 (as of 22/04/2025) **Version:** 1.0 (as of 22/04/2025)
## Features ## Features
@ -30,10 +32,11 @@ Make sure you have the following command-line tools installed:
```bash ```bash
sudo apt install jq # Debian. sudo apt install jq # Debian.
``` ```
* **xclip:** Used for accessing the X11 clipboard. **This script will not work on Wayland sessions.** * **xclip:** Used for accessing the X11 clipboard. **This is for X11. Wayland users, see below..**
```bash ```bash
sudo apt install xclip # Debian. sudo apt install xclip # Debian.
``` ```
* **wl-clipboard** Used for accessing the Wayland clipboard. **This is for Wayland. X11 users, see above.**
* **notify-send (Optional):** Used for desktop notifications. The script works without it but won't show popups. * **notify-send (Optional):** Used for desktop notifications. The script works without it but won't show popups.
```bash ```bash
sudo apt install notify-send # Debian (often in libnotify-bin). sudo apt install notify-send # Debian (often in libnotify-bin).
@ -55,22 +58,25 @@ Make sure you have the following command-line tools installed:
mkdir -p ~/.local/bin mkdir -p ~/.local/bin
ln -s "$(pwd)/imgbb" ~/.local/bin/imgbb ln -s "$(pwd)/imgbb" ~/.local/bin/imgbb
``` ```
Now you can just run `imgbb` from your terminal.
## Configuration ## Configuration
This script requires a **free API key** from ImgBB: This script requires a **free API key** from ImgBB:
1. Go to [https://api.imgbb.com/](https://api.imgbb.com/) and register or log in to get your key. 1. Go to [https://api.imgbb.com/](https://api.imgbb.com/) and register or log in to get your key.
2. Store the key in `.config/imgbb/uploader/api_key`. 2. Set the API key using *one* of these methods (script checks in this order):
* **File** Create the directory and file, then paste *only* your API key inside: * Store the key in `.config/imgbb/uploader/api_key`.
```bash * **File** Create the config file `~/.config/imgbb_uploader.conf` and add a line like:
mkdir -p ~/.config/imgbb_uploader ```bash
nano ~/.config/imgbb_uploader/api_key echo "api_key="YOUR_KEY_HERE" > ~/.config/imgbb_uploader.conf
# Paste your key, save the file. # Set permissions so only you can read it:
# Set permissions so only you can read it: chmod 600 ~/.config/imgbb_uploader.conf
chmod 600 ~/.config/imgbb_uploader/api_key ```
``` * **Environment Variable:** Set the `IMGBB_API_KEY` variable in your environment
```bash
export IMGBB_API_KEY="YOUR KEY HERE"
```
Now you can just run `imgbb` from your terminal.
## Usage ## Usage
**Options:** **Options:**
@ -104,7 +110,8 @@ imgbb -h
# Notes # Notes
Currently relies on xclip and therefore only works reliably under X11 sessions. Wayland support would require adding logic to use wl-clipboard. - Supports both X11 (using xclip) and Wayland (using wl-clipboard) sessions. It detects the session type using $XDG_SESSION_TYPE.
# License # License

161
imgbb
View File

@ -5,8 +5,9 @@
# to ImgBB (imgbb.com) using their V1 API. Retrieves the direct # to ImgBB (imgbb.com) using their V1 API. Retrieves the direct
# image URL, prints it to stdout, and copies it to the X11 clipboard. # image URL, prints it to stdout, and copies it to the X11 clipboard.
# Author: Ritchie Cunningham <ritchie@ritchiecunningham.co.uk> # Author: Ritchie Cunningham <ritchie@ritchiecunningham.co.uk>
# License: GPL License # Contributors: dacav <dacav@fastmail.com>
# Version: 3.0 # License: GPL 3.0 License
# Version: 1.2
# Date: 22/04/2025 # Date: 22/04/2025
# ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------
# Usage Examples: # Usage Examples:
@ -23,26 +24,36 @@
# - bash (v4+ required for =~, (( )), BASH_REMATCH) # - bash (v4+ required for =~, (( )), BASH_REMATCH)
# - curl: (e.g., sudo apt install curl) # - curl: (e.g., sudo apt install curl)
# - jq: (e.g., sudo apt install jq) # - jq: (e.g., sudo apt install jq)
# - xclip: (X11 clipboard access) (e.g., sudo apt install xclip) # - Clipboard tool:
# - xclip: (X11 clipboard access) (e.g., sudo apt install xclip)
# - wl-clipboard (For Wayland clipboard access) (e.g., sudo apt install wl-clipboard)
# - notify-send: (Optional, for desktop notifications) (e.g., sudo apt install notify-send) # - notify-send: (Optional, for desktop notifications) (e.g., sudo apt install notify-send)
# - Coreutils: (mktemp, basename, rm, cat, echo, etc. - usually standard) # - Coreutils: (mktemp, basename, rm, cat, echo, etc. - usually standard)
# ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------
# Configuration: # Configuration:
# Requires an ImgBB API key (v1). Get one free: https://api.imgbb.com/ # Requires an ImgBB API key (v1). Get one free: https://api.imgbb.com/
# Store the key: # Set the API key using ONE of these methods (checked in this order):
# - File: ~/.config/imgbb_uploader/api_key (chmod 600 recommended) # 1. Environment Variable: IMGBB_API_KEY="YOUR KEY HERE"
# (Create directory: mkdir -p ~/.config/imgbb_uploader) # 2. Config File: Create ~/.config/imgbb_uploader.conf and add a line like:
# api_key="YOUR_KEY_HERE"
# (We'll soon have other defaults to set here).
# ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------
# Notes: # Notes:
# - Uses 'xclip', works on X11 sessions only. Wayland requires 'wl-clipboard'. # - Supports both X11 (using xclip) and Wayland (using wl-clipboard) sessions.
# It detects the session type using $XDG_SESSION_TYPE.
# ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------
# === Default Configuration & Argument Parsing. === # === Default Configuration & Argument Parsing. ===
API_KEY_FILE="$HOME/.config/imgbb_uploader/api_key"
api_key=""
config_file="$HOME/.config/imgbb_uploader.conf"
filepath="" filepath=""
expire_seconds="7200" # 2h - Set to "" for no expiry. or use flag -e 0, never or none. expire_seconds="7200" # 2h - Set to "" for no expiry. or use flag -e 0, never or none.
custom_name="" custom_name=""
markdown_mode="false" markdown_mode="false"
clipboard="$XDG_SESSION_TYPE"
[ ! -e "$config_file" ] || . "$config_file"
print_usage() { print_usage() {
echo "Usage: $(basename "$0") [options] [filepath]" echo "Usage: $(basename "$0") [options] [filepath]"
@ -59,6 +70,15 @@ print_usage() {
echo " -h, --help Show this help message." echo " -h, --help Show this help message."
} }
die() {
declare msg
msg="$*"
notify_cmd -u critical "ImgBB Upload Error" "$msg" &>/dev/null
echo "$msg" >&2
exit 1
}
# Parse command-line options. # Parse command-line options.
while [[ $# -gt 0 ]]; do while [[ $# -gt 0 ]]; do
key="$1" key="$1"
@ -79,7 +99,7 @@ while [[ $# -gt 0 ]]; do
unit="${BASH_REMATCH[2]}" # The unit part. unit="${BASH_REMATCH[2]}" # The unit part.
# Default to minutes if no unit was provided. # Default to minutes if no unit was provided.
if [ -z "$unit" ]; then unit="s"; fi if [ -z "$unit" ]; then unit="m"; fi
# Calculate total seconds based on the unit. # Calculate total seconds based on the unit.
case "$unit" in case "$unit" in
@ -151,19 +171,16 @@ if [ -n "$filepath" ] && [ ! -r "$filepath" ]; then
fi fi
# === Read API Key. === # === Read API Key. ===
API_KEY="" if [[ -n "$IMGBB_API_KEY" ]]; then
if [[ -f "$API_KEY_FILE" ]]; then api_key="$IMGBB_API_KEY"
API_KEY=$(cat "$API_KEY_FILE")
elif [[ -n "$IMGBB_API_KEY" ]]; then
API_KEY="$IMGBB_API_KEY"
fi fi
# Check if API key is actually set. # Check if API key is actually set.
if [ -z "$API_KEY" ]; then if [ -z "$api_key" ]; then
# Use function defined below if notify-send exists. # Use function defined below if notify-send exists.
notify_cmd -u critical "ImgBB Upload Error" "API Key not found." &>/dev/null notify_cmd -u critical "ImgBB Upload Error" "API Key not found." &>/dev/null
echo "Error: API Key not found." >&2 echo "Error: API Key not found." >&2
echo "Please store your key in '$API_KEY_FILE' or set the IMGBB_API_KEY environment variable." >&2 echo "Please store your key in '$config_file' or set the IMGBB_API_KEY environment variable." >&2
exit 1 exit 1
fi fi
@ -185,12 +202,70 @@ fi
# Now check other dependencies. # Now check other dependencies.
check_command curl check_command curl
check_command jq check_command jq
# Only check xclip if we plan to use the clipboard. # Only check the clipboard command if we plan to use the clipboard.
if [ -z "$filepath" ]; then if [ -z "$filepath" ]; then
case "$clipboard" in
x11)
check_command xclip check_command xclip
;;
wayland)
check_command wl-paste
;;
*)
die "Unsupported clipboard: $clipboard"
esac
fi fi
# === Main Logic. === # === Main Logic. ===
paste_x11() {
declare tmp
tmp_img="$(mktemp)" || die "Could not create temp file."
xclip -selection clipboard -t image/png -o >"$tmp_img" 2>/dev/null
if [ -s "$tmp_img" ]; then
mv "$tmp_img" "$tmp_img.png"
printf "%s\n" "$tmp_img.png"
return 0
fi
xclip -selection clipboard -t image/jpeg -o >"$tmp_img" 2>/dev/null
if [ -s "$tmp_img" ]; then
mv "$tmp_img" "$tmp_img.jpeg"
printf "%s\n" "$tmp_img.jpeg"
return 0
fi
rm -f "$tmp_img"
die "Could not get PNG or JPEG image data from clipboard."
}
paste_wl() {
declare tmp_img
declare format
format="$(wl-paste -l | grep -m1 -F -e image/png -e image/jpeg)" ||
die "Invalid file type in clipboard."
tmp_img="$(mktemp)" || die "Could not create temp file."
if wl-paste -t "$format" >"$tmp_img" 2>/dev/null; then
mv "$tmp_img" "$tmp_img.${format##image/}"
printf "%s\n" "$tmp_img.${format##image/}"
return 0
fi
rm -f "$tmp_img"
die "Could not get PNG or JPEG image data from clipboard."
}
yank_x11() {
xclip -selection clipboard
}
yank_wl() {
wl-copy
}
TMP_IMG="" # Path to the image file to upload. TMP_IMG="" # Path to the image file to upload.
image_source_description="" image_source_description=""
@ -198,43 +273,23 @@ image_source_description=""
if [ -z "$filepath" ]; then if [ -z "$filepath" ]; then
# === Clipboard Input Mode. === # === Clipboard Input Mode. ===
image_source_description="clipboard" image_source_description="clipboard"
# Create temporary file(s). TMP_IMG="$(
TMP_IMG_PNG=$(mktemp --suffix=.png) case "$clipboard" in
TMP_IMG_JPEG=$(mktemp --suffix=.jpg) x11) paste_x11;;
# Ensure temporary files are cleaned up on script exit. wayland) paste_wl;;
trap 'echo "Cleaning up temp files..."; rm -f "$TMP_IMG_PNG" "$TMP_IMG_JPEG"' EXIT esac
)" || exit
# Try extracting PNG image from clipboard. trap 'rm -f "$TMP_IMG"' EXIT
notify_cmd "ImgBB Uploader" "Getting image from clipboard..."
if xclip -selection clipboard -t image/png -o > "$TMP_IMG_PNG" 2>/dev/null && [ -s "$TMP_IMG_PNG" ]; then
echo "Retrieved PNG image from clipboard."
TMP_IMG="$TMP_IMG_PNG"
rm -f "$TMP_IMG_JPEG" # Remove unused JPEG temp file.
else
# If PNG fails or is empty, try JPEG.
echo "PNG failed or empty, trying JPEG..."
if xclip -selection clipboard -t image/jpeg -o > "$TMP_IMG_JPEG" 2>/dev/null && [ -s "$TMP_IMG_JPEG" ]; then
echo "Retrieved JPEG image from clipboard."
TMP_IMG="$TMP_IMG_JPEG"
rm -f "$TMP_IMG_PNG" # Remove unused PNG temp file.
else
# If both fail or are empty.
notify_cmd -u critical "ImgBB Upload Error" "Could not get PNG or JPEG image data from clipboard."
echo "Error: Could not get PNG or JPEG image data from clipboard." >&2
exit 1
fi
fi
else else
# === File Input Mode. === # === File Input Mode. ===
image_source_description="file '$filepath'" image_source_description="file '$filepath'"
TMP_IMG="$filepath" # Use the provided file path directly. TMP_IMG="$filepath" # Use the provided file path directly.
echo "Using image from file: $filepath" echo "Using image from file: $filepath"
trap '' EXIT # Clear trap if we are not using temp files.
fi fi
# Build curl options. # Build curl options.
curl_opts=(-s -L -X POST) curl_opts=(-s -S -f -L -X POST)
curl_opts+=(--form "key=$API_KEY") curl_opts+=(--form "key=$api_key")
curl_opts+=(--form "image=@$TMP_IMG") curl_opts+=(--form "image=@$TMP_IMG")
if [ -n "$expire_seconds" ]; then if [ -n "$expire_seconds" ]; then
@ -290,14 +345,14 @@ fi
# Output the URL to terminal and copy to clipboard. # Output the URL to terminal and copy to clipboard.
echo "Image URL:" echo "Image URL:"
echo "$output_url" echo "$output_url"
# Use xclip only if we determined we are not uploading from file (i.e., we used clipboard input) # Copy URL only if we determined we are not uploading from file (i.e., we used clipboard input)
# Or always copy? Let's always copy for now. # Or always copy? Let's always copy for now.
if command -v xclip &> /dev/null; then
echo "$output_url" | xclip -selection clipboard case "$clipboard" in
notify_cmd "ImgBB Uploader" "Success! URL copied: $output_url" x11) printf "%s\n" "$output_url" | yank_x11;;
else wayland) printf "%s\n" "$output_url" | yank_wl;;
notify_cmd "ImgBB Uploader" "Success! URL: $output_url" esac
fi notify_cmd "ImgBB Uploader" "Success! URL copied: $output_url"
# Temporary files are removed automatically by the 'trap' command on exit if they were created. # Temporary files are removed automatically by the 'trap' command on exit if they were created.
exit 0 exit 0