Alex7590 commited on
Commit
488fef5
·
verified ·
1 Parent(s): 5c58298

Delete update_from_repo.py

Browse files
Files changed (1) hide show
  1. update_from_repo.py +0 -385
update_from_repo.py DELETED
@@ -1,385 +0,0 @@
1
- #!/usr/bin/env python3
2
- # Version 1.0.1
3
- """
4
- Script to automatically update code from a GitHub repository.
5
- Clones the repository into a temporary folder and replaces required files.
6
- """
7
-
8
- import os
9
- import sys
10
- import shutil
11
- import tempfile
12
- from CONFIG.messages import Messages, safe_get_messages
13
- import subprocess
14
- from pathlib import Path
15
- from datetime import datetime
16
-
17
- # Configuration
18
- REPO_URL = "https://github.com/chelaxian/tg-ytdlp-bot.git"
19
- # Use explicit branch
20
- BRANCH = "newdesign2"
21
- # BRANCH = "main"
22
-
23
- # Files and directories that MUST NOT be updated
24
- EXCLUDED_FILES = [
25
- "CONFIG/domains.py", # Main configuration file (contains domains data)
26
- "CONFIG/config.py", # Main configuration file (contains sensitive data)
27
- #"requirements.txt", # Dependencies may differ
28
- ".env", # Environment variables
29
- ".bot_pid", # Bot PID file
30
- "bot.log", # Bot logs
31
- "runtime.log", # Runtime logs
32
- "magic.session", # Pyrogram session
33
- "magic.session-journal", # Session journal
34
- "dump.json", # Firebase dump
35
- "script.sh", # Script for updating porn lists
36
- #"update_from_repo.py", # Do not overwrite the updater itself
37
- #"update.sh", # Do not overwrite the update shell script
38
- ]
39
-
40
- EXCLUDED_DIRS = [
41
- "venv", # Virtual environment
42
- ".git", # Git repository
43
- "__pycache__", # Python cache
44
- "_backup", # Backups
45
- "users", # User data
46
- "cookies", # Cookie files
47
- "TXT", # Text files
48
- "_arabic_fonts_amiri", # Fonts
49
- "_cursor", # Cursor temp workspace
50
- ]
51
-
52
- # Additional directories/files that must always be synced
53
- INCLUDE_DIRS = [
54
- "web", # Includes templates, static assets, and the FastAPI app itself
55
- "CONFIG/templates", # In case templates/localizations are added
56
- ]
57
-
58
- ALWAYS_INCLUDE_FILES = [
59
- "requirements.txt",
60
- ]
61
-
62
- def log(message, level="INFO"):
63
- """Logging with timestamp"""
64
- timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
65
- print(f"[{timestamp}] {level}: {message}")
66
-
67
- def _is_inside(path: str, directory: str) -> bool:
68
- """Helper: checks if path is the directory itself or inside it."""
69
- return path == directory or path.startswith(f"{directory}/")
70
-
71
-
72
- def should_update_file(file_path, exclude_include_dirs=False):
73
- """Checks whether the file should be updated
74
-
75
- Args:
76
- file_path: Path to the file to check
77
- exclude_include_dirs: If True, exclude files from INCLUDE_DIRS
78
- (they will be synced separately via sync_include_directories)
79
- """
80
- # Check excluded files
81
- for excluded in EXCLUDED_FILES:
82
- if file_path == excluded:
83
- return False
84
-
85
- # Check excluded directories
86
- for excluded_dir in EXCLUDED_DIRS:
87
- if _is_inside(file_path, excluded_dir):
88
- return False
89
-
90
- # If exclude_include_dirs is True, skip files from INCLUDE_DIRS
91
- # (they will be synced via sync_include_directories)
92
- if exclude_include_dirs:
93
- for include_dir in INCLUDE_DIRS:
94
- if _is_inside(file_path, include_dir):
95
- return False
96
-
97
- # Ensure explicitly listed files are synced
98
- if file_path in ALWAYS_INCLUDE_FILES:
99
- return True
100
-
101
- # Ensure specific directories (e.g. web UI) are synced entirely
102
- # (only if not excluding them)
103
- if not exclude_include_dirs:
104
- for include_dir in INCLUDE_DIRS:
105
- if _is_inside(file_path, include_dir):
106
- return True
107
-
108
- # Update Python files
109
- if file_path.endswith('.py'):
110
- return True
111
-
112
- # Update files from LANGUAGES directory (all file types)
113
- if file_path.startswith('CONFIG/LANGUAGES/'):
114
- return True
115
-
116
- return False
117
-
118
- def backup_file(file_path):
119
- """Create a backup copy of a file"""
120
- try:
121
- if os.path.exists(file_path):
122
- # Use minute-level timestamp to group all backups within a minute
123
- backup_ts = datetime.now().strftime('%Y%m%d_%H%M')
124
- backup_path = f"{file_path}.backup_{backup_ts}"
125
- shutil.copy2(file_path, backup_path)
126
- log(f"Backup created: {backup_path}")
127
- return backup_path
128
- except Exception as e:
129
- log(f"Error creating backup for {file_path}: {e}", "ERROR")
130
- return None
131
-
132
- def clone_repository(temp_dir):
133
- messages = safe_get_messages(None)
134
- """Clone the repository into the temporary folder"""
135
- try:
136
- log(f"📥 Cloning repository into {temp_dir}...")
137
-
138
- # Command for cloning
139
- cmd = [
140
- 'git', 'clone',
141
- '--branch', BRANCH,
142
- '--depth', '1', # Only the last commit
143
- '--single-branch',
144
- REPO_URL,
145
- temp_dir
146
- ]
147
-
148
- result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
149
-
150
- if result.returncode == 0:
151
- messages = safe_get_messages()
152
- log(messages.UPDATE_REPOSITORY_CLONED_SUCCESS_MSG)
153
- return True
154
- else:
155
- messages = safe_get_messages()
156
- log(messages.UPDATE_CLONE_ERROR_MSG.format(error=result.stderr), "ERROR")
157
- return False
158
-
159
- except subprocess.TimeoutExpired:
160
- messages = safe_get_messages()
161
- log(messages.UPDATE_CLONE_TIMEOUT_MSG, "ERROR")
162
- return False
163
- except Exception as e:
164
- messages = safe_get_messages()
165
- log(messages.UPDATE_CLONE_EXCEPTION_MSG.format(error=e), "ERROR")
166
- return False
167
-
168
- def find_python_files(source_dir, exclude_include_dirs=False):
169
- """Find all Python files and LANGUAGES files in the source directory
170
-
171
- Args:
172
- source_dir: Source directory to search
173
- exclude_include_dirs: If True, exclude files from INCLUDE_DIRS
174
- (they will be synced separately via sync_include_directories)
175
- """
176
- files_to_update = []
177
-
178
- for root, dirs, files in os.walk(source_dir):
179
- # Exclude unnecessary directories
180
- dirs[:] = [d for d in dirs if d not in ['.git', '__pycache__', 'venv']]
181
-
182
- # Also exclude INCLUDE_DIRS from walking if we're excluding them
183
- if exclude_include_dirs:
184
- for include_dir in INCLUDE_DIRS:
185
- if include_dir in dirs:
186
- dirs.remove(include_dir)
187
-
188
- for file in files:
189
- # Build relative path
190
- rel_path = os.path.relpath(os.path.join(root, file), source_dir)
191
- if should_update_file(rel_path, exclude_include_dirs=exclude_include_dirs):
192
- files_to_update.append(rel_path)
193
-
194
- return sorted(files_to_update)
195
-
196
-
197
- def sync_include_directories(source_root: str) -> None:
198
- """Fully sync directories from INCLUDE_DIRS (hard copy)."""
199
- for include_dir in INCLUDE_DIRS:
200
- source_path = os.path.join(source_root, include_dir)
201
- if not os.path.exists(source_path):
202
- log(f"⚠️ Include directory missing in repo: {include_dir}", "WARNING")
203
- continue
204
-
205
- target_path = Path(include_dir)
206
- target_path.parent.mkdir(parents=True, exist_ok=True)
207
-
208
- # Count files before removal
209
- file_count = 0
210
- if target_path.exists():
211
- for root, dirs, files in os.walk(target_path):
212
- file_count += len(files)
213
- log(f"🧹 Removing existing directory: {include_dir} ({file_count} files)")
214
- shutil.rmtree(target_path)
215
-
216
- # Count files to copy
217
- files_to_copy = []
218
- for root, dirs, files in os.walk(source_path):
219
- for file in files:
220
- rel_path = os.path.relpath(os.path.join(root, file), source_path)
221
- files_to_copy.append(rel_path)
222
-
223
- log(f"📦 Syncing directory: {include_dir} ({len(files_to_copy)} files)")
224
- shutil.copytree(source_path, target_path)
225
- log(f"✅ Successfully synced {include_dir}: {len(files_to_copy)} files updated")
226
-
227
- def update_file_from_source(source_file, target_file):
228
- """Update a file from the source repository"""
229
- try:
230
- # Create directories if missing (only if file is not in the project root)
231
- dir_name = os.path.dirname(target_file)
232
- if dir_name: # Directory path is not empty
233
- os.makedirs(dir_name, exist_ok=True)
234
- log(f"📁 Created directory: {dir_name}")
235
-
236
- # Create a backup
237
- backup_path = backup_file(target_file)
238
-
239
- # Copy the file
240
- shutil.copy2(source_file, target_file)
241
-
242
- log(f"Updated file: {target_file}")
243
- if backup_path:
244
- log(f"Backup: {backup_path}")
245
-
246
- return True
247
- except Exception as e:
248
- log(f"Error updating file {target_file}: {e}", "ERROR")
249
- return False
250
-
251
- def move_backups_to_backup_dir():
252
- messages = safe_get_messages(None)
253
- """Move all *.backup* files into _backup directory, keeping relative paths."""
254
- try:
255
- log("📦 Moving backups to _backup/...")
256
- cmd = "mkdir -p _backup && find . -path './_backup' -prune -o -type f -name \"*.backup*\" -print0 | sed -z 's#^\\./##' | rsync -a --relative --from0 --files-from=- --remove-source-files ./ _backup/"
257
- subprocess.run(["bash", "-lc", cmd], check=True)
258
- messages = safe_get_messages()
259
- log(messages.UPDATE_BACKUPS_MOVED_MSG)
260
- except Exception as e:
261
- log(f"⚠️ Failed to move backups: {e}", "WARNING")
262
-
263
- def main():
264
- messages = safe_get_messages(None)
265
- """Main update routine"""
266
- log("🚀 Starting update from GitHub repository")
267
- log(f"Repository: {REPO_URL}")
268
- log(f"Branch: {BRANCH}")
269
-
270
- # Ensure we are in the correct directory
271
- if not os.path.exists("magic.py"):
272
- log("❌ File magic.py not found. Make sure you run this in the bot folder.", "ERROR")
273
- return False
274
-
275
- # Ensure LANGUAGES directory exists
276
- languages_dir = "CONFIG/LANGUAGES"
277
- if not os.path.exists(languages_dir):
278
- try:
279
- os.makedirs(languages_dir, exist_ok=True)
280
- log(f"📁 Created LANGUAGES directory: {languages_dir}")
281
- except Exception as e:
282
- log(f"⚠️ Failed to create LANGUAGES directory: {e}", "WARNING")
283
-
284
- # Ensure git is available
285
- if not shutil.which('git'):
286
- log("❌ Git not found. Please install Git to use this updater.", "ERROR")
287
- return False
288
-
289
- # Create temp directory
290
- temp_dir = None
291
- try:
292
- temp_dir = tempfile.mkdtemp(prefix="tg-ytdlp-update-")
293
- log(f"📁 Temporary directory created: {temp_dir}")
294
-
295
- # Clone repository
296
- if not clone_repository(temp_dir):
297
- return False
298
-
299
- # Find files to update (exclude INCLUDE_DIRS - they will be synced separately)
300
- files_to_update = find_python_files(temp_dir, exclude_include_dirs=True)
301
-
302
- if not files_to_update:
303
- log("❌ No files found to update", "ERROR")
304
- return False
305
-
306
- log(f"📋 Found {len(files_to_update)} files to update")
307
-
308
- # Show file list to update
309
- log("📝 Files to update:")
310
- for file_path in files_to_update:
311
- log(f" - {file_path}")
312
-
313
- # Ask for confirmation
314
- response = input("\n🤔 Proceed with update? (y/N): ").strip().lower()
315
- if response not in ['y', 'yes']:
316
- messages = safe_get_messages()
317
- log(messages.UPDATE_CANCELED_BY_USER_MSG)
318
- return False
319
-
320
- # Update files
321
- updated_count = 0
322
- failed_count = 0
323
-
324
- for file_path in files_to_update:
325
- log(f"🔄 Updating {file_path}...")
326
-
327
- source_file = os.path.join(temp_dir, file_path)
328
- target_file = file_path
329
-
330
- if update_file_from_source(source_file, target_file):
331
- updated_count += 1
332
- else:
333
- failed_count += 1
334
-
335
- # Results
336
- log("=" * 50)
337
- log("📊 Update results:")
338
- log(f"✅ Successfully updated: {updated_count}")
339
- log(f"❌ Errors: {failed_count}")
340
- log(f"📁 Total files: {len(files_to_update)}")
341
-
342
- # Force-sync required directories (e.g., web/)
343
- log("=" * 50)
344
- log("📦 Syncing include directories (web/, etc.)...")
345
- sync_include_directories(temp_dir)
346
-
347
- # Move backups into _backup/
348
- move_backups_to_backup_dir()
349
-
350
- if failed_count == 0:
351
- log("🎉 All files updated successfully!")
352
- return True
353
- else:
354
- log(f"⚠️ Updated with errors: {failed_count} files", "WARNING")
355
- return False
356
-
357
- except Exception as e:
358
- log(f"❌ Critical error: {e}", "ERROR")
359
- return False
360
-
361
- finally:
362
- # Remove temp directory
363
- if temp_dir and os.path.exists(temp_dir):
364
- try:
365
- shutil.rmtree(temp_dir)
366
- log(f"🗑️ Temporary directory removed: {temp_dir}")
367
- except Exception as e:
368
- log(f"⚠️ Failed to remove temporary directory: {e}", "WARNING")
369
-
370
- def show_excluded_files():
371
- """Display excluded files and directories"""
372
- log("📋 Excluded files:")
373
- for file_path in EXCLUDED_FILES:
374
- log(f" - {file_path}")
375
-
376
- log("📁 Excluded directories:")
377
- for dir_path in EXCLUDED_DIRS:
378
- log(f" - {dir_path}/")
379
-
380
- if __name__ == "__main__":
381
- if len(sys.argv) > 1 and sys.argv[1] == "--show-excluded":
382
- show_excluded_files()
383
- else:
384
- success = main()
385
- sys.exit(0 if success else 1)