-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathteams.rs
More file actions
3397 lines (3131 loc) · 111 KB
/
Copy pathteams.rs
File metadata and controls
3397 lines (3131 loc) · 111 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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::collections::{HashMap, HashSet};
use std::fs;
use std::io::Read;
use std::path::PathBuf;
use std::process::Command;
use std::thread;
use std::time::Duration as StdDuration;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use anyhow::{Context, Result, bail};
use base64::Engine as _;
use clap::{CommandFactory, Parser, Subcommand, ValueEnum};
use ed25519_dalek::SigningKey;
use hifitime::{Epoch, TimeScale};
use rand_core::OsRng;
use reqwest::blocking::Client;
use reqwest::header::CONTENT_TYPE;
use serde_json::{Value as JsonValue, json};
use serde::Deserialize;
use triblespace::core::metadata;
use triblespace::core::blob::Bytes;
use triblespace::core::repo::pile::Pile;
use triblespace::core::repo::{Repository, Workspace};
use triblespace::macros::id_hex;
use triblespace::prelude::blobencodings::LongString;
use triblespace::prelude::inlineencodings::{Handle, NsTAIInterval, ShortString, U256BE};
use triblespace::prelude::*;
/// Author entity used by the teams faculty when writing its own log entries.
/// Singleton — same id across every faculty run.
const TEAMS_LOG_AUTHOR_ID: Id = id_hex!("5E9B01A9D7C9BB6D765F8C96A83D2E60");
/// Author entity used for attachment backfill rows (there is no real author
/// for these; the attachments-only backfill is a faculty action, not a user
/// message). Singleton.
#[allow(dead_code)]
const TEAMS_BACKFILL_AUTHOR_ID: Id = id_hex!("64A9492F3B2368A0DAB5FAF3277132C2");
/// Fallback author id used when Teams delivers a message with no `from.user.id`.
/// Mapping every anonymous message to the same id keeps the graph small and
/// lets us eventually merge/correct them later if the upstream data improves.
#[allow(dead_code)]
const TEAMS_UNKNOWN_AUTHOR_ID: Id = id_hex!("04217F0E5F75F57B8A7CBFD824D5FF31");
use faculties::schemas::archive::{RawBytes, archive};
use faculties::schemas::teams::{
DEFAULT_BRANCH, DEFAULT_DELTA_URL, DEFAULT_LOG_BRANCH, FILES_BRANCH_NAME, file_schema, teams,
};
use file_schema::KIND_FILE;
use file_schema::file;
#[derive(Parser)]
#[command(name = "teams", about = "Ingest Microsoft Teams messages into TribleSpace")]
struct Cli {
/// Path to the pile file to write into.
#[arg(long, env = "PILE")]
pile: PathBuf,
/// Branch name to write into (created if missing).
#[arg(long, default_value = DEFAULT_BRANCH)]
branch: String,
/// Branch id to write into (hex). Overrides config/env branch id.
#[arg(long)]
branch_id: Option<String>,
/// Microsoft Graph delta endpoint.
#[arg(long, default_value = DEFAULT_DELTA_URL)]
delta_url: String,
/// OAuth bearer token (optional; otherwise use token command). Use @path for file input or @- for stdin.
#[arg(long)]
token: Option<String>,
/// Command that outputs a bearer token. Use @path for file input or @- for stdin.
#[arg(
long,
default_value =
"az account get-access-token --resource https://graph.microsoft.com --query accessToken -o tsv"
)]
token_command: String,
#[command(subcommand)]
command: Option<CommandMode>,
}
#[derive(Subcommand)]
enum CommandMode {
/// Sync from Graph and read messages from the local pile.
Read {
/// Teams chat id (external id).
chat_id: Option<String>,
/// Only show messages at or after this timestamp (RFC3339 or Graph format).
#[arg(long)]
since: Option<String>,
/// Maximum number of messages to return (0 = no limit).
#[arg(long, default_value_t = 20)]
limit: usize,
/// Show newest messages first.
#[arg(long)]
descending: bool,
},
/// Send a message into a Teams chat.
Send {
chat_id: String,
#[arg(help = "Message text. Use @path for file input or @- for stdin.")]
text: String,
},
/// Users directory commands.
Users {
#[command(subcommand)]
command: UsersCommand,
},
/// Presence commands.
Presence {
#[command(subcommand)]
command: PresenceCommand,
},
/// Chat commands.
Chat {
#[command(subcommand)]
command: ChatCommand,
},
/// Attachment commands.
Attachments {
#[command(subcommand)]
command: AttachmentsCommand,
},
/// Interactive device-code login to cache a delegated token.
Login {
/// Tenant id or domain (default: common).
#[arg(long, default_value = "common")]
tenant: String,
/// Azure app client id.
#[arg(long)]
client_id: String,
/// Azure app client secret (stored in the pile).
#[arg(long, help = "Azure app client secret (stored in the pile). Use @path for file input or @- for stdin.")]
client_secret: Option<String>,
/// Space-delimited scopes (defaults to chat + presence + user read + offline_access).
#[arg(long, help = "Space-delimited scopes. Use @path for file input or @- for stdin.")]
scopes: Option<String>,
},
}
#[derive(Subcommand)]
enum UsersCommand {
/// List directory users by display name prefix.
List {
/// Name/email prefix to search for.
prefix: Option<String>,
/// Maximum number of users to return (0 = no limit).
#[arg(long, default_value_t = 20)]
limit: usize,
},
}
#[derive(Clone, Debug, ValueEnum)]
enum PresenceAvailability {
#[value(name = "Available", alias = "available")]
Available,
#[value(name = "Busy", alias = "busy")]
Busy,
#[value(name = "Away", alias = "away")]
Away,
#[value(
name = "DoNotDisturb",
alias = "do-not-disturb",
alias = "donotdisturb",
alias = "dnd"
)]
DoNotDisturb,
}
impl PresenceAvailability {
fn as_graph(&self) -> &'static str {
match self {
PresenceAvailability::Available => "Available",
PresenceAvailability::Busy => "Busy",
PresenceAvailability::Away => "Away",
PresenceAvailability::DoNotDisturb => "DoNotDisturb",
}
}
}
#[derive(Clone, Debug, ValueEnum)]
enum PresenceActivity {
#[value(name = "Available", alias = "available")]
Available,
#[value(name = "InACall", alias = "in-a-call", alias = "inacall", alias = "call")]
InACall,
#[value(
name = "InAConferenceCall",
alias = "in-a-conference-call",
alias = "inaconferencecall",
alias = "conference"
)]
InAConferenceCall,
#[value(name = "Away", alias = "away")]
Away,
#[value(name = "Presenting", alias = "presenting")]
Presenting,
}
impl PresenceActivity {
fn as_graph(&self) -> &'static str {
match self {
PresenceActivity::Available => "Available",
PresenceActivity::InACall => "InACall",
PresenceActivity::InAConferenceCall => "InAConferenceCall",
PresenceActivity::Away => "Away",
PresenceActivity::Presenting => "Presenting",
}
}
}
#[derive(Subcommand)]
enum PresenceCommand {
/// Set the Teams presence for the logged-in user.
Set {
/// Availability (Available, Busy, Away, DoNotDisturb).
availability: PresenceAvailability,
/// Activity (Available, InACall, InAConferenceCall, Away, Presenting).
#[arg(long)]
activity: Option<PresenceActivity>,
/// Expiration in minutes (5-240).
#[arg(long, default_value_t = 60)]
duration_mins: u32,
/// Optional session id override (defaults to app client id).
#[arg(long)]
session_id: Option<String>,
},
/// Get presence for one or more users (by id).
Get {
/// One or more user ids to query.
user_ids: Vec<String>,
},
}
#[derive(Subcommand)]
enum ChatCommand {
/// Invite a user into an existing chat.
Invite {
chat_id: String,
user_id: String,
/// Add as owner.
#[arg(long)]
owner: bool,
},
/// Create a new chat with users (by id).
Create {
/// User ids to include (self is added automatically).
user_ids: Vec<String>,
/// Force a group chat even for 1:1.
#[arg(long)]
group: bool,
/// Optional group chat topic.
#[arg(long, help = "Optional group chat topic. Use @path for file input or @- for stdin.")]
topic: Option<String>,
},
}
#[derive(Subcommand)]
enum AttachmentsCommand {
/// List attachments stored in the pile.
List {
/// Filter by Teams chat id (external id).
#[arg(long)]
chat_id: Option<String>,
/// Filter by Teams message id (external id).
#[arg(long)]
message_id: Option<String>,
/// Maximum number of attachments to return (0 = no limit).
#[arg(long, default_value_t = 20)]
limit: usize,
/// Show newest attachments first.
#[arg(long)]
descending: bool,
},
/// Backfill attachments for existing messages.
Backfill {
/// Filter by Teams chat id (external id).
#[arg(long)]
chat_id: Option<String>,
/// Filter by Teams message id (external id).
#[arg(long)]
message_id: Option<String>,
/// Maximum number of messages to scan (0 = no limit).
#[arg(long, default_value_t = 0)]
limit: usize,
/// Scan newest messages first.
#[arg(long)]
descending: bool,
},
/// Export a stored attachment to a local file.
Export {
/// Attachment source id (as shown in attachments list).
source_id: String,
/// Filter by Teams chat id (external id).
#[arg(long)]
chat_id: Option<String>,
/// Filter by Teams message id (external id).
#[arg(long)]
message_id: Option<String>,
/// Output directory (created if missing).
out_dir: Option<PathBuf>,
/// Override filename (defaults to attachment name or source id).
#[arg(long)]
filename: Option<String>,
/// Overwrite if the file already exists.
#[arg(long)]
overwrite: bool,
},
}
#[derive(Clone, Debug)]
struct TeamsBridgeConfig {
pile_path: PathBuf,
branch: String,
branch_id: Id,
log_branch_id: Id,
delta_url: String,
token: Option<String>,
token_command: String,
}
fn main() -> Result<()> {
let mut cli = Cli::parse();
let Some(mode) = cli.command.take() else {
let mut command = Cli::command();
command.print_help()?;
println!();
return Ok(());
};
match mode {
CommandMode::Read {
chat_id,
since,
limit,
descending,
} => {
let config = build_config(&cli)?;
read_messages(
config,
ReadOptions {
chat_id,
since,
limit,
descending,
},
)
}
CommandMode::Send { chat_id, text } => {
let config = build_config(&cli)?;
let text = load_value_or_file(&text, "message text")?;
send_message(config, &chat_id, &text)
}
CommandMode::Users { command } => {
let config = build_config(&cli)?;
match command {
UsersCommand::List { prefix, limit } => list_users(config, prefix.as_deref(), limit),
}
}
CommandMode::Presence { command } => {
let config = build_config(&cli)?;
match command {
PresenceCommand::Set { availability, activity, duration_mins, session_id } => {
set_presence_status(config, availability, activity, duration_mins, session_id)
}
PresenceCommand::Get { user_ids } => get_presence(config, user_ids),
}
}
CommandMode::Chat { command } => {
let config = build_config(&cli)?;
match command {
ChatCommand::Invite { chat_id, user_id, owner } => invite_to_chat(config, &chat_id, &user_id, owner),
ChatCommand::Create { user_ids, group, topic } => {
let topic = topic
.as_deref()
.map(|value| load_value_or_file(value, "chat topic"))
.transpose()?;
create_chat(config, user_ids, group, topic)
}
}
}
CommandMode::Attachments { command } => {
let config = build_config(&cli)?;
match command {
AttachmentsCommand::List { chat_id, message_id, limit, descending } => {
list_attachments(config, AttachmentListOptions { chat_id, message_id, limit, descending })
}
AttachmentsCommand::Backfill { chat_id, message_id, limit, descending } => {
backfill_attachments(config, AttachmentBackfillOptions { chat_id, message_id, limit, descending })
}
AttachmentsCommand::Export { source_id, chat_id, message_id, out_dir, filename, overwrite } => {
let out_dir = out_dir.unwrap_or_else(|| PathBuf::from("./attachments"));
export_attachment(
config,
AttachmentExportOptions {
source_id,
chat_id,
message_id,
out_dir,
filename,
overwrite,
},
)
}
}
}
CommandMode::Login {
tenant,
client_id,
client_secret,
scopes,
} => {
let config = build_config(&cli)?;
let scopes = scopes
.as_deref()
.map(|value| load_value_or_file(value, "scopes"))
.transpose()?
.unwrap_or_else(default_scopes);
let client_secret = client_secret
.as_deref()
.map(|value| load_value_or_file_trimmed(value, "client secret"))
.transpose()?;
login_device_code(&config, &tenant, &client_id, client_secret.as_deref(), &scopes)
}
}
}
fn with_repo<T>(
pile_path: &PathBuf,
f: impl FnOnce(&mut Repository<Pile>) -> Result<T>,
) -> Result<T> {
let pile = open_pile(pile_path)?;
let repo = Repository::new(pile, SigningKey::generate(&mut OsRng), TribleSet::new())
.map_err(|err| anyhow::anyhow!("create repository: {err:?}"))?;
with_repo_close(repo, f)
}
fn build_config(cli: &Cli) -> Result<TeamsBridgeConfig> {
let pile_path = cli.pile.clone();
let branch = std::env::var("TRIBLESPACE_BRANCH").ok().unwrap_or_else(|| cli.branch.clone());
let log_branch = std::env::var("TRIBLESPACE_LOG_BRANCH")
.ok()
.unwrap_or_else(|| DEFAULT_LOG_BRANCH.to_string());
let branch_id = with_repo(&pile_path, |repo| {
if let Some(hex) = cli.branch_id.as_deref() {
return Id::from_hex(hex.trim())
.ok_or_else(|| anyhow::anyhow!("invalid branch id '{hex}'"));
}
repo.ensure_branch(&branch, None)
.map_err(|e| anyhow::anyhow!("ensure teams branch: {e:?}"))
})?;
let log_branch_id = with_repo(&pile_path, |repo| {
repo.ensure_branch(&log_branch, None)
.map_err(|e| anyhow::anyhow!("ensure logs branch: {e:?}"))
})?;
let delta_url = std::env::var("TEAMS_DELTA_URL")
.ok()
.unwrap_or_else(|| cli.delta_url.clone());
let token = cli
.token
.as_deref()
.map(|value| load_value_or_file_trimmed(value, "token"))
.transpose()?
.or_else(|| std::env::var("TEAMS_TOKEN").ok());
let token_command = std::env::var("TEAMS_TOKEN_COMMAND")
.ok()
.unwrap_or_else(|| cli.token_command.clone());
let token_command = load_value_or_file_trimmed(&token_command, "token command")?;
Ok(TeamsBridgeConfig {
pile_path,
branch,
branch_id,
log_branch_id,
delta_url,
token,
token_command,
})
}
fn default_scopes() -> String {
[
"offline_access",
"User.Read.All",
"Presence.ReadWrite",
"Presence.Read.All",
"Chat.ReadWrite",
"ChatMessage.Send",
"Chat.Create",
"ChatMember.ReadWrite",
]
.join(" ")
}
fn with_repo_close<T, F>(repo: Repository<Pile>, f: F) -> Result<T>
where
F: FnOnce(&mut Repository<Pile>) -> Result<T>,
{
let mut repo = repo;
let result = f(&mut repo);
let pile = repo.into_storage();
let close_res = pile.close().map_err(|e| anyhow::anyhow!("close pile: {e:?}"));
if let Err(err) = close_res {
if result.is_ok() {
return Err(err);
}
eprintln!("warning: failed to close pile cleanly: {err:#}");
}
result
}
fn log_event(config: &TeamsBridgeConfig, level: &str, message: &str) -> Result<()> {
let (repo, branch_id) = open_repo_for_branch_id(&config.pile_path, config.log_branch_id, "logs")?;
with_repo_close(repo, |repo| {
let mut ws = map_err_debug(repo.pull(branch_id), "pull workspace")?;
let catalog = map_err_debug(ws.checkout(..), "checkout workspace")?.into_facts();
let mut change = TribleSet::new();
let author_name = ws.put("teams".to_string());
let author_role = ws.put("faculty".to_string());
change += entity! { ExclusiveId::force_ref(&TEAMS_LOG_AUTHOR_ID) @
metadata::tag: archive::kind_author,
archive::author_name: author_name,
archive::author_role: author_role,
};
let log_id = ufoid();
let content = format!("[{}] {}", level.trim(), message.trim());
let content_handle = ws.put(content);
let created_at = epoch_interval(now_epoch());
change += entity! { &log_id @
metadata::tag: teams::kind_log,
archive::author: TEAMS_LOG_AUTHOR_ID,
metadata::created_at: created_at,
archive::content: content_handle,
};
let change = change.difference(&catalog);
if change.is_empty() {
return Ok(());
}
ws.commit(change, "teams log");
map_err_debug(repo.push(&mut ws), "push workspace")?;
Ok(())
})
}
fn pull_once_with_cache(
config: &TeamsBridgeConfig,
app_token_cache: &mut Option<AppTokenCache>,
) -> Result<()> {
let (token, app_config) = get_app_token(config, app_token_cache)?;
let (repo, branch_id) =
open_repo_for_branch_id(&config.pile_path, config.branch_id, &config.branch)?;
with_repo_close(repo, |repo| {
let mut ws = map_err_debug(repo.pull(branch_id), "pull workspace")?;
let catalog = map_err_debug(ws.checkout(..), "checkout workspace")?.into_facts();
let cursor_state = load_cursor_from_space(&mut ws, &catalog)?;
let start_url = match cursor_state.as_ref() {
Some(cursor) if cursor.url.contains("/me/") => {
resolve_delta_url(&config.delta_url, &app_config.user_id)?
}
Some(cursor) => cursor.url.clone(),
None => resolve_delta_url(&config.delta_url, &app_config.user_id)?,
};
let (messages, new_cursor) = fetch_delta_messages(&token, &start_url)?;
let index = CatalogIndex::build(&catalog);
let incoming = parse_messages(messages)?;
let (mut change, files_change) = build_ingest_change(&mut ws, &catalog, &index, incoming, &token, config)?;
if let Some(cursor_change) =
build_cursor_change(&mut ws, &catalog, cursor_state.as_ref(), new_cursor)?
{
change += cursor_change;
}
if !change.is_empty() {
ws.commit(change, "teams ingest");
map_err_debug(repo.push(&mut ws), "push workspace")?;
}
// Commit file entities to the files branch.
if !files_change.is_empty() {
let files_branch_id = repo.ensure_branch(FILES_BRANCH_NAME, None)
.map_err(|e| anyhow::anyhow!("ensure files branch: {e:?}"))?;
let mut files_ws = map_err_debug(repo.pull(files_branch_id), "pull files workspace")?;
files_ws.commit(files_change, "teams attachment files");
map_err_debug(repo.push(&mut files_ws), "push files workspace")?;
}
Ok(())
})
}
#[derive(Debug, Clone)]
struct AppTokenCache {
access_token: String,
expires_at_key: i128,
}
#[derive(Debug, Clone)]
struct AppConfig {
tenant: String,
client_id: String,
client_secret: String,
user_id: String,
}
#[derive(Debug, Clone, Default)]
struct TeamsConfigData {
tenant: Option<String>,
client_id: Option<String>,
client_secret: Option<String>,
user_id: Option<String>,
}
fn get_app_token(
config: &TeamsBridgeConfig,
app_token_cache: &mut Option<AppTokenCache>,
) -> Result<(String, AppConfig)> {
let app_config = load_app_config_from_pile(config)?;
let now_key = interval_key(epoch_interval(now_epoch()));
if let Some(cache) = app_token_cache {
if cache.expires_at_key > now_key + 30 * 1_000_000_000 {
return Ok((cache.access_token.clone(), app_config));
}
}
let token = request_client_credentials_token(
&app_config.tenant,
&app_config.client_id,
&app_config.client_secret,
)?;
let expires_at = epoch_interval(epoch_after_seconds(now_epoch(), token.expires_in));
let expires_at_key = interval_key(expires_at);
let access_token = token.access_token;
*app_token_cache = Some(AppTokenCache {
access_token: access_token.clone(),
expires_at_key,
});
Ok((access_token, app_config))
}
fn load_app_config_from_pile(config: &TeamsBridgeConfig) -> Result<AppConfig> {
let Some(config_data) = load_config_from_pile(config)? else {
bail!(
"missing Teams app config; run teams.rs login --client-id <app-id> --tenant <tenant-id> --client-secret <secret>"
);
};
let tenant = config_data.tenant.ok_or_else(|| {
anyhow::anyhow!("missing tenant in Teams config; re-run teams.rs login")
})?;
let client_id = config_data.client_id.ok_or_else(|| {
anyhow::anyhow!("missing client id in Teams config; re-run teams.rs login")
})?;
let client_secret = config_data.client_secret.ok_or_else(|| {
anyhow::anyhow!(
"missing client secret in Teams config; re-run teams.rs login with --client-secret"
)
})?;
let user_id = config_data.user_id.ok_or_else(|| {
anyhow::anyhow!("missing user id in Teams config; re-run teams.rs login")
})?;
Ok(AppConfig {
tenant,
client_id,
client_secret,
user_id,
})
}
fn resolve_delta_url(template: &str, user_id: &str) -> Result<String> {
if template.contains("{user_id}") {
return Ok(template.replace("{user_id}", user_id));
}
if template.contains("/me/") {
bail!("delta url uses /me; configure /users/{{user_id}}/chats/getAllMessages/delta");
}
Ok(template.to_owned())
}
fn get_delegated_token(config: &TeamsBridgeConfig) -> Result<String> {
if let Some(token) = config.token.as_ref() {
let token = token.trim();
if !token.is_empty() {
return Ok(token.to_owned());
}
}
if let Some(token) = load_cached_token_from_pile(config)? {
return Ok(token);
}
let cmd = config
.token_command
.split_whitespace()
.map(str::to_string)
.collect::<Vec<_>>();
if cmd.is_empty() {
bail!("token command is empty");
}
let mut command = Command::new(&cmd[0]);
if cmd.len() > 1 {
command.args(&cmd[1..]);
}
let output = command.output().context("run token command")?;
if !output.status.success() {
bail!(
"token command failed: exit={} stderr={}",
output.status,
String::from_utf8_lossy(&output.stderr)
);
}
let stdout = String::from_utf8(output.stdout).context("token command stdout not utf8")?;
let token = stdout.trim();
if token.is_empty() {
bail!("token command returned empty token");
}
Ok(token.to_owned())
}
#[derive(Debug, Clone, Deserialize)]
struct DeviceCodeResponse {
device_code: String,
user_code: String,
verification_uri: String,
verification_uri_complete: Option<String>,
expires_in: i64,
interval: Option<i64>,
message: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
struct TokenResponse {
access_token: String,
refresh_token: Option<String>,
expires_in: i64,
scope: Option<String>,
token_type: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
struct ErrorResponse {
error: String,
error_description: Option<String>,
}
#[derive(Debug, Clone)]
struct TokenState {
token_id: Id,
created_at_key: i128,
expires_at_key: i128,
access_token: Inline<Handle<LongString>>,
refresh_token: Option<Inline<Handle<LongString>>>,
scope: Option<Inline<Handle<LongString>>>,
tenant: Option<Inline<Handle<LongString>>>,
client_id: Option<Inline<Handle<LongString>>>,
}
#[derive(Debug, Clone)]
struct ConfigState {
config_id: Id,
created_at_key: i128,
tenant: Option<Inline<Handle<LongString>>>,
client_id: Option<Inline<Handle<LongString>>>,
client_secret: Option<Inline<Handle<LongString>>>,
user_id: Option<Inline<Handle<LongString>>>,
}
#[derive(Debug, Clone)]
struct TokenData {
access_token: String,
refresh_token: Option<String>,
expires_at: Inline<NsTAIInterval>,
token_type: Option<String>,
scope: Option<String>,
tenant: String,
client_id: String,
}
fn now_epoch_secs() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_else(|_| Duration::from_secs(0))
.as_secs() as i64
}
fn load_cached_token_from_pile(config: &TeamsBridgeConfig) -> Result<Option<String>> {
let (repo, branch_id) =
open_repo_for_branch_id(&config.pile_path, config.branch_id, &config.branch)?;
with_repo_close(repo, |repo| {
let mut ws = map_err_debug(repo.pull(branch_id), "pull workspace")?;
let catalog = map_err_debug(ws.checkout(..), "checkout workspace")?.into_facts();
let Some(state) = latest_token_state(&catalog) else {
return Ok(None);
};
let now_key = interval_key(epoch_interval(now_epoch()));
if state.expires_at_key > now_key + 30 * 1_000_000_000 {
let token = load_longstring(&mut ws, state.access_token)?;
return Ok(Some(token));
}
let refresh_handle = state.refresh_token.clone();
let tenant_handle = state.tenant.clone();
let client_handle = state.client_id.clone();
let Some(refresh_handle) = refresh_handle else {
return Ok(None);
};
let Some(tenant_handle) = tenant_handle else {
return Ok(None);
};
let Some(client_handle) = client_handle else {
return Ok(None);
};
let refresh = load_longstring(&mut ws, refresh_handle)?;
let tenant = load_longstring(&mut ws, tenant_handle)?;
let client_id = load_longstring(&mut ws, client_handle)?;
let scope = match state.scope.clone() {
Some(scope) => Some(load_longstring(&mut ws, scope)?),
None => None,
};
let refreshed = refresh_token(&tenant, &client_id, &refresh, scope.as_deref())?;
let expires_at = epoch_interval(epoch_after_seconds(now_epoch(), refreshed.expires_in));
let token = TokenData {
access_token: refreshed.access_token.clone(),
refresh_token: refreshed.refresh_token.or(Some(refresh)),
expires_at,
token_type: refreshed.token_type,
scope: refreshed.scope.or(scope),
tenant,
client_id,
};
store_token_in_repo(repo, branch_id, &token)?;
Ok(Some(token.access_token))
})
}
fn load_config_from_pile(config: &TeamsBridgeConfig) -> Result<Option<TeamsConfigData>> {
let (repo, branch_id) =
open_repo_for_branch_id(&config.pile_path, config.branch_id, &config.branch)?;
with_repo_close(repo, |repo| {
let mut ws = map_err_debug(repo.pull(branch_id), "pull workspace")?;
let catalog = map_err_debug(ws.checkout(..), "checkout workspace")?.into_facts();
let Some(state) = latest_config_state(&catalog) else {
return Ok(None);
};
let tenant = match state.tenant {
Some(handle) => Some(load_longstring(&mut ws, handle)?),
None => None,
};
let client_id = match state.client_id {
Some(handle) => Some(load_longstring(&mut ws, handle)?),
None => None,
};
let client_secret = match state.client_secret {
Some(handle) => Some(load_longstring(&mut ws, handle)?),
None => None,
};
let user_id = match state.user_id {
Some(handle) => Some(load_longstring(&mut ws, handle)?),
None => None,
};
Ok(Some(TeamsConfigData {
tenant,
client_id,
client_secret,
user_id,
}))
})
}
fn latest_token_state(catalog: &TribleSet) -> Option<TokenState> {
let mut best: Option<TokenState> = None;
for (token_id, access_token, expires_at, created_at) in find!(
(
token: Id,
access: Inline<Handle<LongString>>,
expires_at: Inline<NsTAIInterval>,
created_at: Inline<NsTAIInterval>
),
pattern!(catalog, [{
?token @
metadata::tag: teams::kind_token,
teams::access_token: ?access,
metadata::expires_at: ?expires_at,
metadata::created_at: ?created_at,
}])
) {
let created_key = interval_key(created_at);
let expires_key = interval_key(expires_at);
let replace = match &best {
None => true,
Some(current) => {
created_key > current.created_at_key
|| (created_key == current.created_at_key && token_id > current.token_id)
}
};
if replace {
best = Some(TokenState {
token_id,
created_at_key: created_key,
expires_at_key: expires_key,
access_token,
refresh_token: find_optional_handle(catalog, token_id, &teams::refresh_token),
scope: find_optional_handle(catalog, token_id, &teams::scope),
tenant: find_optional_handle(catalog, token_id, &teams::tenant),
client_id: find_optional_handle(catalog, token_id, &teams::client_id),
});
}
}
best
}
fn latest_config_state(catalog: &TribleSet) -> Option<ConfigState> {
let mut best: Option<ConfigState> = None;
for (config_id, created_at) in find!(
(config: Id, created_at: Inline<NsTAIInterval>),
pattern!(catalog, [{
?config @
metadata::tag: teams::kind_config,
metadata::created_at: ?created_at,
}])
) {
let created_key = interval_key(created_at);
let replace = match &best {
None => true,
Some(current) => {
created_key > current.created_at_key
|| (created_key == current.created_at_key && config_id > current.config_id)
}
};
if replace {
best = Some(ConfigState {
config_id,
created_at_key: created_key,
tenant: find_optional_handle(catalog, config_id, &teams::tenant),
client_id: find_optional_handle(catalog, config_id, &teams::client_id),
client_secret: find_optional_handle(catalog, config_id, &teams::client_secret),
user_id: find_optional_handle(catalog, config_id, &teams::user_id),
});
}
}
best
}
fn find_optional_handle(
catalog: &TribleSet,
entity: Id,
attribute: &Attribute<Handle<LongString>>,
) -> Option<Inline<Handle<LongString>>> {
find!(
(handle: Inline<Handle<LongString>>),
pattern!(catalog, [{ entity @ attribute: ?handle }])
)
.into_iter()
.next()
.map(|(handle,)| handle)
}
fn find_optional_value<S: InlineEncoding>(
catalog: &TribleSet,
entity: Id,
attribute: &Attribute<S>,
) -> Option<Inline<S>> {
find!(
(value: Inline<S>),
pattern!(catalog, [{ entity @ attribute: ?value }])
)
.into_iter()
.next()
.map(|(value,)| value)
}
fn load_chat_map(
ws: &mut Workspace<Pile>,
catalog: &TribleSet,
) -> Result<HashMap<Id, String>> {
let mut map = HashMap::new();
for (chat_id, handle) in find!(
(chat: Id, chat_id: Inline<Handle<LongString>>),
pattern!(catalog, [{
?chat @ teams::chat_id: ?chat_id,
}])
) {
let value = load_longstring(ws, handle)?;
map.insert(chat_id, value);
}
Ok(map)
}
fn load_message_external_map(
ws: &mut Workspace<Pile>,
catalog: &TribleSet,
) -> Result<HashMap<Id, String>> {