Repository navigation
Expand file tree
/
Copy pathwiki_cli.py
More file actions
193 lines (165 loc) · 8 KB
/
Copy pathwiki_cli.py
File metadata and controls
193 lines (165 loc) · 8 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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
import requests
import sys
import os
import tempfile
import subprocess
import readline
# Activation du support de l'édition de ligne (flèches, backspace, copier-coller)
readline.parse_and_bind("tab: complete")
# --- Configuration Wiki.js ---
# Script conçu par BlablaLinux
# Remplacez les valeurs ci-dessous par vos propres accès API
WIKI_URL = "https://wiki.votre-domaine.be/graphql"
WIKI_TOKEN = "VOTRE_TOKEN_API_ICI"
def clear_screen():
os.system('clear' if os.name == 'posix' else 'cls')
def query_graphql(query, variables=None):
headers = {"Authorization": f"Bearer {WIKI_TOKEN}"}
try:
response = requests.post(WIKI_URL, json={'query': query, 'variables': variables}, headers=headers)
return response.json()
except Exception as e:
print(f"Erreur de connexion : {e}")
return {}
def get_text_from_editor(initial_content=""):
"""Ouvre l'éditeur par défaut (nano) pour éditer le contenu Markdown."""
editor = os.environ.get('EDITOR', 'nano')
with tempfile.NamedTemporaryFile(suffix=".md", delete=False, mode='w+', encoding='utf-8') as tf:
tf.write(initial_content)
temp_path = tf.name
subprocess.call([editor, temp_path])
with open(temp_path, 'r', encoding='utf-8') as tf:
content = tf.read()
if os.path.exists(temp_path):
os.remove(temp_path)
return content
def list_pages(filter_str=None):
query = "{ pages { list { id path title locale isPublished } } }"
res = query_graphql(query)
all_pages = res.get('data', {}).get('pages', {}).get('list', [])
if filter_str:
return [p for p in all_pages if filter_str.lower() in p['title'].lower() or filter_str.lower() in p['path'].lower()]
return all_pages
def get_single_page(page_id):
query = """query($id: Int!) { pages { single(id: $id) { id title description content path locale editor isPublished isPrivate tags { tag } } } }"""
return query_graphql(query, {"id": page_id}).get('data', {}).get('pages', {}).get('single')
def select_page_ui(action_name):
print(f"\n{'─'*10} {action_name} {'─'*10}")
search = input("Rechercher un mot-clé (ou Entrée pour tout lister) : ")
pages = list_pages(search)
if not pages:
print("Aucune page trouvée.")
return None
for i, p in enumerate(pages):
pub = "✔" if p['isPublished'] else "✘"
print(f"{i+1:2d}) [{p['locale'].upper()}] [{pub}] {p['title']} ({p['path']})")
idx_input = input("\nNuméro de la page (ou 'q' pour annuler) : ")
if idx_input.lower() == 'q' or not idx_input: return None
try:
return get_single_page(pages[int(idx_input)-1]['id'])
except:
return None
def create_page():
print("\n" + "─"*40 + "\n📄 CRÉATION D'UNE PAGE\n" + "─"*40)
title = input("Titre : ")
path = input("Slug (ex: mon-tuto ou en/my-tuto) : ")
if path.startswith("en/"):
locale = "en"
path = path[3:]
else:
locale = "fr"
if path.startswith("fr/"):
path = path[3:]
desc = input("Description : ")
print("Ouverture de l'éditeur pour le contenu...")
content = get_text_from_editor()
tags_raw = input("Tags (séparés par des virgules) : ")
tags = [t.strip() for t in tags_raw.split(',') if t.strip()]
is_published = (input("Publier immédiatement ? (O/n) : ") or "o").lower() == "o"
mutation = """
mutation($content: String!, $description: String!, $editor: String!, $isPublished: Boolean!, $isPrivate: Boolean!, $locale: String!, $path: String!, $tags: [String]!, $title: String!) {
pages { create(content: $content, description: $description, editor: $editor, isPublished: $isPublished, isPrivate: $isPrivate, locale: $locale, path: $path, tags: $tags, title: $title) {
responseResult { succeeded, message }
} } }"""
vars = {
"content": content, "description": desc, "editor": "markdown",
"isPublished": is_published, "isPrivate": False,
"locale": locale, "path": path, "tags": tags, "title": title
}
res = query_graphql(mutation, vars)
if 'errors' in res:
print(f"❌ Erreur : {res['errors'][0]['message']}")
else:
print(f"✅ Résultat : {res['data']['pages']['create']['responseResult']['message']}")
input("\nAppuyez sur Entrée...")
def update_page():
current = select_page_ui("✏️ MODIFICATION")
if not current: return
print("\n(Laissez vide pour conserver la valeur actuelle)")
title = input(f"Titre [{current['title']}] : ") or current['title']
desc = input(f"Description [{current['description']}] : ") or current['description']
path = input(f"Slug [{current['path']}] : ") or current['path']
if path.startswith("en/"):
locale = "en"
path = path[3:]
else:
locale = "fr"
if path.startswith("fr/"):
path = path[3:]
pub_choice = input(f"Publier ? (actuel: {current['isPublished']}) (o/n/Entrée) : ").lower()
is_published = current['isPublished'] if not pub_choice else (pub_choice == 'o')
content = get_text_from_editor(current['content']) if input("Modifier le contenu ? (o/N) : ").lower() == 'o' else current['content']
tags = [t.strip() for t in input("Tags : ").split(',')] if input("Changer les tags ? (o/N) : ").lower() == 'o' else [t['tag'] for t in current['tags']]
mutation = """
mutation($id: Int!, $content: String!, $description: String!, $editor: String!, $isPublished: Boolean!, $isPrivate: Boolean!, $locale: String!, $path: String!, $tags: [String]!, $title: String!) {
pages { update(id: $id, content: $content, description: $description, editor: $editor, isPublished: $isPublished, isPrivate: $isPrivate, locale: $locale, path: $path, tags: $tags, title: $title) {
responseResult { succeeded, message }
} } }"""
vars = {
"id": current['id'], "content": content, "description": desc, "editor": current['editor'],
"isPublished": is_published, "isPrivate": current['isPrivate'],
"locale": locale, "path": path, "tags": tags, "title": title
}
res = query_graphql(mutation, vars)
if 'errors' in res:
print(f"❌ Erreur : {res['errors'][0]['message']}")
else:
print(f"✅ Résultat : {res['data']['pages']['update']['responseResult']['message']}")
input("\nAppuyez sur Entrée...")
def delete_page():
current = select_page_ui("🗑️ SUPPRESSION")
if not current: return
if input(f"⚠️ Confirmer la suppression définitive de '{current['title']}' ? (oui/non) : ").lower() == 'oui':
res = query_graphql("mutation($id: Int!) { pages { delete(id: $id) { responseResult { succeeded, message } } } }", {"id": current['id']})
print(f"✅ Résultat : {res['data']['pages']['delete']['responseResult']['message']}")
input("\nAppuyez sur Entrée...")
def main():
while True:
clear_screen()
print("\n" + "═"*30 + "\n WIKI.JS CLI MANAGER\n by BlablaLinux\n" + "═"*30)
print(" 1. Lister / Rechercher les pages")
print(" 2. Créer une nouvelle page")
print(" 3. Modifier une page existante")
print(" 4. Supprimer une page")
print(" q. Quitter le programme")
print("─"*30)
choix = input("Action : ").lower()
if choix == '1':
s = input("Recherche (Entrée pour tout) : ")
pages = list_pages(s)
print("\n" + "─"*40)
for p in pages:
st = "✔" if p['isPublished'] else "✘"
print(f"• [{p['locale'].upper()}] [{st}] {p['title']} ({p['path']})")
print("─"*40)
input("\nAppuyez sur Entrée...")
elif choix == '2': create_page()
elif choix == '3': update_page()
elif choix == '4': delete_page()
elif choix == 'q':
clear_screen()
user_name = os.environ.get('USER', 'Ami')
print(f"Au revoir {user_name} ! Merci d'utiliser Wiki CLI by BlablaLinux.")
break
if __name__ == "__main__":
main()