-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
506 lines (436 loc) · 17.2 KB
/
app.py
File metadata and controls
506 lines (436 loc) · 17.2 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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
from viktor import ViktorController
from viktor.parametrization import ViktorParametrization
import viktor as vkt
import requests
import os
import pandas as pd
from io import BytesIO
import openpyxl
def _get_sharepoint_sites():
integration = vkt.external.OAuth2Integration('microsoft-entra')
access_token = integration.get_access_token()
# Test SharePoint access by getting list of sites
headers = {
'Authorization': f'Bearer {access_token}',
'Accept': 'application/json'
}
try:
# Try to get SharePoint sites
response = requests.get(
'https://graph.microsoft.com/v1.0/sites?search=*',
headers=headers
)
if response.status_code == 200:
sites = response.json()
return [
vkt.OptionListElement(
label=str(site.get('displayName', 'N/A')),
value=str(site.get('webUrl', 'N/A'))
) for site in sites.get('value', [])
]
except Exception as e:
print("Error occurred, empty list: ", e)
return []
def get_sharepoint_options(params, **kwargs):
return _get_sharepoint_sites()
def is_file(params, type, **kwargs):
if params.selected_name:
return params.selected_name.split(".")[1] == type
return False
class Parametrization(ViktorParametrization):
header = vkt.Text("# Select SharePoint site")
url = vkt.OptionField("SharePoint site", options=get_sharepoint_options)
lb = vkt.LineBreak()
header2 = vkt.Text("# Selected document to preview")
selected_name = vkt.TextField("Selected document Name")
selected_url = vkt.TextField("Selected document URL")
class Controller(ViktorController):
label = "My Controller"
parametrization = Parametrization
@vkt.TableView("Excel File", duration_guess=1, visible=lambda params, **kwargs: is_file(params, "xlsx", **kwargs))
def excel_view(self, params, **kwargs):
if not params.selected_url:
return vkt.TableResult(pd.DataFrame({"Error": ["No file selected"]}))
# Get access token
integration = vkt.external.OAuth2Integration('microsoft-entra')
access_token = integration.get_access_token()
# Download the file from SharePoint using the Graph API URL
headers = {
'Authorization': f'Bearer {access_token}',
}
try:
response = requests.get(params.selected_url, headers=headers)
if response.status_code != 200:
return vkt.TableResult(pd.DataFrame({
"Error": [f"Failed to download file: {response.status_code}"]
}))
# Load Excel file from bytes
excel_bytes = BytesIO(response.content)
df = pd.read_excel(excel_bytes)
return vkt.TableResult(df)
except Exception as e:
return vkt.TableResult(pd.DataFrame({
"Error": [f"Error loading Excel file: {str(e)}"]
}))
@vkt.PDFView("Word File", duration_guess=1, visible=lambda params, **kwargs: is_file(params, "docx", **kwargs))
def docx_view(self, params, **kwargs):
# Get access token
integration = vkt.external.OAuth2Integration('microsoft-entra')
access_token = integration.get_access_token()
# Download the file from SharePoint using the Graph API URL
headers = {
'Authorization': f'Bearer {access_token}',
}
try:
response = requests.get(params.selected_url, headers=headers)
if response.status_code != 200:
# Return an empty PDF with error message
raise Exception(f"Failed to download file: {response.status_code}")
# Return PDF data
word_file = vkt.File.from_data(response.content)
with word_file.open_binary() as f:
pdf_file = vkt.convert_word_to_pdf(f)
return vkt.PDFResult(file=pdf_file)
except Exception as e:
# Create a simple error PDF or raise the exception
raise Exception(f"Error loading PDF file: {str(e)}")
@vkt.PDFView("PDF File", duration_guess=1, visible=lambda params, **kwargs: is_file(params, "pdf", **kwargs))
def pdf_view(self, params, **kwargs):
# Get access token
integration = vkt.external.OAuth2Integration('microsoft-entra')
access_token = integration.get_access_token()
# Download the file from SharePoint using the Graph API URL
headers = {
'Authorization': f'Bearer {access_token}',
}
try:
response = requests.get(params.selected_url, headers=headers)
if response.status_code != 200:
# Return an empty PDF with error message
raise Exception(f"Failed to download file: {response.status_code}")
# Return PDF data
pdf_file = vkt.File.from_data(response.content)
return vkt.PDFResult(file=pdf_file)
except Exception as e:
# Create a simple error PDF or raise the exception
raise Exception(f"Error loading PDF file: {str(e)}")
@vkt.WebView("Site Contents", duration_guess=1)
def site_contents_view(self, params, **kwargs):
if not params.url:
return vkt.WebResult(html="<h2>Please select a SharePoint site first</h2>")
integration = vkt.external.OAuth2Integration('microsoft-entra')
access_token = integration.get_access_token()
headers = {
'Authorization': f'Bearer {access_token}',
'Accept': 'application/json'
}
def get_folder_contents(drive_id, item_id=None, depth=0, max_depth=3):
"""Recursively get folder contents with depth limit"""
if depth > max_depth:
return ""
# Build URL for items
if item_id:
url = f'https://graph.microsoft.com/v1.0/drives/{drive_id}/items/{item_id}/children'
else:
url = f'https://graph.microsoft.com/v1.0/drives/{drive_id}/root/children'
items_response = requests.get(url, headers=headers)
if items_response.status_code != 200:
return f"<li class='error'>Error loading contents</li>"
items = items_response.json().get('value', [])
if not items:
return "<li class='empty'>Empty folder</li>"
html = ""
folders = [item for item in items if 'folder' in item]
files = [item for item in items if 'file' in item]
# Show folders first
for folder in folders:
folder_name = folder.get('name', 'N/A')
folder_id = folder.get('id')
child_count = folder.get('folder', {}).get('childCount', 0)
html += f"""
<li class='folder-item'>
<details>
<summary>
<span class='folder-icon'>📁</span>
<span class='folder-name'>{folder_name}</span>
<span class='item-count'>({child_count} items)</span>
</summary>
<ul class='nested'>
{get_folder_contents(drive_id, folder_id, depth + 1, max_depth)}
</ul>
</details>
</li>
"""
# Show files
for file in files:
file_name = file.get('name', 'N/A')
file_size = file.get('size', 0)
file_url = file.get('webUrl', '#')
file_id = file.get('id')
# Construct Graph API download URL
download_url = f"https://graph.microsoft.com/v1.0/drives/{drive_id}/items/{file_id}/content"
# Convert size to readable format
size_kb = file_size / 1024
if size_kb < 1024:
size_str = f"{size_kb:.1f} KB"
elif size_kb < 1024 * 1024:
size_str = f"{size_kb/1024:.1f} MB"
else:
size_str = f"{size_kb/(1024*1024):.1f} GB"
# Determine file icon based on extension
ext = file_name.split('.')[-1].lower() if '.' in file_name else ''
if ext in ['pdf']:
icon = '📄'
elif ext in ['doc', 'docx']:
icon = '📝'
elif ext in ['xls', 'xlsx']:
icon = '📊'
elif ext in ['ppt', 'pptx']:
icon = '📽️'
elif ext in ['jpg', 'jpeg', 'png', 'gif']:
icon = '🖼️'
elif ext in ['zip', 'rar', '7z']:
icon = '📦'
else:
icon = '📄'
# Escape single quotes in file name and URL for JavaScript
file_name_escaped = file_name.replace("'", "\\'")
download_url_escaped = download_url.replace("'", "\\'")
# Only show Load File button for supported file types
load_button = ""
if ext in ['docx', 'xlsx', 'pdf']:
load_button = f"<button class='load-btn' onclick=\"loadFile('{file_name_escaped}', '{download_url_escaped}');\">Load File</button>"
html += f"""
<li class='file-item'>
<span class='file-icon'>{icon}</span>
<a href='{file_url}' target='_blank' class='file-name'>{file_name}</a>
<span class='file-size'>{size_str}</span>
{load_button}
</li>
"""
return html
# CSS styles and scripts
css = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="VIKTOR_JS_SDK"></script>
<script>
function loadFile(fileName, downloadUrl) {
viktorSdk.sendParams({
selected_name: fileName,
selected_url: downloadUrl
}, true);
}
</script>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 20px;
margin: 0;
}
.container {
max-width: 1200px;
margin: 0 auto;
background: white;
border-radius: 12px;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
padding: 30px;
}
h2 {
color: #2d3748;
font-size: 28px;
margin-bottom: 10px;
font-weight: 600;
}
.site-url {
color: #718096;
font-size: 14px;
margin-bottom: 30px;
word-break: break-all;
}
.drive-section {
margin-bottom: 30px;
}
.drive-title {q
color: #4a5568;
font-size: 20px;
font-weight: 600;
margin-bottom: 15px;
padding: 12px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border-radius: 8px;
display: flex;
align-items: center;
gap: 10px;
}
ul {
list-style: none;
padding-left: 0;
}
.nested {
padding-left: 30px;
margin-top: 8px;
}
details {
margin: 4px 0;
}
summary {
cursor: pointer;
padding: 10px;
border-radius: 6px;
transition: background-color 0.2s;
display: flex;
align-items: center;
gap: 8px;
user-select: none;
}
summary:hover {
background-color: #f7fafc;
}
details[open] > summary {
background-color: #edf2f7;
margin-bottom: 8px;
}
.folder-item {
margin: 4px 0;
}
.folder-icon {
font-size: 18px;
}
.folder-name {
font-weight: 500;
color: #2d3748;
}
.item-count {
color: #a0aec0;
font-size: 12px;
}
.file-item {
padding: 10px;
border-radius: 6px;
transition: background-color 0.2s;
display: flex;
align-items: center;
gap: 10px;
margin: 4px 0;
}
.file-item:hover {
background-color: #f7fafc;
}
.file-icon {
font-size: 18px;
}
.file-name {
flex: 1;
color: #4299e1;
text-decoration: none;
font-weight: 500;
}
.file-name:hover {
text-decoration: underline;
}
.file-size {
color: #a0aec0;
font-size: 12px;
font-weight: 500;
margin-right: 10px;
}
.load-btn {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
padding: 6px 12px;
border-radius: 5px;
font-size: 12px;
font-weight: 600;
cursor: pointer;
transition: transform 0.2s, box-shadow 0.2s;
}
.load-btn:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}
.load-btn:active {
transform: translateY(0);
}
.empty {
color: #a0aec0;
font-style: italic;
padding: 10px;
}
.error {
color: #e53e3e;
padding: 10px;
}
.stats {
background: #f7fafc;
padding: 15px;
border-radius: 8px;
margin-top: 30px;
color: #4a5568;
font-weight: 500;
}
</style>
</head>
<body>
"""
html = css
html += "<div class='container'>"
html += "<h2>📂 SharePoint Site Contents</h2>"
html += f"<div class='site-url'>{params.url}</div>"
try:
# First, get the site ID from the URL
site_url = params.url.replace('https://', '')
parts = site_url.split('/')
hostname = parts[0]
site_path = '/' + '/'.join(parts[1:]) if len(parts) > 1 else ''
# Get site by URL
response = requests.get(
f'https://graph.microsoft.com/v1.0/sites/{hostname}:{site_path}',
headers=headers
)
if response.status_code != 200:
html += f"<div class='error'><h3>❌ Error getting site: {response.status_code}</h3>"
html += f"<pre>{response.text}</pre></div>"
html += "</div>"
return vkt.WebResult(html=html)
site = response.json()
site_id = site.get('id')
# Get document libraries (drives)
drives_response = requests.get(
f'https://graph.microsoft.com/v1.0/sites/{site_id}/drives',
headers=headers
)
if drives_response.status_code != 200:
html += f"<div class='error'>❌ Error getting drives: {drives_response.status_code}</div>"
html += "</div>"
return vkt.WebResult(html=html)
drives = drives_response.json().get('value', [])
if not drives:
html += "<p class='empty'>No document libraries found</p>"
html += "</div>"
return vkt.WebResult(html=html)
# List contents from all drives
for drive in drives:
drive_id = drive.get('id')
drive_name = drive.get('name', 'Unknown')
html += f"<div class='drive-section'>"
html += f"<div class='drive-title'>🗄️ {drive_name}</div>"
html += "<ul>"
html += get_folder_contents(drive_id)
html += "</ul>"
html += "</div>"
except Exception as e:
html += f"<div class='error'><h3>❌ Error</h3>"
html += f"<pre>{str(e)}</pre></div>"
html += "</div>"
html += "</body>"
html += "</html>"
# Replace the Viktor JS SDK path
html = html.replace("VIKTOR_JS_SDK", os.environ["VIKTOR_JS_SDK_PATH"] + "v1.js")
return vkt.WebResult(html=html)