-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmigrate.py
More file actions
139 lines (112 loc) · 4.47 KB
/
Copy pathmigrate.py
File metadata and controls
139 lines (112 loc) · 4.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
import os
import json
import sqlite3
import time
CACHE_DIR = "cache"
USERS_FILE = "users.json"
CACHED_INDEX_FILE = "cached.json" # Старый индекс ссылок
DB_PATH = "gsmarbot.db"
def get_connection():
return sqlite3.connect(DB_PATH)
def migrate_devices(conn):
print(f"\n📱 --- Миграция Устройств ---")
cursor = conn.cursor()
# Создаем таблицу, если нет
cursor.execute('''
CREATE TABLE IF NOT EXISTS devices (
id TEXT PRIMARY KEY,
url TEXT UNIQUE,
title TEXT,
data TEXT,
updated_at INTEGER
)
''')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_url ON devices (url)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_title ON devices (title)')
# Читаем файлы
if not os.path.exists(CACHE_DIR):
print("❌ Папка cache не найдена.")
return
files = [f for f in os.listdir(CACHE_DIR) if f.endswith('.json')]
total = len(files)
print(f"📂 Найдено файлов устройств: {total}")
count = 0
skipped = 0
# Также загрузим старый cached.json для сверки (опционально)
old_index = {}
if os.path.exists(CACHED_INDEX_FILE):
try:
with open(CACHED_INDEX_FILE, 'r') as f:
old_index = json.load(f)
print(f"ℹ️ Загружен старый индекс cached.json: {len(old_index)} ссылок.")
except: pass
for filename in files:
filepath = os.path.join(CACHE_DIR, filename)
try:
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read().strip()
if not content: continue
data = json.loads(content)
if 'id' not in data or 'link' not in data:
skipped += 1
continue
# Генерация descr, если нет (для старых записей)
if 'descr' not in data:
res = data.get('screen', '').split(',')[0].split('(')[0].strip()
cpu = data.get('CPU', 'CPU not specified')
data['descr'] = f"{res} | {cpu}"
json_dump = json.dumps(data, ensure_ascii=False)
updated_at = int(data.get('infodate', time.time()))
cursor.execute('''
INSERT OR REPLACE INTO devices (id, url, title, data, updated_at)
VALUES (?, ?, ?, ?, ?)
''', (data['id'], data['link'], data.get('title', 'Unknown'), json_dump, updated_at))
count += 1
if count % 1000 == 0: print(f" Processed {count} devices...")
except Exception:
skipped += 1
conn.commit()
print(f"✅ Устройства перенесены: {count}. Пропущено: {skipped}")
def migrate_users(conn):
print(f"\n👤 --- Миграция Пользователей ---")
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS user_settings (
user_id INTEGER PRIMARY KEY,
settings TEXT
)
''')
if not os.path.exists(USERS_FILE):
print("ℹ️ Файл users.json не найден, пропускаем.")
return
try:
with open(USERS_FILE, 'r', encoding='utf-8') as f:
users_data = json.load(f)
total_users = len(users_data)
print(f"📂 Найдено пользователей: {total_users}")
count = 0
for uid_str, settings_list in users_data.items():
try:
user_id = int(uid_str)
# settings_list это массив [1, 0, None...]
# Сохраняем его как JSON строку в базу
settings_json = json.dumps(settings_list)
cursor.execute('''
INSERT OR REPLACE INTO user_settings (user_id, settings)
VALUES (?, ?)
''', (user_id, settings_json))
count += 1
except:
pass
conn.commit()
print(f"✅ Пользователи перенесены: {count}")
except Exception as e:
print(f"❌ Ошибка чтения users.json: {e}")
def main():
conn = get_connection()
migrate_devices(conn)
migrate_users(conn)
conn.close()
print("\n🎉 ВСЯ МИГРАЦИЯ ЗАВЕРШЕНА!")
if __name__ == "__main__":
main()