quiethost

This commit is contained in:
Lucas Faber authored and Lucas Vivohost committed 2026-09-14 09:20:47 +02:00
1 parent 9c379af76b
commit b3c06c0a80
47 files changed
+2116

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
http-password = Mira2012
http-user = ll_
+39
View File
@@ -0,0 +1,39 @@
#!/bin/bash
if [ $# -lt 3 ]; then
echo "Usage <new_name> <new_cmd> <key_combo>"
exit 1;
fi
counter=0;
list="["
num=0
while read -r line; do
list="$list$(echo $line | sed 's/\]//g' | sed 's/\[//g'), "
ret="$(printf "%s\n" "$line" | grep "custom$counter")"
if [ "$ret" == "" ]; then
num=$counter
break;
else
(( counter++ ))
num=$counter;
fi
done < <(gsettings get org.gnome.settings-daemon.plugins.media-keys custom-keybindings | sed 's/, /\n/g')
key="org.gnome.settings-daemon.plugins.media-keys.custom-keybinding:"
custom="/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom$num/"
if [[ $list = *"@as"* ]]; then
list="['$custom']"
else
list="$list'$custom']"
fi
echo $list
new_name=$1
new_cmd=$2
key_combo=$3
echo "$key$custom $new_name $new_cmd $key_combo"
#key_str="$(xev)"
#echo $key_str | sed 's/KeyRelease/\nKeyRelease/g' | sed 's/KeyPress/\nKeyPress/g' | grep KeyPress | sed 's/keysym/\nkeysym/g'| sed 's/same_screen/\nsame_screen/g' | grep keysym | grep -o -P '(?<=, ).*(?=\),)' | sed 's/_L//g' | sed 's/_R//g'
#exit
gsettings set org.gnome.settings-daemon.plugins.media-keys custom-keybindings "$list"
gsettings set $key$custom name "$new_name"
gsettings set $key$custom command "$new_cmd"
gsettings set $key$custom binding "$key_combo"
+20
View File
@@ -0,0 +1,20 @@
FFMPEG="true"
if [ "$2" == "" ]; then
for file in *mp3; do
if [[ "${FFMPEG}" == "true" ]]; then
ffmpeg -i "$file" -i /home/lucas/Downloads/$1 -map 0:0 -map 1:0 -c copy -id3v2_version 3 -metadata:s:v title="Album cover" -metadata:s:v comment="Cover (front)" "$file.mp3"
else
lame --ti /home/lucas/Downloads/$1 "$file"
fi
mv "$file.mp3" "$file"
done
else
for file in "$2"; do
if [[ "${FFMPEG}" == "true" ]]; then
ffmpeg -i "$file" -i /home/lucas/Downloads/$1 -map 0:0 -map 1:0 -c copy -id3v2_version 3 -metadata:s:v title="Album cover" -metadata:s:v comment="Cover (front)" "$file.mp3"
else
lame --ti /home/lucas/Downloads/$1 "$file"
fi
mv "$file.mp3" "$file"
done
fi
+13
View File
@@ -0,0 +1,13 @@
#!/bin/bash
cp /home/lucas/files.txt /home/lucas/files1.txt
input="/tmp/rsync_files.txt"
while IFS= read -r var
do
echo "$var"
#var=$(echo $var
cat /home/lucas/files1.txt | grep -vF "$var" > /home/lucas/files2.txt
mv /home/lucas/files2.txt /home/lucas/files1.txt
#sleep 10
done < "$input"
while IFS= read -r var; do ls "$var" >/dev/null; done < /home/lucas/files1.txt
View File
Whitespace-only changes.
+12
View File
@@ -0,0 +1,12 @@
#!/bin/bash
for img in *; do
size=$(identify ${img} | cut -f3 -d' ')
if [[ "$(echo ${size} | grep 3546)" != "" ]]; then
echo $size
convert $img -crop 2448x3264+0+0 $(echo $img | sed 's/\.jpg/_c\.jpg/g')
mv $img $(echo $img | sed 's/\.jpg/_u\.jpg/g')
fi
done
+33
View File
@@ -0,0 +1,33 @@
#nmcli con down id VPN1
LOGFILE=/home/lucas/.LOG/deluged-log.log
exec >>$LOGFILE 2>&1
if [ "$(pgrep deluge)" != "" ]; then
date
VPN="$(nmcli con show --active | grep -i vpn) "
ret=$?
echo "${VPN}Status: $ret" | sed 's/ */ /g'
if [ $ret -ne 0 ]; then
echo "No VPN active. Starting VPN"
nmcli con up id VPN1
sleep 1
VPN="$(nmcli con show --active | grep vpn)"
ret=$?
echo "STATUS:$ret $VPN"
if [ $ret -ne 0 ]; then
echo "Starting VPN failed. Start killing all Deluge processes"
pkill deluged
pkill deluge-gtk
echo "Kill VPN and Restart network"
nmcli radio all off
nmcli radio all on
fi
else
echo "All in Order. Proceed as usual."
fi
fi
filesize=$(stat -c%s $LOGFILE)
if [ $filesize -gt 1000000 ]; then
line=$(( $(cat $LOGFILE | wc -l)/2 ))
echo "Filesize: $filesize: Delete Line 1 - $line"
sed -i "1,${line}d" $LOGFILE
fi
+5
View File
@@ -0,0 +1,5 @@
#!/bin/bash
if [ -f /etc/systemd/sleep.conf.orig ] && [ $1 == "post" ] && [ $2 == "hibernate" ]; then
mv /etc/systemd/sleep.conf.orig /etc/systemd/sleep.conf
fi
+3
View File
@@ -0,0 +1,3 @@
#!/bin/bash
sudo printf "[Sleep]\nHibernateMode=reboot\nHybridSleepMode=reboot\nSuspendMode=reboot\n" > /etc/systemd/sleep.conf
+16
View File
@@ -0,0 +1,16 @@
#!/bin/bash
IFS=$'\n'; set -f
ARR=($(find . \( -name "*.png" -or -name "*.jp*g" \) | grep -v xml))
unset IFS; set +f
for ((i=0;i<${#ARR[@]};i++)); do
NUM1=$(identify "${ARR[i]}" | rev | cut -f7 -d' ' | rev | cut -f1 -d'x')
NUM2=$(identify "${ARR[i]}" | rev | cut -f7 -d' ' | rev | cut -f2 -d'x')
echo "${ARR[i]}"
if [[ "$NUM1" != "" && $NUM2 != "" ]]; then
if [[ $NUM1 -gt $(( $NUM2 * 3 )) ]]; then
identify "${ARR[i]}" >> panoramaImages.txt
cp "${ARR[i]}" /home/lucas/Downloads/
fi
fi
done
+31
View File
@@ -0,0 +1,31 @@
#!/bin/bash
DATE="$(date +'%m%d%H%M%S')"
log="logfile_${DATE}.log"
IMG_DIR="/home/lucas/Pictures/"
PANORAMA_AR_LT="0.5"
PANORAMA_AR_HT="1.8"
> "${IMG_DIR}${log}"
getAspectRatio() {
if [ "$1" == "" ]; then return "0"; fi
identify "$1" | perl -ne '/(.+?)\s+[A-Z]{3,4}\s+(\d+)x(\d+)/; print $3/$2, "\n"'
if [ $? -ne 0 ]; then return "0"; fi
}
write_log() {
echo "$@"
echo "$@" >> "${IMG_DIR}${log}"
}
IFS=$'\n'; set -f
IMG_ARR=($(find ${IMG_DIR} -name '*.jp*g' -or -name '*.JP*G' -name '*.png'))
for IMG in ${IMG_ARR[@]}; do
imageAR=$(getAspectRatio ${IMG})
if [ "${imageAR}" != "" ]; then
if [ $(echo ${imageAR}'<'${PANORAMA_AR_LT} | bc -l) -eq 1 ] || [ $(echo ${imageAR}'>'${PANORAMA_AR_HT} | bc -l) -eq 1 ]; then
if [ $(identify -verbose ${IMG} | grep -o "Panorama" | wc -l) -eq 0 ]; then
write_log ${IMG} ${imageAR}
fi
fi
fi
done
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
workdir=${HOME}/shell-theme
if [ ! -d ${workdir}/theme ]; then
mkdir -p ${workdir}/theme
fi
gst=/usr/share/gnome-shell/gnome-shell-theme.gresource
for r in `gresource list $gst`; do
echo " gresource extract $gst $r >$workdir/${r#\/org\/gnome\/shell/}"
gresource extract $gst $r >$workdir/${r#\/org\/gnome\/shell/}
done
@@ -0,0 +1,481 @@
import sys
import json
import argparse
import logging
import os
import re
import time
from datetime import datetime
class ColoredFormatter(logging.Formatter):
# ANSI escape codes for colors
COLORS = {
"DEBUG": "\033[94m", # Blue
"INFO": "\033[92m", # Green
"WARNING": "\033[93m", # Yellow
"ERROR": "\033[91m", # Red
"CRITICAL": "\033[95m", # Magenta
"RESET": "\033[0m" # Reset
}
def format(self, record):
color = self.COLORS.get(record.levelname, self.COLORS["RESET"])
message = super().format(record)
return f"{color}{message}{self.COLORS['RESET']}"
def setup_logger(log_file=None, level=logging.DEBUG):
"""
Sets up a logger that logs messages to the console and optionally to a file.
Parameters:
log_file (str): Path to a log file. If None, only console logging is used.
level (int): Logging level (e.g., logging.INFO, logging.DEBUG, logging.ERROR).
Returns:
logging.Logger: Configured logger instance.
"""
logger = logging.getLogger(__name__)
logger.setLevel(level)
# Avoid adding multiple handlers if logger already exists
if not logger.handlers:
# Console handler (INFO and above)
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
ch_formatter = ColoredFormatter('%(asctime)s - %(levelname)s - %(message)s')
ch.setFormatter(ch_formatter)
logger.addHandler(ch)
# File handler (optional)
if log_file:
# Ensure the directory exists
os.makedirs(os.path.dirname(log_file), exist_ok=True)
fh = logging.FileHandler(log_file, mode='a')
fh.setLevel(level)
fh_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
fh.setFormatter(fh_formatter)
logger.addHandler(fh)
return logger
# -------- OpenAI --------
from openai import OpenAI
# -------- Gemini --------
from google import genai
# -------- Hugging Face --------
from huggingface_hub import InferenceClient
import requests
# -------------------------
# API Keys
# -------------------------
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") or "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"
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY") or "AIzaSyDRO5QyNa44eUsbfE5eQbMpjagO3398Ihs"
# -------------------------
# Hugging Face
# -------------------------
HF_API_KEY = os.getenv("HF_API_KEY") or "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"
HF_MODEL = "Qwen/Qwen2.5-7B-Instruct"
HF_API_URL = f"https://api-inference.huggingface.co/models/{HF_MODEL}"
# -------------------------
# Groq
# -------------------------
# export GROQ_API_KEY= "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"
GROQ_API_KEY = os.getenv("GROQ_API_KEY") or "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"
GROQ_MODEL = "llama-3.1-8b-instant"
GROQ_MODEL = "openai/gpt-oss-120b"
# -------------------------
# Configuration
# -------------------------
OPENAI_MODEL = "gpt-4.1-mini"
GEMINI_MODEL = "gemini-2.0-flash"
REQUIRED_NUTRITION_FIELDS = [
"calories",
"proteinContent",
"fatContent",
"carbohydrateContent"]
REQUIRED_FIELDS = [
"keywords",
"dateCreated",
"recipeYield",
"recipeIngredient",
"recipeInstructions"
]
# -------------------------
# Prompt generation
# -------------------------
def generate_prompt(recipe_content: str) -> str:
return f"""
Du bist eine reine JSON-Transformationsmaschine.
Anweisungen:
1. Aktualisiere oder erstelle ein Objekt „nutrition“ für das eine Portion des Rezepts im JSON und berechne die folgenden Felder:
"nutrition": {{
"@type": "NutritionInformation",
"servingSize": "1 Portion",
"calories": "<numeric> kcal",
"proteinContent": "<numeric> g",
"fatContent": "<numeric> g",
"carbohydrateContent": "<numeric> g"
"cholesterolContent": "<numeric> g",
"fiberContent": "<numeric> g",
"saturatedFatContent": "<numeric> g",
"sodiumContent": "<numeric> g",
"sugarContent": "<numeric> g",
"transFatContent": "<numeric> g",
"unsaturatedFatContent": "<numeric> g"
}}
Berechne die Nährwerte anhand der Zutaten in „recipeIngredient“.
Die Zutaten sind auf Deutsch.
Füge die Einheiten zu den Feldern hinzu.
Falls du Annahmen bezüglich Mengen machst, schreibe diese zu den Zutaten, recipeIngredient.
2. Alle anderen Felder im ursprünglichen JSON unverändert lassen.
3. Gib das vollständige aktualisierte JSON-Objekt zurück, einschließlich der aktualisierten Nährwerte.
4. Gib ausschließlich gültiges JSON zurück.
5. Keine Markdown-Formatierung, keine Kommentare, keine Erklärungen und keinen zusätzlichen Text ausgeben.
6. Die Ausgabe muss direkt mit json.loads() parsbar sein.
Data:
{recipe_content}
"""
# -------------------------
# Hugging Face call (LEGACY – WORKING)
# -------------------------
def call_huggingface(prompt: str) -> str:
API_URL = "https://router.huggingface.co/v1/chat/completions"
headers = {
"Authorization": f"Bearer {HF_API_KEY}",
}
def query(payload):
response = requests.post(API_URL, headers=headers, json=payload)
return response.json()
response = query({
"messages": [
{
"role": "user",
"content": prompt
}
],
"model": "Qwen/Qwen2.5-72B:featherless-ai"
})
returnStr = response["choices"][0]["message"]["content"]
logger.debug(response)
logger.debug(returnStr)
return returnStr
# -------------------------
# Groq call
# -------------------------
def call_groq(prompt: str) -> str:
client = OpenAI(
api_key=GROQ_API_KEY,
base_url="https://api.groq.com/openai/v1"
)
response = client.chat.completions.create(
model=GROQ_MODEL,
messages=[
{"role": "system", "content": "You return valid JSON only."},
{"role": "user", "content": prompt},
],
temperature=0.3,
)
logger.debug(response)
returnStr = response.choices[0].message.content.strip()
return returnStr
# -------------------------
# OpenAI call
# -------------------------
def call_openai(prompt: str) -> str:
client = OpenAI(api_key=OPENAI_API_KEY)
response = client.chat.completions.create(
model=OPENAI_MODEL,
messages=[
{"role": "system", "content": "You return valid JSON only."},
{"role": "user", "content": prompt},
],
temperature=0.3,
)
return response.choices[0].message.content.strip()
# -------------------------
# Gemini call
# -------------------------
def call_gemini(prompt: str) -> str:
client = genai.Client(api_key=GEMINI_API_KEY)
response = client.models.generate_content(
model=GEMINI_MODEL,
contents=prompt,
)
text = response.text.strip()
# Defensive cleanup
if text.startswith("```"):
text = text.split("```")[1].replace("json", "").strip()
return text
# -------------------------
# Model router
# -------------------------
def call_model(provider: str, prompt: str) -> str:
if provider == "openai":
return call_openai(prompt)
elif provider == "gemini":
return call_gemini(prompt)
elif provider == "huggingface":
return call_huggingface(prompt)
elif provider == "groq":
return call_groq(prompt)
else:
raise ValueError(f"Unknown provider: {provider}")
# -------------------------
# Evaluation
# -------------------------
def list_dict_fields(d, parent_key=""):
"""
Recursively lists all keys and subkeys in a dict, returning full paths.
"""
fields = []
for k, v in d.items():
full_key = f"{parent_key}.{k}" if parent_key else k
fields.append(full_key)
if isinstance(v, dict):
fields.extend(list_dict_fields(v, full_key))
elif isinstance(v, list):
# If list of dicts, include their fields
for i, item in enumerate(v):
if isinstance(item, dict):
fields.extend(list_dict_fields(item, f"{full_key}[{i}]"))
return fields
def evaluate_response(data: dict) -> dict:
errors = []
all_fields = list_dict_fields(data)
for field in REQUIRED_FIELDS + REQUIRED_NUTRITION_FIELDS :
if not any(field in fields for fields in all_fields):
errors.append(f"Missing field: {field}")
# Check that recipeYield is numeric
recipe_yield = data.get("recipeYield")
if not isinstance(recipe_yield, (int, float)):
errors.append("recipeYield must be numeric")
return {
"valid": len(errors) == 0,
"errors": errors
}
# -------------------------
# Main processing for a single file
# -------------------------
def remove_keys(d: dict, keys_to_remove: list):
"""
Remove specified keys from a dictionary (top-level only).
"""
for key in keys_to_remove:
if key in d:
del d[key]
return d
def extract_and_remove_keys(d: dict, keys_to_remove: list):
"""
Remove specified keys from a dictionary (top-level only) and store their values.
Returns a tuple: (cleaned_dict, extracted_values)
"""
extracted = {}
for key in keys_to_remove:
if key in d:
extracted[key] = d.pop(key)
return d, extracted
def process_recipe(file_path: str, provider: str, update_nutrition: bool = True, delete_nutrition: bool = True):
if not os.path.exists(file_path):
logger.error(f"❌ File not found: {file_path}")
return
with open(file_path, "r", encoding="utf-8") as f:
try:
recipe_data = json.load(f)
except json.JSONDecodeError:
logger.error(f"❌ File is not valid JSON: {file_path}")
return
# -------------------------
# Nutrition check (optional)
# -------------------------
if "nutrition" in recipe_data and isinstance(recipe_data["nutrition"], dict):
all_fields = list_dict_fields(recipe_data["nutrition"])
for field in REQUIRED_NUTRITION_FIELDS:
if not any(field in fields for fields in all_fields):
update_nutrition = True
logger.warning(f"Missing field: {field}, Nutrition block will be updated.")
break
warning = f"⚠️ Nutrition block already exists in {os.path.basename(os.path.dirname(file_path))}/{os.path.basename(file_path)}. "
if update_nutrition:
logger.warning(f"{warning:<100} - It will be updated")
elif delete_nutrition:
logger.warning(f"{warning:<100} - It will be deleted")
recipe_data, _ = extract_and_remove_keys(recipe_data, ["nutrition"])
with open(file_path, "w", encoding="utf-8") as f:
json.dump(recipe_data, f, indent=2, ensure_ascii=False)
return True
else:
logger.warning(f"{warning:<100} - Skipping recipe")
return True
else:
logger.info(f"ℹ️ No nutrition block found in {file_path}. A new one will be added.")
recipe_data,_ = extract_and_remove_keys(recipe_data, ["video","aggregateRating","reviews"])
recipe_data, stored_keys = extract_and_remove_keys(recipe_data, ["valueInit"])
# Serialize JSON back to string for prompt
recipe_content = json.dumps(recipe_data, ensure_ascii=False)
prompt = generate_prompt(recipe_content)
logger.info(f"🚀 Using provider: {provider} → {file_path}")
logger.debug(prompt)
while(True):
try:
raw_response = call_model(provider, prompt)
start = raw_response.find("{")
end = raw_response.rfind("}")
raw_response = raw_response[start:end + 1]
updated_data = json.loads(raw_response)
evaluation = evaluate_response(updated_data)
if not evaluation["valid"]:
logger.error("❌ Evaluation failed. File NOT updated.")
for e in evaluation["errors"]:
logger.error(f"{e}")
return
combined = updated_data | stored_keys
with open(file_path, "w", encoding="utf-8") as f:
json.dump(combined, f, indent=2, ensure_ascii=False)
logger.info("✅ Recipe updated successfully.")
break
except json.JSONDecodeError:
logger.error("❌ Model did not return valid JSON.")
logger.error("RAW OUTPUT:\n", raw_response)
except Exception as e:
msg = str(e)
if "rate limit" in msg.lower():
# Extract wait time
match = re.search(r'Please try again in (\d+)m([\d\.]+)s', msg)
logger.warning(msg)
if match:
minutes = int(match.group(1))
seconds = float(match.group(2))
wait_time = (minutes * 60 + seconds) *1.5
logger.warning(f"Rate limit hit. Waiting for {wait_time:.2f} seconds...")
for remaining in range(int(wait_time), 0, -1):
print(f"\rTime left: {remaining}s", end="")
time.sleep(1)
logger.info("\nRetrying now...")
else:
logger.error("Rate limit hit, could not parse wait time. Waiting 200 seconds...")
return False
else:
logger.error("❌ Error:", e)
return False
return True
# -------------------------
# Recursively find all recipe.json files in a folder
# -------------------------
def process_folder(folder_path: str, provider: str, update_nutrition: bool = True , delete_nutrition: bool = True):
json_files = []
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.lower() == "recipe.json":
full_path = os.path.join(root, file)
json_files.append(os.path.join(root, file))
i = 1
for file in json_files:
logger.info(f"Checking: {i}/{len(json_files)} ... {os.path.basename(os.path.dirname(file))}/{os.path.basename(file)}.")
i+=1
if not process_recipe(file, provider, update_nutrition, delete_nutrition):
logger.warning(f"File: {file} failed. Continuing")
# -------------------------
# CLI entry point
# -------------------------
if __name__ == "__main__":
script_name = os.path.splitext(os.path.basename(__file__))[0]
log_path = os.path.join(os.path.expanduser("~"), ".LOG",f"{script_name}",
f"{script_name}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
)
logger = setup_logger(log_file=log_path)
logger.info("Logger initialized.")
parser = argparse.ArgumentParser()
parser.add_argument("path", help="Recipe JSON file or folder containing recipe.json files")
parser.add_argument(
"--provider",
choices=["openai", "gemini", "huggingface", "groq"],
default="groq",
help="LLM provider to use"
)
parser.add_argument(
"-un", "--update_nutrition",
action="store_true",
help="Enable nutrition block check and update"
)
parser.add_argument(
"-dn", "--delete_nutrition",
action="store_true",
help="Enable nutrition block deletion"
)
args = parser.parse_args()
path = args.path
provider = args.provider
update_nutrition = args.update_nutrition
delete_nutrition = args.delete_nutrition
# path = "/data/Nextcloud/Documents/Dokumente/Shared/Diverses/Kochbuch/RecepiesLucas/Sauerteig herstellen und züchten"
# update_nutrition = False
# delete_nutrition = False
if os.path.isdir(path):
process_folder(path, provider, update_nutrition, delete_nutrition)
else:
process_recipe(path, provider, update_nutrition, delete_nutrition)
+35
View File
@@ -0,0 +1,35 @@
#!/bin/bash
if [ $# -lt 1 ]; then echo "No Path given"; exit 1; fi
IMG_PATH="$1"
if [ "$2" == "-m" ]; then MOVE=true; fi
MOVE=false
echo Path: $IMG_PATH
find "$IMG_PATH" \( -name "*.png" -or -name "*.jp*g" \)
files="$(find "$IMG_PATH" \( -name "*.png" -or -name "*.jp*g" \) | wc -l)"
printf "%s Files, Move: %s\n" "$files" "$MOVE"
read -n 1 -s -r -p "Press any key to continue"
printf "\n"
minImgX="1400"
screenAR="0.5625"
AR_tolerance="0.2"
counter=0
find "$IMG_PATH" \( -name "*.png" -or -name "*.jp*g" \) | while read img; do
((counter++))
object_path="$(echo "${img}" | rev | cut -f2- -d'/' | rev)/"
img="$(echo "${img}" | rev | cut -f1 -d'/' | rev)"
if [ "$(echo "${img}" | grep " ")" != "" ]; then
mv "${object_path}${img}" "${object_path}$(echo "${img}" | sed 's/ \+/_/g')"
img="$(echo "${img}" | sed 's/ \+/_/g')"
fi
if [ "$(echo "${img}" | grep -e "jp[e]\?g")" != "" ]; then
convert "${object_path}${img}" "${object_path}$(echo "${img}" | sed 's/jp[e]\?g/png/g')"
rm "${object_path}${img}"
img="$(echo "${img}" | sed 's/jp[e]\?g/png/g')"
fi
imageAR=$(identify "${object_path}${img}" | perl -ne '/(.+?)\s+[A-Z]{3}\s+(\d+)x(\d+)/; print $3/$2, "\n"')
imgX=$(identify "${object_path}${img}" | cut -f3 -d' ' | cut -f1 -d'x')
if [[ "$MOVE" = true && $(echo ${imageAR}'<'${screenAR}'*(1+'${AR_tolerance}')' | bc -l) -eq 1 && $(echo ${imageAR}'>'${screenAR}'*(1-'${AR_tolerance}')' | bc -l) -eq 1 && $(echo ${imgX}'>'${minImgX} | bc -l ) -eq 1 ]] ;then
printf "%d/%s: %s\t%s\n" "$counter" "$files" "${img}" "$imageAR"
cp "${object_path}${img}" "/data/Ubuntu_Data/Videos/.stuff/"
fi
done
+16
View File
@@ -0,0 +1,16 @@
#!/bin/bash
while IFS= read -r line; do
element_name="$(printf "%s_%s_%s%s\n" "$(echo $line | cut -f2 -d' ')" "$(echo $line | cut -f3 -d' ')" "$(echo $line | cut -f1 -d' ' | head -c 1 | tr 'a-z' 'A-Z')" "$(echo $line | cut -f1 -d' ' | tail -c +2)")"
element="$(printf "%s%s\n" "$(echo $line | cut -f1 -d' ' | head -c 1 | tr 'a-z' 'A-Z')" "$(echo $line | cut -f1 -d' ' | tail -c +2)")"
LINK="$(wget -qO- https://commons.wikimedia.org/wiki/File:${element}_spectrum_visible.png | grep "Original file" | grep -o 'href="[^"]*' | tail -c +7)"
if [ "$LINK" == "" ]; then
echo "None for $element"
else
echo $LINK
fi
wget $LINK
mv ${element}_spectrum_visible.png ${element_name}.png
convert ${element_name}.png -resize 3840x ${element_name}.png
convert ${element_name}.png -crop 3840x540+0+0 ${element_name}.png
mv ${element_name}.png /home/lucas/Documents/Dokumente/Zeug/Wallpaper/Desktop1920x1080/Elements/Elements_Panorama_${element_name}.png
done < "get_images.txt"
+97
View File
@@ -0,0 +1,97 @@
hydrogen 1 H Hydrogen spectrum visible.png
helium 2 He Helium spectrum visible.png
lithium 3 Li Lithium spectrum visible.png
beryllium 4 Be Beryllium spectrum visible.png
boron 5 B Boron spectrum visible.png
carbon 6 C Carbon spectrum visible.png
nitrogen 7 N Nitrogen spectrum visible.png
oxygen 8 O Oxygen spectrum visible.png
fluorine 9 F Fluorine spectrum visible.png
neon 10 Ne Neon spectrum visible.png
sodium 11 Na Sodium spectrum visible.png
magnesium 12 Mg Magnesium spectrum visible.png
aluminium 13 Al Aluminium spectrum visible.png
silicon 14 Si Silicon spectrum visible.png
phosphorus 15 P Phosphorus spectrum visible.png
sulfur 16 S Sulfur spectrum visible.png
chlorine 17 Cl Chlorine spectrum visible.png
argon 18 Ar Argon spectrum visible.png
potassium 19 K Potassium spectrum visible.png
calcium 20 Ca Calcium spectrum visible.png
scandium 21 Sc Scandium spectrum visible.png
titanium 22 Ti Titanium spectrum visible.png
vanadium 23 V Vanadium spectrum visible.png
chromium 24 Cr Chromium spectrum visible.png
manganese 25 Mn Manganese spectrum visible.png
iron 26 Fe Iron spectrum visible.png
cobalt 27 Co Cobalt spectrum visible.png
nickel 28 Ni Nickel spectrum visible.png
copper 29 Cu Copper spectrum visible.png
zinc 30 Zn Zinc spectrum visible.png
gallium 31 Ga Gallium spectrum visible.png
germanium 32 Ge Germanium spectrum visible.png
arsenic 33 As Arsenic spectrum visible.png
selenium 34 Se Selenium spectrum visible.png
bromine 35 Br Bromine spectrum visible.png
krypton 36 Kr Krypton spectrum visible.png
rubidium 37 Rb Rubidium spectrum visible.png
strontium 38 Sr Strontium spectrum visible.png
yttrium 39 Y Yttrium spectrum visible.png
zirconium 40 Zr Zirconium spectrum visible.png
niobium 41 Nb Niobium spectrum visible.png
molybdenum 42 Mo Molybdenum spectrum visible.png
technetium 43 Tc Technetium spectrum visible.png
ruthenium 44 Ru Ruthenium spectrum visible.png
rhodium 45 Rh Rhodium spectrum visible.png
palladium 46 Pd Palladium spectrum visible.png
silver 47 Ag Silver spectrum visible.png
cadmium 48 Cd Cadmium spectrum visible.png
indium 49 In Indium spectrum visible.png
tin 50 Sn Tin spectrum visible.png
antimony 51 Sb Antimony spectrum visible.png
tellurium 52 Te Tellurium spectrum visible.png
iodine 53 I Iodine spectrum visible.png
xenon 54 Xe Xenon spectrum visible.png
caesium 55 Cs Caesium spectrum visible.png
barium 56 Ba Barium spectrum visible.png
lanthanum 57 La Lanthanum spectrum visible.png
cerium 58 Ce Cerium spectrum visible.png
praseodymium 59 Pr Praseodymium spectrum visible.png
neodymium 60 Nd Neodymium spectrum visible.png
promethium 61 Pm Promethium spectrum visible.png
samarium 62 Sm Samarium spectrum visible.png
europium 63 Eu Europium spectrum visible.png
gadolinium 64 Gd Gadolinium spectrum visible.png
terbium 65 Tb Terbium spectrum visible.png
dysprosium 66 Dy Dysprosium spectrum visible.png
holmium 67 Ho Holmium spectrum visible.png
erbium 68 Er Erbium spectrum visible.png
thulium 69 Tm Thulium spectrum visible.png
ytterbium 70 Yb Ytterbium spectrum visible.png
lutetium 71 Lu Lutetium spectrum visible.png
hafnium 72 Hf Hafnium spectrum visible.png
tantalum 73 Ta Tantalum spectrum visible.png
tungsten 74 W Tungsten spectrum visible.png
rhenium 75 Re Rhenium spectrum visible.png
osmium 76 Os Osmium spectrum visible.png
iridium 77 Ir Iridium spectrum visible.png
platinum 78 Pt Platinum spectrum visible.png
gold 79 Au Gold spectrum visible.png
mercury 80 Hg Mercury spectrum visible.png
thallium 81 Tl Thallium spectrum visible.png
lead 82 Pb Lead spectrum visible.png
bismuth 83 Bi Bismuth spectrum visible.png
polonium 84 Po Polonium spectrum visible.png
radon 86 Rn Radon spectrum visible.png
radium 88 Ra Radium spectrum visible.png
actinium 89 Ac Actinium spectrum visible.png
thorium 90 Th Thorium spectrum visible.png
protactinium 91 Pa Protactinium spectrum visible.png
uranium 92 U Uranium spectrum visible.png
neptunium 93 Np Neptunium spectrum visible.png
plutonium 94 Pu Plutonium spectrum visible.png
americium 95 Am Americium spectrum visible.png
curium 96 Cm Curium spectrum visible.png
berkelium 97 Bk Berkelium spectrum visible.png
californium 98 Cf Californium spectrum visible.png
einsteinium 99 Es
+11
View File
@@ -0,0 +1,11 @@
#!/bin/bash
IMG_FOLDER="."
IMG_ARR=($(find ${IMG_FOLDER} -name '*.jp*g'))
for IMG in ${IMG_ARR[@]}; do
echo ${IMG}
convert "$IMG" "$(echo $IMG | sed 's/jp[e]\?g/png/g')"
rm ${IMG}
done
#for file in *g ; do
#convert "$file" -resize x1080 $(echo "NEW/${file}" | sed 's/jp[e]\?g/png/g')
#done
+10
View File
@@ -0,0 +1,10 @@
#!/bin/bash
ssh serverhost sudo /home/lucas/scripts/deluge_user_cmd.sh deluge-console add "$1" > /home/lucas/.LOG/torrentlog.log 2>&1
if [ $(cat /home/lucas/.LOG/torrentlog.log | grep -o "Torrent added!" | wc -l) -gt 0 ]; then
notify-send 'Add Magnet' 'Success'
else
notify-send 'Add Magnet' 'FAIL -> Copy to Clipboard'
echo "$1" | xclip
fi
exit
+19
View File
@@ -0,0 +1,19 @@
## Sed something out of file
## name: attention for *
name="$1"
sed1="$2"
sed2="$3"
for file in $name; do
mv "$file" "$(echo "$file" | sed 's/$sed1/$sed2/g')"
done
## Swap -f2 and -f1
names="$(ls $1)"
while read lines; do
date="$(echo $lines | cut -d' ' -f2)"
file="$(echo $lines | cut -d' ' -f1)"
mv "$file" "$(printf "%s_%s" "$date" "$file")"
done < names
## Rearrange Filename
for file in BestScore*png; do
mv $file $(echo $file | tr '_.' '|' | awk '{split($0,a,"|"); print a[2]"_"a[1]"."a[3]}')
done
+2
View File
@@ -0,0 +1,2 @@
/usr/bin/nmcli radio all off
/usr/bin/nmcli radio all on
+67
View File
@@ -0,0 +1,67 @@
#!/bin/bash
LOG_FILE=/home/lucas/.LOG/panic_log.log
exec 1>>${LOG_FILE} 2>&1
id
gsettings set org.gnome.desktop.background picture-uri ''
gsettings set org.gnome.desktop.background primary-color 'rgb(255, 173, 100)'
if [ -d /media/veracrypt_system/NewDat ]; then
sudo /usr/bin/veracrypt --dismount /media/lucas/LucasFestplatte/SystemData/SavedFiles/System_Data
echo "System Dismounted"
else
echo "System not present"
fi
if [ -d /media/veracrypt_cmcs/Comics ]; then
sudo /usr/bin/veracrypt --dismount /media/lucas/LucasFestplatte/SystemData/SavedFiles/Cmcis
echo "Cmcs Dismounted"
else
echo "Cmcs not present"
fi
if [ -d /media/veracrypt_man/New ]; then
sudo /usr/bin/veracrypt --dismount /media/lucas/LucasFestplatte/SystemData/SavedFiles/System_Man
echo "Man Dismounted"
else
echo "Man not present"
fi
if [ $(ps -elf | grep -v grep | grep '.py' | grep '-EO' | wc -l) -gt 0 ]; then
kill -f $(ps -elf | grep -v grep | grep '.py' | grep '-EO' | sed 's/ */ /g' | cut -f4 -d' ')
echo "Renpy killed"
else
echo "Renpy not running"
fi
if [ $(ps -elf | grep -v grep | grep -i firefox | wc -l) -gt 0 ]; then
pkill -f firefox &
echo "Firefox killed"
else
echo "Firefox not running"
fi
if [ $(ps -elf | grep -v grep | grep -i vlc | wc -l) -gt 0 ]; then
pkill vlc
echo "VLC killed"
else
echo "VLC not running"
fi
if [ $(ps -elf | grep -v grep | grep -i totem | wc -l) -gt 0 ]; then
pkill totem
echo "Totem killed"
else
echo "Totem not running"
fi
if [ $(ps -elf | grep -v grep | grep -i nautilus | wc -l) -gt 0 ]; then
pkill nautilus
echo "nautilus killed"
else
echo "nautilus not running"
fi
/home/lucas/scripts/wallpaperChanger.sh -c -l -X &
echo "Wallpaper Changed"
+1
View File
@@ -0,0 +1 @@
for file in Logo*; do pdftoppm -f 1 -l 1 Logo.pdf | pnmtojpeg - > IMG_Logo.jpg; done
+54
View File
@@ -0,0 +1,54 @@
#!/bin/bash
pdf_file="$1"
if [ $# -ne 1 ]; then
echo "Filename Missing"
exit
fi
if [ -f ${pdf_file} ]; then
echo "Using ${pdf_file}"
else
echo "${pdf_file} doesnt exist!"
exit
fi
NAME="$(echo ${pdf_file} | rev | cut -f1 -d'/' | rev)"
if [ "$(echo ${pdf_file} | grep -o '/')" != "" ]; then
path="$(echo ${pdf_file} | rev | cut -f2- -d'/' | rev)"
else
path="$(pwd)"
fi
cd ${path}
if [ -d .BUFFERFOLDER ]; then
rm -dr .BUFFERFOLDER
fi
mkdir .BUFFERFOLDER
cp ${NAME} .BUFFERFOLDER/
NAME="$(echo ${NAME} | rev | cut -f2- -d'.' | rev)"
cd .BUFFERFOLDER
pdfimages -png ${NAME}.pdf ${NAME}
count=0
for img in *.png; do
convert ${img} "$(echo ${img} | sed 's/png/jpg/g')"
rm ${img}
img="$(echo ${img} | sed 's/png/jpg/g')"
echo ${img}
convert ${img} -resize 2550x3300! ${img}
if [ "$(echo ${img} | grep "000")" != "" ]; then
convert ${img} -crop 2206x3200+200+50 ${img}
else
convert ${img} -crop 2106x3200+200+50 ${img}
fi
convert ${img} -fuzz 20%% -transparent White ${img}
convert ${img} -resize 2550x3300 -gravity center -background White -extent 2550x3300 ${img}
split_var=$((count / 100))
if [ ! -d "split_${split_var}" ]; then
mkdir split_${split_var}
fi
mv ${img} split_${split_var}/
((count++))
done
for ((i=0;i<$(ls | grep split_ | wc -l);i++)); do
echo "Convert Part $i"
convert split_$i/*.jpg ../${NAME}_split_${i}.pdf
done
cd ../
rm -dr .BUFFERFOLDER
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/perl
use strict;
use warnings;
use Spreadsheet::WriteExcel;
print "Start\n";
my $workbook = Spreadsheet::WriteExcel->new("BA_Data.ods");
my $worksheet = $workbook->add_worksheet();
my ($x,$y) = (0,0);
my @list = qw(13,92 12,98 101,13);
foreach my $c (@list){
$worksheet->write($x, $y++, $c);
}
$workbook->close();
+55
View File
@@ -0,0 +1,55 @@
#!/usr/bin/perl -w
use strict;
use Spreadsheet::ParseExcel;
use Spreadsheet::ParseExcel::SaveParser;
# Open the template with SaveParser
my $parser = new Spreadsheet::ParseExcel::SaveParser;
#my $finanzen = "/data/DatenLucas/Dokumente/Dokumente/Finanzen/Finanzen2020.ods"
my $finanzen = 'test.ods';
my $template = $parser->Parse($finanzen);
my $sheet = 0;
my $row = 3;
my $col = 3;
# Get the format from the cell
my $format = $template->{Worksheet}[$sheet]
->{Cells}[$row][$col]
->{FormatNo};
# Write data to some cells
$template->AddCell(0, $row, $col, 1, $format);
$template->AddCell(0, $row+1, $col, "Hello", $format);
# Add a new worksheet
$template->AddWorksheet('New Data');
$template->AddCell(1, $row+2, $col, "Hello3", $format);
my $worksheet_1 = $template->worksheet('New Data');
$worksheet_1->AddCell($row+3, $col, "Hello3", $format);
# The SaveParser SaveAs() method returns a reference to a
# Spreadsheet::WriteExcel object. If you wish you can then
# use this to access any of the methods that aren't
# available from the SaveParser object. If you don't need
# to do this just use SaveAs().
#
my $workbook;
{
# SaveAs generates a lot of harmless warnings about unset
# Worksheet properties. You can ignore them if you wish.
local $^W = 0;
# Rewrite the file or save as a new file
$workbook = $template->SaveAs('new.ods');
}
# Use Spreadsheet::WriteExcel methods
my $worksheet = $workbook->sheets(0);
$worksheet->write($row+2, $col, "World2");
$workbook->close();
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/perl -w
use strict;
use Spreadsheet::ParseExcel;
use Spreadsheet::ParseExcel::SaveParser;
# Open the template with SaveParser
my $parser = new Spreadsheet::ParseExcel::SaveParser;
my $finanzen = "/data/DatenLucas/Dokumente/Dokumente/Finanzen/BA_Data.ods";
#my $finanzen = "FinanzenTest.xls";
my $template = $parser->Parse($finanzen);
my $row=0;
my $col=0;
my $sheet=0;
# Get the format from the cell
my $format = $template->{Worksheet}[$sheet]
->{Cells}[$row][$col]
->{FormatNo};
$template->AddCell(0, $row+1, $col, 1, $format);
$template->SaveAs('new.xls');
Binary file not shown.
Binary file not shown.
+14
View File
@@ -0,0 +1,14 @@
#!/bin/bash
ls "$1"
if [ $? -ne 0 ] || [ "$1" == "" ]; then
echo "List $1 not available"
fi
list=$1
IFS=$'\n'; set -f
songs=($(cat ${list} | cut -f1 -d';'))
artists=($(cat ${list} | cut -f2 -d';'))
unset IFS; set +f
for((i=0;i < ${#songs[@]};i++)) do
printf "%s - %s\n" "${artists[i]}" "${songs[i]}"
find /data/DatenLucas/Music/ -type f -iname *"${songs[i]}"* | grep "${artists[i]}"
done
+236
View File
@@ -0,0 +1,236 @@
#!/bin/bash
RSYNCFILE="/tmp/rsync_files.txt"
MUSICDir="/data/DatenLucas/Music/Musik/"
if [[ -d /home/lucas/.quodlibet/playlists/ ]]; then
PLPATH="/home/lucas/.quodlibet/playlists/"
elif [[ -d /home/lucas/.config/quodlibet/playlists/ ]]; then
PLPATH="/home/lucas/.config/quodlibet/playlists/"
else
echo "No Playlist Directory found. Exiting"
exit
fi
if [ -f /home/lucas/.LOG/rsync.log ]; then
rm /home/lucas/.LOG/rsync.log
fi
PHONE_path="Default Path"
if [ -d /run/user/1000/gvfs/mtp* ]; then
PHONE_path="/run/user/1000/gvfs/$(ls /run/user/1000/gvfs/ | grep "mtp")/Internal shared storage/"
fi
ANDR_MUSIC="Music"
PHONE_PL_PATH="/\/storage\/emulated\/0\/${ANDR_MUSIC}\/"
i=0
SYNC=true
DRY_RUN=false
RESYNC=false
COPY=false
RELOAD_PLAYLIST=false
playlist_array=()
usage() {
printf "Usage
-p <pl1> <pl2>\t\tSync Playlists
-resync\t\t\tResync all Playlists
-reloadPlaylist\t\tCopy Playlists only
-all\t\t\tSync all Playlists in ${PLPATH}
-PO\t\t\tDont Sync
-copy\t\tCopy Files
-dry\t\t\tDry Run
-folder\t\tSync To /win10/Users/lucas/Music/
-watch\t\tSync To Garmin Watch
-help\t\t\tDisplay this\n"
}
get_config() {
while [[ ${1:0:1} != "" ]]; do
if [ $1 == -resync ]; then
RESYNC=true
shift 1
continue
fi
if [ $1 == -reloadPlaylist ]; then
RELOAD_PLAYLIST=true
break
fi
if [ $1 == -help ]; then
usage
exit
fi
if [ $1 == -dry ]; then
DRY_RUN=true
shift 1
continue
fi
if [ $1 == -copy ]; then
COPY=true
shift 1
continue
fi
if [ $1 == -diff ]; then
DIFF=true
shift 1
continue
fi
if [ $1 == -folder ]; then
PHONE_path="/win10/Users/lucas/Music/"
PHONE_PL_PATH="\/win10\/Users\/lucas\/Music\/"
rm -dr ${PHONE_path}Music/*
shift 1
continue
fi
if [ $1 == -watch ]; then
if [[ "$(ls /run/user/1000/gvfs/mtp*)" != "" ]]; then
PHONE_path="/run/user/1000/gvfs/mtp:host=091e_4c05_0000c6a66cb9/Primary/"
else
echo "No Watch Path found"
fi
shift 1
continue
fi
if [ $1 == -p ]; then
shift 1
echo "Sync Playlists in Arguments"
while [[ ${1:0:1} != "" ]] && [[ ${1:0:1} != "-" ]]; do
ls "${PLPATH}"$1 >>/dev/null 2>&1
if [ $? -ne 0 ]; then
echo "No such Playlist $1"
shift 1
continue
fi
arr=($(ls "${PLPATH}"$1 | rev | cut -f1 -d'/' | rev))
printf "Sync "
for ((i=0;i<${#arr[@]};i++)); do printf "%s " "${arr[$i]}"; done
printf "? (y/*) "
read -t 10 -n 2 choice
if [ "$choice" != "y" ]; then
printf "\nAbort\n"
shift 1
continue
fi
playlist_array+=($(ls "${PLPATH}"$1 | rev | cut -f1 -d'/' | rev))
((i++))
shift 1
continue
done
continue
fi
echo "Parameter $1 discarded"
usage
exit
done
}
if [ $# -lt 1 ]; then
echo "Too few Arguments"
usage
exit 0
fi
get_config "$@"
if [ ! -d "${PHONE_path}" ]; then
echo "Phone Path: ${PHONE_path} not found"
exit
else
echo "Phone Path: ${PHONE_path}"
fi
if [[ "${RESYNC}" == "true" ]] || [[ "${RELOAD_PLAYLIST}" == "true" ]] ; then
playlist_array+=($(ls /run/user/1000/gvfs/mtp:host=*/Internal\ shared\ storage/Playlists/ | sed 's/\.m3u//g'))
if [[ "${RELOAD_PLAYLIST}" == "true" ]]; then
SYNC=false
fi
fi
if [[ "${DIFF}" == "true" ]]; then
for playlist in "${playlist_array[@]}"; do
echo "Check Handy Playlist ${playlist} for Changes"
cat ${PHONE_path}BlackPlayer/Playlists/${playlist}.m3uBackup | sed 's/\/storage\/emulated\/0\/Music\///g' | sort > .handy_${playlist}
cat ${PLPATH}${playlist} | sed 's/\/data\/DatenLucas\/Music\/Musik\///g' | sort > .quodlibet_${playlist}
IFS=$'\n'; set -f
in_quodlibet=("$(diff .handy_${playlist} .quodlibet_${playlist} | grep '> ' | sed 's/> //g')")
in_handy=($(diff .handy_${playlist} .quodlibet_${playlist} | grep '< ' | sed 's/< //g'))
rm .quodlibet_${playlist} .handy_${playlist}
if [ ${#in_handy[@]} -gt 0 ]; then
printf "#### Handy ####\n\n"
else
printf "No Differences found\n"
fi
for song in ${in_handy[@]}; do
echo "Keep ${song}?(y/*)"
read -t 10 -n 2 choice
if [ "$choice" != "y" ]; then
printf "Delete\n"
else
echo "/data/DatenLucas/Music/Musik/${song}" >> ${PLPATH}${playlist}
fi
done
unset IFS; set +f
done
fi
for playlist in "${playlist_array[@]}"; do
IFS=$'\n'
PL_songs=($(cat "${PLPATH}${playlist}"))
unset IFS
NOW=$(pwd)
cd ${MUSICDir}
> ${RSYNCFILE}
for ((i=0;i<${#PL_songs[@]};i++)); do
ACT_PATH="$(echo "${PL_songs[$i]}" | rev | cut -f2- -d'/' | rev | sed 's/\/data\/DatenLucas\/'"${ANDR_MUSIC}"'\/Musik\///g')/"
NAME="$(echo "${PL_songs[$i]}" | rev | cut -f1 -d'/' | rev)"
echo "${ACT_PATH}${NAME}" >> ${RSYNCFILE}
done
if ${SYNC}; then
if ${DRY_RUN}; then
echo "Dry Run"
rsync -n -v --inplace --progress --omit-dir-times --no-perms --size-only --files-from=${RSYNCFILE} . "${PHONE_path}"${ANDR_MUSIC}/
else
if [[ "${COPY}" == "true" ]];then
printf "\nCopy $(ls "${PLPATH}${playlist}")\n"
IFS=$'\n'; set -f
count=0
for file in $(cat ${RSYNCFILE}); do
num=$(cat ${RSYNCFILE} | wc -l)
path=$(echo "$file" | rev | cut -f2- -d'/' | rev)
if [ ! -d "${PHONE_path}${ANDR_MUSIC}/${path}/" ]; then
echo "mkdir ${PHONE_path}${ANDR_MUSIC}/${path}/"
mkdir -p "${PHONE_path}${ANDR_MUSIC}/${path}/"
fi
echo "cp ${file}"
cp --force --no-preserve=ownership --no-preserve=timestamps ${file} ${PHONE_path}${ANDR_MUSIC}/${path}/
((count++))
done
unset IFS; set +f
else
printf "\nSyncing $(ls "${PLPATH}${playlist}")\n"
rsync -v --inplace --progress --delete --omit-dir-times --no-perms --size-only --files-from=${RSYNCFILE} . "${PHONE_path}"${ANDR_MUSIC}/ 2>>~/.LOG/rsync.log
fi
fi
fi
rm ${RSYNCFILE}
cd ${PLPATH}
echo "Copy ${playlist}.m3u"
cp ${playlist} /tmp/${playlist}.m3u
sed -i 's/\/data\/DatenLucas\/Music\/Musik\/'"${PHONE_PL_PATH}"'/g' "/tmp/${playlist}.m3u"
if [ -d "${PHONE_path}Playlists/" ]; then
cp --no-preserve=ownership --force --no-preserve=timestamps "/tmp/${playlist}.m3u" "${PHONE_path}Playlists/"
else
echo "No ${PHONE_path}Playlists/ Directory"
fi
rm "/tmp/${playlist}.m3u"
cd ${NOW}
done
for playlist in ${PLPATH}*; do
echo "Backup $(echo ${playlist} | rev | cut -f1 -d'/' | rev).m3u"
cp ${playlist} /home/lucas/Music/Playlists/$(echo ${playlist} | rev | cut -f1 -d'/' | rev).m3u
cp ${playlist} /home/lucas/Music/Playlists/WIN10/$(echo ${playlist} | rev | cut -f1 -d'/' | rev)_WIN10.m3u
sed -i 's/\/data/D:/g' "/home/lucas/Music/Playlists/WIN10/$(echo ${playlist} | rev | cut -f1 -d'/' | rev)_WIN10.m3u"
sed -i 's/\//\\/g' "/home/lucas/Music/Playlists/WIN10/$(echo ${playlist} | rev | cut -f1 -d'/' | rev)_WIN10.m3u"
done
IFS=$'\n'
for file in $(cat /home/lucas/.LOG/rsync.log | grep mp3 |cut -f2 -d'"'); do
rm "$file"
done
#cat TopOldSchool1 | rev | cut -f1 -d'/' | rev > TopOldSchool
#sort -um TopOldSchool1 TopOldSchool
#awk '!a[$0]++' TopOldSchool TopOldSchool1 > TopOldSchool2
#cat TopOldSchool | sort >> TopOldSchool9
#diff TopOldSchool8 TopOldSchool9
+173
View File
@@ -0,0 +1,173 @@
#!/bin/bash
# Usage:
# Source this script
# enable_trapping <- optional to clean up properly if user presses ctrl-c
# setup_scroll_area <- create empty progress bar
# draw_progress_bar 10 <- advance progress bar
# draw_progress_bar 40 <- advance progress bar
# block_progress_bar 45 <- turns the progress bar yellow to indicate some action is requested from the user
# draw_progress_bar 90 <- advance progress bar
# destroy_scroll_area <- remove progress bar
# Constants
CODE_SAVE_CURSOR="\033[s"
CODE_RESTORE_CURSOR="\033[u"
CODE_CURSOR_IN_SCROLL_AREA="\033[1A"
COLOR_FG="\e[30m"
COLOR_BG="\e[42m"
COLOR_BG_BLOCKED="\e[43m"
RESTORE_FG="\e[39m"
RESTORE_BG="\e[49m"
# Variables
PROGRESS_BLOCKED="false"
TRAPPING_ENABLED="false"
TRAP_SET="false"
setup_scroll_area() {
# If trapping is enabled, we will want to activate it whenever we setup the scroll area and remove it when we break the scroll area
if [ "$TRAPPING_ENABLED" = "true" ]; then
trap_on_interrupt
fi
lines=$(tput lines)
let lines=$lines-1
# Scroll down a bit to avoid visual glitch when the screen area shrinks by one row
echo -en "\n"
# Save cursor
echo -en "$CODE_SAVE_CURSOR"
# Set scroll region (this will place the cursor in the top left)
echo -en "\033[0;${lines}r"
# Restore cursor but ensure its inside the scrolling area
echo -en "$CODE_RESTORE_CURSOR"
echo -en "$CODE_CURSOR_IN_SCROLL_AREA"
# Start empty progress bar
draw_progress_bar 0
}
destroy_scroll_area() {
lines=$(tput lines)
# Save cursor
echo -en "$CODE_SAVE_CURSOR"
# Set scroll region (this will place the cursor in the top left)
echo -en "\033[0;${lines}r"
# Restore cursor but ensure its inside the scrolling area
echo -en "$CODE_RESTORE_CURSOR"
echo -en "$CODE_CURSOR_IN_SCROLL_AREA"
# We are done so clear the scroll bar
clear_progress_bar
# Scroll down a bit to avoid visual glitch when the screen area grows by one row
echo -en "\n\n"
# Once the scroll area is cleared, we want to remove any trap previously set. Otherwise, ctrl+c will exit our shell
if [ "$TRAP_SET" = "true" ]; then
trap - INT
fi
}
draw_progress_bar() {
percentage=$1
lines=$(tput lines)
let lines=$lines
# Save cursor
echo -en "$CODE_SAVE_CURSOR"
# Move cursor position to last row
echo -en "\033[${lines};0f"
# Clear progress bar
tput el
# Draw progress bar
PROGRESS_BLOCKED="false"
print_bar_text $percentage
# Restore cursor position
echo -en "$CODE_RESTORE_CURSOR"
}
block_progress_bar() {
percentage=$1
lines=$(tput lines)
let lines=$lines
# Save cursor
echo -en "$CODE_SAVE_CURSOR"
# Move cursor position to last row
echo -en "\033[${lines};0f"
# Clear progress bar
tput el
# Draw progress bar
PROGRESS_BLOCKED="true"
print_bar_text $percentage
# Restore cursor position
echo -en "$CODE_RESTORE_CURSOR"
}
clear_progress_bar() {
lines=$(tput lines)
let lines=$lines
# Save cursor
echo -en "$CODE_SAVE_CURSOR"
# Move cursor position to last row
echo -en "\033[${lines};0f"
# clear progress bar
tput el
# Restore cursor position
echo -en "$CODE_RESTORE_CURSOR"
}
print_bar_text() {
local percentage=$1
local cols=$(tput cols)
let bar_size=$cols-17
local color="${COLOR_FG}${COLOR_BG}"
if [ "$PROGRESS_BLOCKED" = "true" ]; then
color="${COLOR_FG}${COLOR_BG_BLOCKED}"
fi
# Prepare progress bar
let complete_size=($bar_size*$percentage)/100
let remainder_size=$bar_size-$complete_size
progress_bar=$(echo -ne "["; echo -en "${color}"; printf_new "#" $complete_size; echo -en "${RESTORE_FG}${RESTORE_BG}"; printf_new "." $remainder_size; echo -ne "]");
# Print progress bar
echo -ne " Progress ${percentage}% ${progress_bar}"
}
enable_trapping() {
TRAPPING_ENABLED="true"
}
trap_on_interrupt() {
# If this function is called, we setup an interrupt handler to cleanup the progress bar
TRAP_SET="true"
trap cleanup_on_interrupt INT
}
cleanup_on_interrupt() {
destroy_scroll_area
exit
}
printf_new() {
str=$1
num=$2
v=$(printf "%-${num}s" "$str")
echo -ne "${v// /$str}"
}
+4
View File
@@ -0,0 +1,4 @@
#!/bin/bash
sed -i -E 's/\\u00dcber[^"]*Video-Tipps! Jetzt entdecken und ausprobieren!//g' */*json
sed -i -E 's/\\u00dcber[^"]*Video-Tipps!//g' */*json
+1
View File
@@ -0,0 +1 @@
i=8 ; for img in Sexy_Natalie_Austin0* ; do mv $img "$(echo $img | sed 's/[0-9]//g' | sed 's/\.png//g')$(printf "%02d" "$i").png";((i++));done
+44
View File
@@ -0,0 +1,44 @@
#!/bin/bash
# Change to your target directory
TARGET_DIR="./" # or set it via "$1" to pass folder as argument
if [[ "$1" != "" ]]; then
TARGET_DIR="$1"
fi
cd "$TARGET_DIR" || exit 1
for file in *.{jpg,jpeg,JPG,JPEG,png,PNG}; do
[ -f "$file" ] || continue # skip if not a file
# Extract DateTimeOriginal using exiftool
datetime=$(exiftool -DateTimeOriginal -s3 "$file")
if [[ -n "$datetime" ]]; then
# Format: "2023:08:21 14:32:10" -> "20230821_143210"
formatted=$(echo "$datetime" | sed 's/://g' | sed 's/ /_/g' | cut -c1-15)
echo $formatted
else
# Fall back to file modification time if no EXIF data
formatted=$(date -r "$file" +"%Y%m%d_%H%M%S")
fi
# Build new filename
extension="${file##*.}"
newname="IMG_${formatted}.${extension}"
# Avoid overwriting
if [[ -e "$newname" ]]; then
i=1
while [[ -e "IMG_${formatted}_$i.${extension}" ]]; do
((i++))
done
newname="IMG_${formatted}_$i.${extension}"
fi
echo "Renaming: '$file' -> '$newname'"
mv "$file" "$newname"
done
+2
View File
@@ -0,0 +1,2 @@
#!/bin/bash
sudo modprobe -r psmouse && sudo modprobe psmouse
+17
View File
@@ -0,0 +1,17 @@
resize_var="x1080"
if [ "$1" != "" ]; then resize_var="$1"; fi
for file in *jpg ; do
if [ "$1" == "" ]; then
height="$(identify -quiet ${file} | cut -f3 -d' ' | cut -f2 -d'x')"
width="$(identify -quiet ${file} | cut -f3 -d' ' | cut -f1 -d'x')"
if [ "${height}" != "" ] && [ "${width}" != "" ]; then
if [ ${height} -gt ${width} ]; then
resize_var="x1080"
else
resize_var="1920"
fi
fi
fi
echo "Transform $file to ${resize_var}"
convert -quiet "$file" -resize ${resize_var} $(echo "NEW/${file}" | sed 's/jp[e]\?g/png/g')
done
+24
View File
@@ -0,0 +1,24 @@
resize_var="x1080"
DATE=$(date +"%d%m%y_")
if [ "$1" != "" ]; then resize_var="$1"; fi
for file in *jpg ; do
if [ "$1" == "" ]; then
height="$(identify -quiet ${file} | cut -f3 -d' ' | cut -f2 -d'x')"
width="$(identify -quiet ${file} | cut -f3 -d' ' | cut -f1 -d'x')"
if [ "${height}" != "" ] && [ "${width}" != "" ]; then
if [ ${height} -gt ${width} ]; then
resize_var="x1080"
else
resize_var="1920"
fi
fi
fi
file_new="$(echo ${file} | tr ' ' '_')"
if [[ "${file_new}" != "${file}" ]]; then
echo "Move $file to $file_new"
mv "$file" "$file_new"
fi
echo "Transform $file_new to ${resize_var}"
if [ ! -d NEW ]; then mkdir "NEW"; fi
convert -quiet "$file_new" -resize ${resize_var} $(echo "NEW/${DATE}${file_new}" | sed 's/jp[e]\?g/png/g')
done
+3
View File
@@ -0,0 +1,3 @@
#!/bin/bash
#rsync -a deluge-user@serverhost:/torrent/mega/TU\\\ Wien/Leistungselektronik/ /home/lucas/Documents/Studium/Master/ToDo/Leistungselektronik/Aufzeichnungen/ --progress --size-only
rsync -a /home/lucas/Documents/Studium/Master/9.Semester/Automatisierung/Aufzeichnungen/ deluge-user@serverhost:/torrent/mega/TU\\\ Wien/Automatisierung/ --progress --size-only
+51
View File
@@ -0,0 +1,51 @@
#!/bin/bash
###/data/DatenLucas/Dokumente/Studium/Master/3.Semester/Mechatronische Systeme/Lernunterlagen/
DEFAULT_DIR="$(cat ~/scripts/screenshot_grab.sh | grep "###" | grep -v grep | sed 's/###//g')"
cont=1
PATH="$(ps -elf | grep -v grep | grep -o -P '(?<=texmaker ).*(?=/.*\.tex)')/"
if [ "$PATH" == "/" ]; then
# /usr/bin/zenity --error --text="No Filepath detected"
# exit 0
while [ $cont -eq 1 ]; do
PATH="$(/usr/bin/zenity --file-selection --title="No TEX open: Where the FUCK shall I go???" --directory --width=600 --height=400 --filename="$DEFAULT_DIR")"
ret=$?
if [[ "$PATH" != "/" ]] && [[ -d "$PATH" ]] && [[ $ret -eq 0 ]]; then
cont=0
elif [[ $ret -eq 1 ]]; then
exit 1
fi
done
PATH="$PATH/"
fi
text="Filename exists:"
NAME="$(/usr/bin/zenity --entry --ok-label="Fuck" --title="Filename" --text="Enter Name:")"
while [ $cont -eq 1 ]; do
if [ -a "$PATH$NAME.png" ]; then
NEWNAME="$(/usr/bin/zenity --entry --entry-text="$NAME" --cancel-label="Fuck It!" --ok-label="New Fuck" --title="Shit Shit Shit" --text="$text")"
ret=$?
if [[ "$NEWNAME" == "" ]] && [[ $ret -eq 1 ]]; then
cont=0
elif [[ "$NAME" != "$NEWNAME" ]] && [[ $ret -eq 0 ]]; then
NAME=$NEWNAME
cont=0
elif [[ "$NAME" == "$NEWNAME" ]] && [[ $ret -eq 0 ]]; then
text="I said new name you stupd fucking Idiot"
else
/usr/bin/zenity --error --title "Fuck Fuck Fuck Error" --text='Some Fucking unexpected State'
fi
else
cont=0
fi
done
if [ "$NAME" == "" ]; then
exit 1;
fi
printf "%s" "$NAME" | /usr/bin/xclip -sel clip
NAME="$NAME.png"
printf "%s\n" "$PATH$NAME"
cont=1
while [ $cont -eq 1 ]; do
/usr/bin/gnome-screenshot -a -f "$PATH$NAME"
/usr/bin/zenity --title="Confirmation" --text="Picture OK?" --ok-label="Fuck Yes" --cancel-label="Fuck No" --question
cont=$?
done
+35
View File
@@ -0,0 +1,35 @@
#!/bin/bash
declare -a hosts=("serverhost" "workhost")
date=$(date +"%m%d%H%M%S")
ping -c 1 -m 1 ${hosts[0]} > /dev/null
if [ $? -ne 0 ]; then
PRE_STAT=1
printf "%s down. WakeOnLan\n" "${hosts[0]}"
bash /home/lucas/Documents/Dokumente/Dokumente/Projekte/Server/scripts/wol.sh serverhost
else
printf "%s up. Commence as planed\n" "${hosts[0]}"
PRE_STAT=0
fi
#bash /home/lucas/Documents/Dokumente/Dokumente/Projekte/Server/scripts/wol.sh workhost
ssh serverhost /home/lucas/scripts/smartctl.sh
ssh serverhost /home/lucas/scripts/upgrade.sh
if [ $? -ne 0 ];then
printf "Update Failed\n"
else
printf "Update Finished\n"
fi
ssh serverhost /home/lucas/scripts/smartctl_long.sh
if [ $? -ne 0 ];then
printf "SMART Test Failed\n"
else
printf "SMART Test Started\n"
fi
ssh serverhost /home/lucas/scripts/backup_all.sh
if [ $? -ne 0 ];then
printf "Backup Failed\n"
else
printf "Finished Started\n"
fi
# Shutdown when finished
#/usr/bin/expect /home/lucas/Raspberry/scripts/shutdown.sh serverhost
+2
View File
@@ -0,0 +1,2 @@
#!/bin/bash
ssh -fNL 127.0.0.2:58846:localhost:58846 lucas@$(dig +short someoneslinux.ddns.net @resolver1.opendns.com) -p 3032 -i /home/lucas/.ssh/id_rsa
+17
View File
@@ -0,0 +1,17 @@
#!/bin/bash
find . -name "* *" -type f | rename 's/ /_/g'
for file in */*flac; do
dir="$(echo $file | cut -f1 -d'/')";
file1="$(echo $file | sed 's/\.flac//g')";
echo "$file1"
echo "$dir"
# continue
# ffmpeg -i "$file1.ape" "$file1.flac";
shnsplit -f "$file1.cue" -t "%n %t" -o flac "$file1.flac";
mv *flac "$dir";
# rm "$file1.ape"
# rm "$file1.cue"
# rm "$file1.flac"
done
+98
View File
@@ -0,0 +1,98 @@
import os
import sys
import shutil
def write_to_quodlibet(file, lines):
with open(os.path.join(quodlibet_path, file), 'w') as fp:
for item in lines:
if not item.startswith("#"):
item = item.replace("\\", "/").replace("D:", "/data").replace("&amp;","&")
if os.path.exists(item):
fp.write("%s\n" % item)
else:
print("File does not exist: %s in %s" % (item, os.path.join(win_dir_path, file + ".m3u")))
ret = input("Continue?(y/n)\n")
if ret == "n":
print("Exit")
exit()
if os.path.exists(os.path.join(quodlibet_path, file + ".xspf")):
os.remove(os.path.join(quodlibet_path, file + ".xspf"))
def write_to_linux(file, lines):
with open(os.path.join(linux_dir_path, file), 'w') as fp:
for item in lines:
if not item.startswith("#"):
fp.write("%s\n" % item.replace("\\", "/").replace("D:", "/data").replace("../..","/data/Nextcloud/Music"))
def write_to_nextcloud(file, lines):
with open(os.path.join(nc_dir_path, file), 'w') as fp:
for item in lines:
item = item.replace("/data/Nextcloud/Music", "../..").replace("&amp;","&")
if not item.startswith("#"):
fp.write("%s\n" % item)
def write_to_win(file, lines):
with open(os.path.join(win_dir_path, file), 'w') as fp:
for item in lines:
item = item.replace("../..","/data/Nextcloud/Music").replace("/data", "D:").replace("/", "\\")
if not item.startswith("#"):
fp.write("%s\n" % item)
def copy_to_garmin(lines):
for sourceFile in lines:
if not sourceFile.startswith("#"):
sourceFile = sourceFile.replace("../..","/data/Nextcloud/Music").replace("&amp;","&")
if os.path.isfile(sourceFile):
shutil.copy(sourceFile, "/data/Nextcloud/Music/Garmin")
else:
print("WARNING: %s not found"%sourceFile)
def read_linux(file):
if os.path.exists(os.path.join(quodlibet_path, file + ".xspf")):
with open(os.path.join(quodlibet_path, file + ".xspf")) as f:
linux_file_lines = f.read().split("</location>")[:-1]
linux_file_lines = [line.split("<location>")[1] for line in linux_file_lines]
elif os.path.exists(os.path.join(quodlibet_path, file)):
with open(os.path.join(quodlibet_path, file)) as f:
linux_file_lines = f.read().splitlines()
return linux_file_lines
arguments = sys.argv[1:]
print(arguments)
win_dir_path = "/data/Nextcloud/Music/Playlists/Win10"
linux_dir_path = "/data/Nextcloud/Music/Playlists/Ubuntu"
nc_dir_path = "/data/Nextcloud/Music/Playlists/Nextcloud"
quodlibet_path = "/home/lucas/.config/quodlibet/playlists"
win_files = os.listdir(win_dir_path)
linux_files = os.listdir(linux_dir_path)
nc_files = os.listdir(nc_dir_path)
linux_files = [os.path.splitext(file)[0] for file in linux_files]
win_files = [os.path.splitext(file)[0] for file in win_files]
nc_files = [os.path.splitext(file)[0] for file in nc_files]
file_set = set(nc_files)
for file in file_set:
if file[0] == ".":
print("Skip: %s" % file)
continue
file_path_m3u = os.path.join(nc_dir_path, file + ".m3u")
file_path_m3u8 = os.path.join(nc_dir_path, file + ".m3u8")
file_path = ""
if os.path.exists(file_path_m3u):
file_path = file_path_m3u
elif os.path.exists(file_path_m3u8):
file_path = file_path_m3u8
with open(file_path) as f:
nc_files_lines = f.read().splitlines()
write_to_linux(file.replace(".m3u", ""), nc_files_lines)
print("Copy to Linux: %s" % file)
write_to_win(file + ".m3u", nc_files_lines)
print("Copy to Win: %s" % file)
if file in arguments:
copy_to_garmin(nc_files_lines)
print("Copy to Garmin")
+145
View File
@@ -0,0 +1,145 @@
#!/bin/bash
IFS=$'\n'; set -f
STUFF="/data/Nextcloud/Filme/New/"
STUFF_ALT="/data/Torrents"
ASSUMEYES=false
FILE_PATH="/torrent/complete/"
usage() {
printf "Usage:
-y\ty Mode
-m\tmega Mode
-f\tCopy to ~/data
-d\tCopy to ~/Downloads
-l\tSelect List
-yt\tYoutube Folder
-help\tDisplay this\n"
}
get_config() {
while [[ ${1:0:1} == - ]]; do
echo "Param: $1"
[[ $1 == -help ]] && {
echo "Help"
usage;
exit;
};
[[ $1 == -y ]] && {
echo "y Mode"
ASSUMEYES=true
shift 1
continue
};
[[ $1 == -yt ]] && {
echo "Youtube Mode"
FILE_PATH="/torrent/youtube/"
shift 1
continue
};
[[ $1 == -m ]] && {
echo "mega Mode"
FILE_PATH="/torrent/mega/"
shift 1
continue
};
[[ $1 == -l ]] && {
echo "List Mode"
LIST_MODE=true
shift 1
continue
};
[[ $1 == -d ]] && {
echo "Change Folder"
STUFF="/home/lucas/Downloads/"
shift 1
continue
};
[[ $1 == -f ]] && {
echo "Change Folder"
STUFF=${STUFF_ALT}
shift 1
continue
};
echo "Parameter $1 discarded"
usage
exit
done
}
get_config "$@"
LIST=($(ssh serverhost ls ${FILE_PATH}))
if [ ${#LIST[@]} -eq 0 ]; then
echo "Nothing to Copy/Delete"
exit
fi
if [ "${LIST_MODE}" == "true" ]; then
for i in "${!LIST[@]}"; do
files=${LIST[$i]}
echo "Copy? ${files} (y/*)"
read -n 10 ans
if [ "$ans" != "y" ]; then
echo "Dont copy $files"
unset 'LIST[i]'
fi
done
echo "NEW LIST:"
echo "${LIST[*]}"
fi
if [ "${ASSUMEYES}" == "false" ]; then
echo "Copy? (y/*)"
echo "${LIST[*]}"
read -n 10 ans
else
ans="y"
fi
if [ "$ans" == "y" ]; then
for files in ${LIST[@]}; do
scp -r deluge-user@serverhost:${FILE_PATH}$(printf "%q" "$files") "${STUFF}"
if [ $? -ne 0 ]; then fail=true; echo "Copy Failure"; exit; fi
done
printf "Torrents Copied\n"
else
printf "Nothing Copied\n"
fi
if [ "${ASSUMEYES}" == "false" ]; then
echo "Rename? (y/*)"
echo "${LIST[*]}"
read -n 10 ans
else
ans="y"
fi
if [ "$ans" == "y" ]; then
for files in ${LIST[@]}; do
echo "Rename $files"
filepath="${STUFF}${files}"
if [ -d "${filepath}" ]; then
echo "${filepath} is a Directory"
bash /home/lucas/scripts/rename_episodes.sh -del -files -dir -repair -path "${filepath}"
elif [ -f "${filepath}" ]; then
echo "${filepath} is a File"
bash /home/lucas/scripts/rename_episodes.sh -files -file "${filepath}"
else
echo "${filepath} neither Directory nor regular file"
fi
done
printf "Rename Complete\n"
else
printf "Nothing Renamed\n"
fi
if [ "${ASSUMEYES}" == "false" ]; then
echo "Delete? (y/*)"
echo "${LIST[*]}"
read -n 10 ans
else
ans="y"
fi
if [ "$ans" == "y" ]; then
for files in ${LIST[@]}; do
echo "Delete $files"
ssh deluge-user@serverhost rm -dr ${FILE_PATH}$(printf "%q" "$files")
done
printf "Torrents Removed\n"
else
printf "Nothing Removed\n"
fi
unset IFS; set +f
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
sudo apt -y update
sudo apt -y upgrade
sudo apt -y dist-upgrade
sudo apt -y autoclean
sudo apt -y autoremove
/home/lucas/Documents/Dokumente/Projekte/Server/scripts/profile_motd2.sh
+21
View File
@@ -0,0 +1,21 @@
#!/bin/bash
# script: winlink
# version: 0.2
# author: Alex Osborn(alex_osborn0@hotmail.com)
# date: 10 Jan 2010
# tested: Ubuntu 9.10 (amd64)
# description: Opens windows .url files in firefox, feel free to edit and use as needed just dont steal the credits!
#
TMP="/tmp/${0##*/}$$"
cat "$@"|grep -s URL|grep -ivs eurl > $TMP
LINE=1
MAX=`cat $TMP|wc -l`
while [ "$LINE" -le "$MAX" ];do
LINK=`head -q "$TMP" -n $LINE|tail -qn 1|tail -qc +5`
if [ -n "$LINK" ];then
firefox -new-tab "$LINK"
echo "$LINK"
fi
LINE=$((LINE+1))
done
rm $TMP
+147
View File
@@ -0,0 +1,147 @@
#!/bin/bash
LIST=false
RETRIES=""
PL_NAME=""
LOG=1
DL_PATH="/home/lucas/Videos/YouTube/"
if [[ "$(hostname)" == "serverhost" ]]; then
DL_PATH="/OwnCloud/Torrents/Complete/"
fi
PLAYLISTS=()
VIDEOS=("")
DATE="$(date +'%m%d%H%M%S')"
log="pl_log_${DATE}.log"
pl_options=""
#pl_options="--playlist-end 11"
vid_options=""
get_config() {
while [[ ${1:0:1} == - ]]; do
echo "Param: $1"
[[ $1 == -retry ]] && {
echo "Retriy Mode"
RETRIES="--retries 100 --fragment-retries 100"
shift 1;
continue;
};
[[ $1 == -log ]] && {
echo "Playlist Log Mode"
LOG=0
shift 1;
continue;
};
[[ $1 == -pl_name ]] && {
if [ $# -lt 2 ]; then
usage
exit
fi
echo "Playlist Dir Name: $2"
PL_NAME=$2;
shift 2;
continue;
};
[[ $1 == -h ]] && {
usage
shift 1;
exit 0;
};
[[ $1 == -L ]] && {
LIST=true
shift 1;
continue;
};
echo "Parameter $1 discarded"
shift 1;
done
}
write_log() {
echo "$@"
echo "$@" >> "${DL_PATH}${log}"
}
usage(){
printf "Usage:
-pl_name <name>\tGive Playlist name for -log mode
-retry\t\tUse more Retries
-log\t\tDownload Playlist Video Titles to Log File
-h\t\tHelp
-L\t\tDowonload from FIle\n"
}
get_config "$@"
if [ "$(hostname)" == "serverhost" ]; then
DL_PATH="/OwnCloud/Torrents/Complete/"
elif [ ! -d ${DL_PATH} ]; then
mkdir "${DL_PATH}"
fi
if [ ${LOG} -eq 1 ]; then
for PL in ${PLAYLISTS[@]}; do
echo $PL
youtube-dl ${RETRIES} -w -i "${PL}" ${pl_options} --output "${DL_PATH}%(uploader)s/%(playlist)s/%(upload_date)s_%(title)s.%(ext)s"
done
else
write_log "Logfile ${log}"
if [[ "${PL_NAME}" == "" ]]; then write_log "Playlist folder in -pl_name missing"; usage; exit 0; fi
for PL in ${PLAYLISTS[@]}; do
log_name="${DL_PATH}pl_log_$(echo "${PL}" | rev | cut -f1 -d'=' | rev).log"
if [ ! -f ${log_name} ]; then
write_log "New Playlist File ${log_name}"
youtube-dl -j --flat-playlist "${PL}" ${pl_options} | cut -f4 -d',' | cut -f2 -d':' | tr -d ' "' | sed 's_^_https://youtu.be/_' > ${log_name}
else
write_log "${log_name} already present"
fi
while [ $(cat ${log_name} | wc -l) -ne 0 ] ; do
count=0
count_fail=0
count_suc=0
lines=$(cat ${log_name} | wc -l)
write_log "${lines} files to download"
for line in $(cat ${log_name}); do
youtube-dl ${RETRIES} -w -i "${line}" "${vid_options}" --output "${DL_PATH}%(uploader)s/${PL_NAME}/%(title)s_%(id)s.%(ext)s"
ret=$?
if [ ${ret} -eq 0 ]; then
((count_suc++))
write_log "Remove ${line} from file ${log_name}"
cat ${log_name} | tr '\n' ';' | sed 's#'"${line}"';##g' | tr ';' '\n' > buf
mv buf ${log_name}
else
((count_fail++))
fi
((count++))
write_log "${count}/${lines} : ${line} : ${ret} - Sucess: ${count_suc} : Fail: ${count_fail}"
done
done
done
fi
if [[ "${LIST}" == "true" ]]; then
if [ ! -f /data/youtubelist.txt ] ; then
echo "No youtubelist present"
fi
count=1
vid_num="$(cat /data/youtubelist.txt | wc -l | grep "")"
IFS=$'\n'; set -f
for VID in $(cat /data/youtubelist.txt); do
echo $VID
echo "********************* VID ${count} of ${vid_num} *********************"
if [ "$(echo ${VID} | grep youtube)" != "" ]; then
youtube-dl ${RETRIES} -w -i "${VID}" ${pl_options} --output "${DL_PATH}%(uploader)s/%(playlist)s/%(upload_date)s_%(title)s.%(ext)s"
else
youtube-dl ${RETRIES} -w -i "${VID}" --output "${DL_PATH}%(title)s_${count}.%(ext)s" --force-ipv4
fi
((count++))
done
fi
count=1
for VID in ${VIDEOS[@]}; do
echo "Video: $VID"
if [ "$(echo ${VID} | grep youtube)" != "" ]; then
youtube-dl ${RETRIES} -w -i "${VID}" --output "${DL_PATH}%(uploader)s/%(title)s.%(ext)s" --force-ipv4
else
youtube-dl ${RETRIES} -w -i "${VID}" --output "${DL_PATH}%(title)s_${count}.%(ext)s" --force-ipv4
el
fi
((count++))
done