huijio commited on
Commit
dfd6e11
·
verified ·
1 Parent(s): d414707

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +115 -243
app.py CHANGED
@@ -1,252 +1,124 @@
1
- #!/bin/bash
2
-
3
- # =============================================
4
- # ADNADE IP SWAPPER - MONITOR MODE
5
- # =============================================
6
-
7
- # Configuration
8
- CONFIG_DIR="$HOME/.adnade_swapper"
9
- SHARED_DIR="$HOME/.adnade_shared"
10
- TEMPLATE_FILE="$SHARED_DIR/template.txt"
11
- IP_LIST_FILE="$CONFIG_DIR/ip_list.txt"
12
- GENERATED_URLS_FILE="$CONFIG_DIR/generated_urls.txt"
13
- PID_FILE="$CONFIG_DIR/surfbar.pid"
14
- LAST_START_FILE="$CONFIG_DIR/last_start.time"
15
- CONFIG_FILE="$CONFIG_DIR/settings.conf"
16
- LOG_FILE="$CONFIG_DIR/surfbar.log"
17
-
18
- # Hardcoded list of IP addresses (same as Flask API)
19
- HARDCODED_IPS=(
20
- "108.181.33.119"
21
- "108.181.34.151"
22
- "108.181.34.157"
23
- "108.181.90.163"
24
- "108.181.34.177"
25
- "208.87.241.1"
26
- "208.87.241.149"
27
- "208.87.242.125"
28
- "208.87.242.233"
29
- "108.181.11.171"
30
- "108.181.6.9"
31
- "108.181.33.135"
32
- "108.181.9.39"
33
- "108.181.11.193"
34
- "108.181.21.229"
35
- "108.181.5.31"
36
- "108.181.3.54"
37
- "108.181.5.51"
38
  "108.181.11.173"
39
- )
40
-
41
- # ⚙️ Configurable Settings with defaults
42
- REFRESH_RATE=5
43
- RESTART_INTERVAL=10800 # 3 hours in seconds
44
- COOLDOWN_PERIOD=600 # 10 minutes in seconds
45
- MAX_RETRIES=5
46
- RETRY_DELAY=30
47
-
48
- # Colors
49
- RED='\033[0;31m'
50
- GREEN='\033[0;32m'
51
- YELLOW='\033[1;33m'
52
- BLUE='\033[0;34m'
53
- PURPLE='\033[0;35m'
54
- CYAN='\033[0;36m'
55
- NC='\033[0m'
56
-
57
- # Logging function
58
- log() {
59
- local message="$1"
60
- local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
61
- echo "[$timestamp] $message" >> "$LOG_FILE"
62
- echo -e "$message"
63
- }
64
-
65
- # Initialize system
66
- init_system() {
67
- mkdir -p "$CONFIG_DIR"
68
- mkdir -p "$SHARED_DIR"
69
-
70
- # Load or create config
71
- if [ -f "$CONFIG_FILE" ]; then
72
- source "$CONFIG_FILE"
73
- else
74
- save_config
75
- fi
76
-
77
- if [ ! -f "$TEMPLATE_FILE" ]; then
78
- echo "# Add your working AdNade URL template here" > "$TEMPLATE_FILE"
79
- echo "# Example: http://192.168.1.1:8080/path?param=value" >> "$TEMPLATE_FILE"
80
- fi
81
-
82
- # Initialize log file
83
- echo "=== AdNade Swapper Started ===" > "$LOG_FILE"
84
- }
85
-
86
- # Save configuration
87
- save_config() {
88
- cat > "$CONFIG_FILE" << EOF
89
- # AdNade Swapper Configuration
90
- REFRESH_RATE=$REFRESH_RATE
91
- RESTART_INTERVAL=$RESTART_INTERVAL
92
- COOLDOWN_PERIOD=$COOLDOWN_PERIOD
93
- MAX_RETRIES=$MAX_RETRIES
94
- RETRY_DELAY=$RETRY_DELAY
95
- EOF
96
- log "${GREEN}✅ Configuration saved${NC}"
97
- }
98
-
99
- # Pre-flight verification
100
- verify_setup() {
101
- log "${CYAN}🔍 Verifying setup...${NC}"
102
-
103
- # Check template
104
- if [ ! -s "$TEMPLATE_FILE" ] || grep -q "^#" "$TEMPLATE_FILE"; then
105
- log "${RED}❌ No template URL found!${NC}"
106
- return 1
107
- fi
108
-
109
- # Check firefox
110
- if ! command -v firefox &> /dev/null; then
111
- log "${RED}❌ Firefox not installed! Run: pkg install firefox${NC}"
112
- return 1
113
- fi
114
-
115
- log "${GREEN}✅ Setup verified - Template: OK, Firefox: OK${NC}"
116
- return 0
117
- }
118
-
119
- # Get browser process count
120
- get_browser_process_count() {
121
- pgrep -c -f "firefox" 2>/dev/null || echo 0
122
- }
123
-
124
- # Memory display
125
- show_memory_status() {
126
- local total_mem=$(free -m | awk 'NR==2{print $2}')
127
- local used_mem=$(free -m | awk 'NR==2{print $3}')
128
- local mem_percent=$((used_mem * 100 / total_mem))
129
-
130
- local swap_total=$(free -m | awk 'NR==3{print $2}')
131
- local swap_used=$(free -m | awk 'NR==3{print $3}')
132
- local swap_percent=0
133
- [ $swap_total -gt 0 ] && swap_percent=$((swap_used * 100 / swap_total))
134
-
135
- local browser_count=$(get_browser_process_count)
136
-
137
- echo -e "${CYAN}🖥️ MEMORY STATUS${NC}"
138
- echo -e "${BLUE}══════════════════════════════════${NC}"
139
- echo -e "📊 RAM: ${used_mem}MB/${total_mem}MB (${mem_percent}%)"
140
- echo -e "💾 SWAP: ${swap_used}MB/${swap_total}MB (${swap_percent}%)"
141
- echo -e "🌐 Browser processes: $browser_count"
142
- echo -e "${BLUE}══════════════════════════════════${NC}"
143
- }
144
-
145
- # Base64 URL decode
146
- base64_url_decode() {
147
- local s="$1"
148
- s=$(echo "$s" | sed 's/_/\//g; s/-/+/g')
149
- local pad=$((4 - ${#s} % 4))
150
- if [ $pad -lt 4 ]; then
151
- s="${s}$(printf '=%.0s' $(seq 1 $pad))"
152
- fi
153
- echo "$s" | base64 -d
154
- }
155
-
156
- # Base64 URL encode
157
- base64_url_encode() {
158
- echo -n "$1" | base64 | tr -d '\n' | sed 's/=*$//; s/\//_/g; s/\+/-/g'
159
- }
160
-
161
- # IP Swapping Engine (same as Flask API)
162
- swap_ip_in_url() {
163
- local original_url="$1"
164
- local new_ip="$2"
165
-
166
- [[ -z "$original_url" || -z "$new_ip" ]] && return 1
167
-
168
- # Parse the URL
169
- local scheme=$(echo "$original_url" | awk -F: '{print $1}')
170
- local host_port_path=$(echo "$original_url" | sed -E "s|^${scheme}://||")
171
- local host=$(echo "$host_port_path" | awk -F/ '{print $1}' | awk -F: '{print $1}')
172
- local port=$(echo "$host_port_path" | awk -F/ '{print $1}' | awk -F: '{print $2}')
173
- local path_query=$(echo "$host_port_path" | sed -E "s|^[^/]*||")
174
-
175
- # Replace IP in host
176
- local new_netloc="$new_ip"
177
- [ -n "$port" ] && new_netloc="$new_netloc:$port"
178
-
179
- # Process query parameters
180
- local query=$(echo "$path_query" | grep -oP '\?.*' | sed 's/^//')
181
- local new_query=""
182
-
183
- if [ -n "$query" ]; then
184
- IFS='&' read -ra params <<< "$query"
185
- for param in "${query[@]}"; do
186
- local key=$(echo "$param" | cut -d'=' -f1)
187
- local value=$(echo "$param" | cut -d'=' -f2-)
188
 
189
- if [ "$key" = "r" ]; then
190
- # Decode and process r parameter
191
- local decoded_r "$value")
192
- if [ -n "$decoded_r" ]; then
193
- # Replace IP in decoded r value
194
- local new_decoded_r | sed "s/$host/$new_ip/g")
195
- # Re-encode value
196
- value=$(base64_url_encode "$modified_r")
197
- fi
198
- fi
199
- fi
200
- new_query="${new_query}&${key}=${value}"
201
- done
202
- new_query="${new_query:1}"
203
- fi
204
 
205
- # Reconstruct URL
206
- echo "${scheme}://${new_netloc}${path_query%%\?*}${new_query:+?$new_query}"
207
- }
208
 
209
- # Generate URLs
210
- generate_urls() {
211
- log "${CYAN}🔄 Generating fresh URLs...${NC}"
212
-
213
- if [ ! -s "$TEMPLATE_FILE" ] || grep -q "^#" "$TEMPLATE_FILE"; then
214
- log "${RED}❌ No template URL! Use option 2 first.${NC}"
215
- return 1
216
- fi
217
-
218
- local template_url=$(grep -v "^#" "$TEMPLATE_FILE" | head -1)
219
-
220
- # Create temporary file first
221
- local temp_file="$GENERATED_URLS_FILE.tmp"
222
- rm -f "$temp_file"
223
- touch "$temp_file"
224
 
225
- local count=0
226
- local success_count=0
227
 
228
- for ip in "${HARDCODED_IPS[@]}"; do
229
- ((count++))
230
- local new_url=$(swap_ip_in_url "$template_url" "$ip")
231
-
232
- if [[ -n "$new_url" ]]; then
233
- echo "$new_url" >> "$temp_file"
234
- ((success_count++))
235
- else
236
- log "${RED}❌ Failed to generate URL for IP: $ip${NC}"
237
- fi
238
- done
239
 
240
- # Atomic replace
241
- if [ -s "$temp_file" ]; then
242
- mv -f "$temp_file" "$GENERATED_URLS_FILE"
243
- log "${GREEN}✅ Generated $success_count/$count URLs${NC}"
244
- else
245
- log "${RED}❌ CRITICAL: No URLs generated!${NC}"
246
- return 1
247
- fi
248
 
249
- return 0
250
- }
251
 
252
- # ... rest of the script remains the same ...
 
 
1
+ from flask import Flask, request, jsonify
2
+ import base64
3
+ import re
4
+ from urllib.parse import urlparse, urlunparse, parse_qs, urlencode
5
+ from concurrent.futures import ThreadPoolExecutor
6
+
7
+ app = Flask(__name__)
8
+
9
+ # Hardcoded list of IPs from the Termux script
10
+ HARDCODED_IPS = [
11
+ "108.181.33.119",
12
+ "108.181.34.151",
13
+ "108.181.34.157",
14
+ "108.181.90.163",
15
+ "108.181.34.177",
16
+ "208.87.241.1",
17
+ "208.87.241.149",
18
+ "208.87.242.125",
19
+ "208.87.242.233",
20
+ "108.181.11.171",
21
+ "108.181.6.9",
22
+ "108.181.33.135",
23
+ "108.181.9.39",
24
+ "108.181.11.193",
25
+ "108.181.21.229",
26
+ "108.181.5.31",
27
+ "108.181.3.54",
28
+ "108.181.5.51",
 
 
 
 
 
 
 
 
 
29
  "108.181.11.173"
30
+ ]
31
+
32
+ def base64_url_decode(s):
33
+ s = s.replace('_', '/').replace('-', '+')
34
+ pad = len(s) % 4
35
+ if pad:
36
+ s += '=' * (4 - pad)
37
+ return base64.b64decode(s).decode('utf-8')
38
+
39
+ def base64_url_encode(s):
40
+ return base64.b64encode(s.encode('utf-8')).decode('utf-8').replace('/', '_').replace('+', '-').rstrip('=')
41
+
42
+ def swap_ip_in_url(template_url, new_ip):
43
+ try:
44
+ # Split URL into base and query string
45
+ base_url = template_url.split('?')[0]
46
+ query_string = '?'.join(template_url.split('?')[1:]) if '?' in template_url else ''
47
+
48
+ # Extract original IP
49
+ old_ip_match = re.search(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', base_url)
50
+ if not old_ip_match:
51
+ return None
52
+ old_ip = old_ip_match.group(0)
53
+
54
+ # Replace IP in base URL
55
+ new_base_url = base_url.replace(old_ip, new_ip)
56
+
57
+ # Process query parameters
58
+ if not query_string:
59
+ return new_base_url
60
+
61
+ params = parse_qs(query_string, keep_blank_values=True)
62
+ new_params = {}
63
+
64
+ for key, values in params.items():
65
+ new_values = []
66
+ for value in values:
67
+ if key == 'r':
68
+ # Special handling for 'r' parameter
69
+ try:
70
+ # URL decode value first
71
+ url_decoded = value.replace('%2F', '/').replace('%3D', '=').replace('%3F', '?').replace('%5F', '_')
72
+
73
+ # Base64 URL decode
74
+ safe_value = url_decoded.replace('_', '/').replace('-', '+')
75
+ decoded_r = base64_url_decode(safe_value)
76
+
77
+ if decoded_r:
78
+ # Replace IP in decoded value
79
+ new_decoded_r = decoded_r.replace(old_ip, new_ip)
80
+ # Re-encode
81
+ new_value = base64_url_encode(new_decoded_r)
82
+ new_values.append(new_value)
83
+ else:
84
+ new_values.append(value)
85
+ except:
86
+ new_values.append(value)
87
+ else:
88
+ new_values.append(value)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
+ new_params[key] = new_values
91
+
92
+ # Rebuild query string
93
+ new_query = urlencode(new_params, doseq=True)
94
+
95
+ return f"{new_base_url}?{new_query}"
 
 
 
 
 
 
 
 
 
96
 
97
+ except Exception as e:
98
+ print(f"Error processing URL: {str(e)}")
99
+ return None
100
 
101
+ @app.route('/')
102
+ def home():
103
+ return "IP Swapper API is running. Use POST /generate with JSON payload."
104
+
105
+ @app.route('/generate', methods=['POST'])
106
+ def generate_urls():
107
+ data = request.get_json()
 
 
 
 
 
 
 
 
108
 
109
+ if not data or 'template_url' not in data:
110
+ return jsonify({"error": "template_url is required"}), 400
111
 
112
+ template_url = data['template_url'].strip()
 
 
 
 
 
 
 
 
 
 
113
 
114
+ with ThreadPoolExecutor() as executor:
115
+ results = []
116
+ for ip in HARDCODED_IPS:
117
+ new_url = swap_ip_in_url(template_url, ip)
118
+ if new_url:
119
+ results.append(new_url)
 
 
120
 
121
+ return jsonify({"generated_urls": results})
 
122
 
123
+ if __name__ == '__main__':
124
+ app.run(host='0.0.0.0', port=7860, threaded=True)