-
Notifications
You must be signed in to change notification settings - Fork 0
/
mjm_chromate.h
2109 lines (1816 loc) · 58.1 KB
/
mjm_chromate.h
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
#ifndef MJM_CHROMATE_H__
#define MJM_CHROMATE_H__
#include "mjm_globals.h"
#include "mjm_thread_util.h"
//unsigned int microseconds;
//usleep(microseconds);
#include <unistd.h>
#include <map>
#include <vector>
#include <algorithm>
#include <map>
#include <set>
#include <cmath>
#include <string>
#include <fstream>
#include <signal.h>
#include <stdlib.h>
#include <stdint.h>
#include <mjm_pawnoff.h>
// this is now shared...
#include <mjm_wscat_bot.h>
#include <mjm_strings.h>
#include <mjm_idiosyncratic_source_locator.h>
#include <../mjsonu/mjsonu.h>
#include <mjm_dir_watch.h>
// Tue Jan 4 07:47:10 EST 2022
// generated by /home/documents/cpp/scripts/cpputil -classhdr mjm_chromate
// QUICKCOMPILE g++ -Wall -std=gnu++11 -DTEST_MJM_CHROMATE -I. -I../../mjm/hlib -I../../mjm/num -I../../pkg/include -Wno-unused-variable -Wno-misleading-indentation -gdwarf-3 -O0 -x c++ mjm_chromate.h -lpthread -lreadline -o chromate.out
// g++ -Wall -std=gnu++11 -DTEST_MJM_CHROMATE -I. -I../../mjm/hlib -I../../mjm/num -I../../pkg/include -Wno-unused-variable -gdwarf-3 -O0 -x c++ mjm_chromate.h -lpthread -lreadline -o chromate.out
// g++ -Wall -std=gnu++11 -DTEST_MJM_CHROMATE -I. -I../../mjm/hlib -I../../mjm/num -gdwarf-3 -O0 -x c++ mjm_chromate.h -lpthread -lreadline
template <class Tr>
class mjm_chromate
{
typedef mjm_chromate Myt;
typedef typename Tr::IdxTy IdxTy;
typedef typename Tr::D D;
typedef typename Tr::StrTy StrTy;
typedef typename Tr::Ss Ss;
typedef typename Tr::IsTy IsTy;
typedef typename Tr::OsTy OsTy;
typedef typename Tr::Ofs Ofs;
//typedef typename Tr::FlagTy;
// typedef typename Tr::MyBlock MyBlock;
enum { BAD=~0};
typedef mjm_pawnoff<Tr> Hand;
typedef mjm_wscat_bot<Tr> WsCat;
typedef mjm_idiosyncratic_source_locator<Tr> IdioRl;
// needs to use pawn def
typedef mjm_blob<Tr> Blob;
typedef pthread_t ThreadId;
typedef mjm_mjsonu JsonTy;
typedef mjm_dir_watch<Tr> DirWatch;
typedef mjm_strings StrUtil;
class FetchInfo {
public:
FetchInfo(): rc(~0),eline(0),right_one(false) {}
FetchInfo & line(const int x) {eline=x; return *this; }
void reset_error() {error=""; }
IdxTy rc,eline;
StrTy error,doc;
StrTy root_node_id;
//fl.back_end_node_il[sz-1];
StrTy back_end_node;
bool right_one;
}; // FetchInfo
class CmdParam
{
public:
typedef std::vector<StrTy> var_type;
typedef std::map<StrTy, StrTy > Kv;
typedef std::map<StrTy, IdxTy > Kp;
void add(const StrTy & k, const StrTy & v){ m_kv[k]=quote(escape(v)); }
template <int n> void add(const StrTy & k, const char v[n]){ m_kv[k]=quote(escape(StrTy(v))); }
void add(const StrTy & k, const IdxTy & v){ Ss ss; ss<< v; m_kv[k]=ss.str(); }
void add(const StrTy & k, const bool & b){ m_kv[k]=b?"true":"false"; }
void add(const StrTy & k, const CmdParam & p){ m_kv[k]="{"+p.str()+"}"; }
StrTy str() const { return str(var_type()); }
StrTy str(const var_type & vv) const
{
Ss ss;
StrTy sep="";
MM_LOOP(ii,m_kv)
{
StrTy v=(*ii).second;
const char * p=v.c_str();
// these are quoted on input doh...
if (p[1]=='#')
{
const IdxTy loc=atoi(p+2);
bool num=false;
if (v.length()>3) num=p[v.length()-2]=='.';
MM_ERR(" ave var "<<MMPR3(v,loc,num))
if (loc<=vv.size())
{
if (num ) v=vv[loc-1];
else v="\""+vv[loc-1]+"\"";
}
else v=StrTy();
}
ss<<sep<<"\""<<(*ii).first<<"\""<<":"<<v; // (*ii).second;
sep=",";
} // ii
return ss.str();
} // str
StrTy quote(const StrTy & s) const { return StrTy ("\"")+s+StrTy("\""); }
StrTy escape(const StrTy & s) const
{
typedef std::vector<char> Cv;
Cv temp;
const char * p=s.c_str();
const IdxTy len=s.length();
for(IdxTy i=0; i<=len; ++i)
{
const char c=p[i];
if (c=='\\') temp.push_back('\\');
if (c=='\"') temp.push_back('\\');
temp.push_back(c);
} //i
//temp.push_back(0);
StrTy x=StrTy(&temp[0]);
return x;
} // escape
Kv m_kv;
Kp m_kp;
}; // CmdParam
class CommandInfo
{
public:
typedef CmdParam params_type;
typedef typename params_type::var_type Vt;
typedef typename params_type::var_type var_type;
//typedef std::vector<CmdParam> Params;
CommandInfo(const StrTy &n, const CmdParam p, const bool s,const bool aid)
: m_nm(n),m_params(p),add_session(s),add_id(aid) {}
CommandInfo() : m_nm(),m_params(),add_session(true),add_id(true) {}
StrTy str(const IdxTy id,const StrTy & session) const {Vt zv; return str(id,session,zv); }
StrTy str() const {Vt zv; return str(~0,StrTy(),zv); }
StrTy str(const IdxTy id,const StrTy & session, const Vt & vars) const
{
//const bool add_id=true;
//const bool add_session=true;
//MM_ERR(MMPR2(id,vars.size()))
Ss ss;
ss<<"{";
if (add_session) { ss<<"\"sessionId\":\""+session+"\","; }
//ss<<"\"method\":\"";
ss<<"\"method\":\""+m_nm+"\",";
ss<<"\"params\":{";
ss<<m_params.str(vars);
ss<<"}";
// move here?
//StrTy jscmd=spfx+"Emulation.setScriptExecutionDisabled\",\"params\":{\"value\":"+StrTy("false")+"},\"id\":";
//{Ragged r=CmdGet(fi,IdAdd(jscmd),flags); }
if (add_id) { ss<< ",\"id\":"; ss<<id ;}
ss<<"}";
return ss.str();
} // str
StrTy m_nm;
params_type m_params;
bool add_session;
bool add_id;
}; // CommandInfo
typedef typename CommandInfo::var_type var_type;
typedef std::map<StrTy, CommandInfo > ChromeCmdMap;
public:
typedef FetchInfo fetch_info;
mjm_chromate() {Init();}
~mjm_chromate() {Free();}
void done() {Free();}
IdxTy launch() { return Launch();}
IdxTy close() { return Close();}
IdxTy use_user(const StrTy & u, const IdxTy flags=0)
{ return UseUser(u,flags); }
// this needs to be called after launching although could fix...
IdxTy set_user_agent(const StrTy ua, const IdxTy flags )
{return SetUA( ua, flags ); }
fetch_info print_page(const StrTy & fn, const StrTy & url, const IdxTy flags)
{ return PrintPage(fn,url,flags); }
fetch_info fetch(const StrTy & url, const IdxTy flags)
{ return Fetch(url,flags);}
fetch_info save(const StrTy & fn, const StrTy & url, const IdxTy flags)
{
fetch_info fi=fetch(url,flags);
MM_ERR("saving "<<MMPR3(fn,fi.doc.length(),url))
std::ofstream save(fn);
save<<fi.doc;
return fi;
} // save
void bro_cmd(const StrTy & url, const IdxTy flags)
{ return BroCmd(url,flags);}
// if using this without the flag bit 0 set it will not wait and
// likely fail
fetch_info download(const StrTy & fn,const StrTy & url, const IdxTy flags)
{ return Download(fn,url,flags);}
// this will wait a long time if server fails but should wait for downlaod
fetch_info wget(const StrTy & fn,const StrTy & url,const IdxTy flags)
{ return Download(fn,url,1);}
// int in seconds lol but scales for perforenacne
void mysleep(const IdxTy n) const { const IdxTy tc=1000000>>2; usleep(n*tc); }
StrTy dump(const IdxTy flags=0) { return Dump(flags); }
private:
bool Bit(const IdxTy f, const IdxTy b) const { return ((f>>b)&1)!=0; }
// should loop over map now
StrTy Dump(const IdxTy flags=0) {Ss ss;
ss<<MMPR4(m_port,m_fifo, m_bro_name, m_options);
ss<<MMPR4(m_port_option,m_user_dir,m_user_profile, m_bro);
ss<<MMPR3( m_download_path,m_tmp_dir,m_download_dir);
ss<<MMPR4( m_ua, m_url, m_state, m_id_cnt);
ss<<MMPR3( m_current_ua,m_target,m_session);
ss<<MMPR(m_wscat.dump());
//WsCat m_wscat;
return ss.str(); }
typedef mjm_thread_util<Tr> ThreadTy;
typedef typename mjm_thread_util<Tr>::mutex_vector MutexVector;
enum { MAP_MU=0 , MU_SZ};
mutable MutexVector m_mutex_vector;
void EnterSerial(const IdxTy i)const { m_mutex_vector.enter_serial(i ); }
void ExitSerial(const IdxTy i)const { m_mutex_vector.exit_serial(i ); }
StrTy Exec(const StrTy & cmd)
{
Blob dest,err,data;
// no trailing crtlf
const IdxTy rc=m_hand.fileio(dest,err,data,cmd,1);
MM_ERR(MMPR4(rc,cmd,StrTy(dest),StrTy(err)))
return StrTy(dest);
}
//m_mutex_vector = MutexVector(MU_SZ);
class tpclass
{
public:
Myt * p;
StrTy cmd;
}; // tpclass
static void * LaunchBro (void * p)
{
tpclass * tpc=(tpclass*) p;
Myt * pp=tpc->p; // (Myt*) p;
pp->Exec(tpc->cmd);
pp->m_state=0;
MM_ERR(" bro thread exits doh ")
//Blob dest,err,data;
//pp->m_hand.fileio(dest,err,data,tpc->cmd);
//MM_ERR(MMPR2(StrTy(dest),StrTy(err)))
delete tpc;
return 0;
}
IdxTy Launch() {
if (m_state)
{
MM_ERR(" mjm_chromate already launched ")
return 0;
}
// this dettached..
StrTy aval=FindListener();
if (aval.length())
{
MM_ERR(" not launching browser as already a listener "<<MMPR2(aval,aval.length()))
return ~0;
}
StrTy cmd=StrTy("(")+m_bro +StrTy(" 2>&1 | tee /tmp/fifo >/dev/null) ");
MM_ERR(MMPR(cmd))
tpclass* ptpc = new tpclass();
tpclass & tpc=*ptpc;
tpc.p=this;
tpc.cmd=cmd;
auto tp=ThreadTy::launch(& Myt::LaunchBro,&tpc);
m_thread=tp;
// DANGER WILL ROBINSON
// everyone on this thread is ok waiting for laucnh, no problem here
m_state=1;
//Blob dest,err,data;
//m_hand.fileio(dest,err,data,cmd);
//MM_ERR(MMPR2(StrTy(dest),StrTy(err)))
StrTy pid;
IdxTy cnt=0;
while (pid=="")
{
++cnt;
if (cnt>10)
{
return ~0;
} //cnt
mysleep(1);
pid=FindListener();
} // while
//File x=open(m_fifo.c_str(),O_RDONLY);
std::ifstream ifs(m_fifo);
MM_ERR(MMPR3(pid,ifs.good(),ifs.eof()))
// DevTools listening on ws://127.0.0.1:9222/devtools/browser/4fa153b9-25fd-471f-aa37-73f2a5450262
//while(ifs.good())
while(true)
{
if ( ifs.eof()||!ifs.good())
{
MM_ERR(MMPR3(pid,ifs.good(),ifs.eof()))
if (FindListener().length())
{
mysleep(1);
ifs.clear();
}
else break;
} // eof
StrTy xx;
ifs>> xx;
//MM_ERR(MMPR(xx))
if (xx=="DevTools")
{
ifs>> xx;
if (xx=="listening")
{
ifs >>xx;
ifs >>xx;
m_url=xx;
MM_ERR(MMPR(m_url))
m_wscat.launch(m_url);
return 0;
} // listening
}
} // while
//close(x);
return 0;
} // Launch
template <class Ty> void Check(Ty* inf)
{
const bool eof=(*inf).eof();
const bool good=(*inf).good();
if ( eof ||!good)
{
MM_ERR(MMPR2(eof,good));
(*inf).clear();
mysleep(1);
}
} // Check
StrTy SRfck(const StrTy & cmd, const IdxTy flags)
{
StrTy x;
auto otf=m_wscat.out();
auto inf=m_wscat.in();
MM_ERR(MMPR(cmd))
(*otf)<<cmd<<"\n";
(*otf).flush();
StrTy xx;
Check(inf);
(*inf)>>xx;
MM_ERR("from wscat "<<MMPR(xx))
while (xx!=">")
{
MM_ERR("looking for >" << MMPR(xx))
x=x+xx;
Check(inf);
(*inf)>>x;
} // xx
return x;
} // SR
StrTy SR(const StrTy & cmd, const IdxTy flags)
{
const bool no_wait=Bit(flags,0);
++m_id_cnt;
StrTy x;
FILE* otf=m_wscat.outfdd();
if (otf==0)
{
MM_ERR(" otf is null probably shutdown and dynamic hazard lol ")
return StrTy();
}
MM_ERR(MMPR2(otf,cmd))
MM_ERR(MMPR(wscato(0,0,0)))
MM_ERR("")
StrTy carap=cmd+"\r";
fwrite(carap.c_str(),1,carap.length(),otf);
fflush(otf);
//(*otf)<<cmd<<"\n";
//(*otf).flush();
if (!no_wait) x=wscato(1,5,0);
MM_ERR(MMPR(cmd))
MM_ERR("")
MM_ERR(MMPR(x))
return x;
}
// this needs to return if disconnected..
StrTy wscato(const IdxTy n, const IdxTy ns,const IdxTy flags)
{
StrTy x;
FILE* inf=m_wscat.infdd();
MM_ERR(MMPR(inf))
if (inf==0)
{
// this happens during shutdown and leaks files...
MM_ERR(" null file pointer "<<MMPR(inf))
return StrTy();
}
// this could still die though if inf is killed
/// try catch? ...
long unsigned int fsz=1<<20;
long unsigned int fszlim=fsz-4;
char * line= new char[fsz];
IdxTy lines=0;
IdxTy sleeps=0;
IdxTy pos=0;
while (true)
{
int c=fgetc(inf);
if (c!=EOF)
{
line[pos]=c;
++pos;
//MM_ERR(MMPR4(c,char(c),pos,x.length()))
if (pos==fszlim)
{
line[pos]=0;
x+=StrTy(line);
pos=0;
} // pos
if (c=='\r') ++lines;
else if (c=='\n') ++lines;
} // EOF
else {
MM_ERR("EOF"<< MMPR3(x,lines,sleeps))
// this is the culprit maybe not the other one..
if (false) ReleaseDebug(1,0);
if (lines>=n)if ((ns==0)||(sleeps>0)) break;
if (sleeps>=ns) break;
if (AppearsAlive()) mysleep(1);
else MM_ERR(" wants to wait but no alive "<<MMPR2(__FUNCTION__,m_state))
++sleeps;
continue;
}
//sleep(1);
} // while
line[pos]=0;
x+=StrTy(line);
MM_ERR("returns "<< MMPR2(__FUNCTION__,x))
delete[] line;
return x;
} //wscato
////////////////////////////////////////
StrTy xxxwscato(const IdxTy n, const IdxTy flags)
{
StrTy x;
FILE* inf=m_wscat.infdd();
long unsigned int fsz=1<<20;
char * line= new char[fsz];
IdxTy lines=0;
while (true)
{
long unsigned int sz=fsz;
getline(&line,&sz,inf);
//x+=StrTy(line)+"\n";
x+=StrTy(line);
if (strlen(line)) ++lines;
MM_ERR(MMPR4(strlen(line),sz,x,x.length()))
int c=fgetc(inf);
ungetc(c,inf);
MM_ERR(MMPR2(c,char(c)))
if ( c==27){ fgetc(inf); continue; }
// it outputs a > SPACE doh
if ( c=='>'){
c=fgetc(inf); // get rid of the prompt
c=fgetc(inf);
if (c==EOF) { if (lines>=n) break; }
else if (c==' ' ){ if (lines>=n) break; }
else ungetc(c,inf); // see if eof...
}
if (c==EOF)
{
MM_ERR("EOF")
mysleep(1);
continue;
}
mysleep(1);
}
delete[] line;
return x;
} //wscato
////////////////////////////////////////
bool AppearsAlive() const { return Bit(m_state,0); }
typedef mjm_ragged_table Ragged;
Ragged CmdGet(fetch_info & fi, const StrTy & cmd, const IdxTy flags)
{
const bool no_sleep=Bit(flags,8);
/*
1|GLOBAL|7||8|GLOBAL|=|34
2|GLOBAL|10||11|id|=|12
3|GLOBAL|10||11|result|12|root|13|nodeId|=|11
4|GLOBAL|10||11|result|12|root|13|backendNodeId|=|72
5|GLOBAL|10||11|result|12|root|13|nodeType|=|9
6|GLOBAL|10||11|result|12|root|13|nodeName|=|#document
7|GLOBAL|10||11|result|12|root|13|localName|=|
8|GLOBAL|10||11|result|12|root|13|nodeValue|=|
9|GLOBAL|10||11|result|12|root|13|childNodeCount|=|2
*/
// this incs m_id_cnt
const IdxTy tid=m_id_cnt;
Ss ssfck; ssfck<<tid;
StrTy ti=SR(cmd,flags);
Ragged r;
bool right_one=false;
IdxTy tries=0;
StrTy lastid="";
while (AppearsAlive()&&!right_one)
{
++tries;
if (tries>5) break; // return r;
//if (!no_wait) x=wscato(1,5,0);
Ss js(ti);
auto pr=m_json.dirty_parse(js,0);
//Ragged & r=pr.res;
r=pr.res;
MM_ERR(__FUNCTION__<<MMPR2(tries,tid))
MM_ERR(MMPR(r.dump()))
MM_ERR("testing for fail ")
/*
the new bro is returning two things one with id doh wtf
x=> {"method":"Target.targetCreated","params":{"targetInfo":{"targetId":"CB32E61B549F55A2715871E63385BAD2","type":"page","title":"about:blank","url":"about:blank","attached":false,"canAccessOpener":false,"browserContextId":"24DEFD879590AE1FB76552E7AD56B6E6"}}}
{"id":2,"result":{}}
getting parsed wrong,
8|GLOBAL|6|GLOBAL|=|id
9|GLOBAL|7|GLOBAL|=|2
10|GLOBAL|8|GLOBAL|=|result
*/
const bool field_dump=false;
for(IdxTy i=0; i<r.size(); ++i)
{
if (field_dump) MM_ERR(" testing line "<<MMPR(i))
Ragged::Line & l=r[i];
const IdxTy len=l.size();
if (len<3) continue;
Ss ss;
if (field_dump) MM_ERR(" looking at line "<<MMPR(l[len-1]))
//MM_LOOP(ii,l) ss<<(*ii)<<"|";
//MM_ERR(MMPR3(__FUNCTION__,i,ss.str()))
//MM_ERR(MMPR3(i,l[len-3],l[len-1]))
if (l[len-3]=="id")
{
lastid=l[len-1]; if (l[len-1]==ssfck.str()) right_one=true; continue;
} // id
// new stuff
if (l[len-1]=="id")
{
MM_ERR(" have new format id "<<MMPR(l[len-1]))
IdxTy locid=i+1;
if (locid<r.size())
{
Ragged::Line & l2=r[locid];
if (l2.size()>0)
{
lastid=l2[l2.size()-1];
MM_ERR(" lookgin for ne cod e "<<MMPR3(l2[0],l2[l2.size()-1],ssfck.str()))
if (lastid==ssfck.str()) right_one=true; continue;
} // zero
} // locid
} // newstuff
if (l[len-3]=="errorText"){ fi.error+=l[len-1]; MM_ERR(" setting error "<<MMPR(l[len-3])) }
if (len<5) continue;
if (l[len-5]=="error"){ fi.error+=l[len-1]; MM_ERR(" setting error "<<MMPR(l[len-1])) }
}
if (right_one) break;
if (!AppearsAlive()) break;
if (no_sleep) break;
mysleep(1);
ti=wscato(1,5,0);
} // While
fi.doc=ti;
fi.right_one=right_one;
MM_ERR(":exiting"<< MMPR4(__FUNCTION__,right_one,tid,lastid)<<MMPR(tries))
return r;
} // CmdGet
StrTy IdAdd(const StrTy & cmd, const IdxTy flags=0)
{
StrTy cmds2="}";
Ss ss;
ss<<cmd;
ss<<m_id_cnt;
ss<<cmds2;
MM_ERR(MMPR(ss.str()))
return ss.str();
} // IdAdd
// only used by BroCmd for user intercace could delete..
StrTy FinishBroCmd(const StrTy & u, const IdxTy flags)
{
StrTy cmd=u;
const bool add_session=Bit(flags,0);
const bool add_id=Bit(flags,1);
if (add_session)
{
StrTy spfx="{\"sessionId\":\""+m_session+"\",\"method\":\"";
cmd=spfx+cmd;
}
if (add_id)
{
Ss ss;
ss<< ",\"id\":";
cmd+=IdAdd(ss.str());
}
return cmd;
} /// FinishBroCmd
// only used for raw command input
// TODO provide interface for serialized and sessioned cmd etc
void BroCmd(const StrTy & u, const IdxTy flags)
{
StrTy cmd=FinishBroCmd(u,flags);
MM_ERR(MMPR(cmd))
fetch_info fi;
Ragged r=CmdGet(fi,cmd,flags);
} // BroCmd
IdxTy StartBrowser( const IdxTy flags)
{
IdxTy rc=0;
fetch_info fi;
// new chrome apparently needs to create a target, will be ignored by old I hope lol
Ragged r;
if (m_target=="") {
{
// hide any errors for old bro
fetch_info fi;
if ( !m_chrome_with_head) // ExecBroCmd(fi,"evaluate",
r=ExecBroCmd(fi,"create_target");
//auto tm=m_json.index(r,flags);
//StrTy tid=m_json.kvm(tm,"type","page","targetId");
//StrTy any_kv(const Ragged & r, const StrTy & k, const IdxTy n, const IdxTy flags)
StrTy tid=m_json.any_kv(r,"targetId",0,0);
MM_ERR(" create traget returnts "<<MMPR(tid))
m_target=tid;
} // new stuff
// this had been set to false
if (!false) if (m_target=="")
{
if (!false) { r=ExecBroCmd(fi,"discover_targets"); }
auto tm=m_json.index(r,flags);
StrTy tid=m_json.kvm(tm,"type","page","targetId");
m_target=tid;
MM_ERR(" target id="<<MMPR(tid))
}
} // m_target
// https://stackoverflow.com/questions/45374377/not-able-to-maximize-chrome-window-in-headless-mode
if (m_session=="")
{
Ragged r=ExecBroCmd(fi,"attach",m_target);
StrTy sess=m_json.any_kv(r,"sessionId",0,flags);
m_session=sess;
MM_ERR(MMPR(sess))
StrTy ua= m_ua; // "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36";
SetUA(ua,0);
// this fails..
if (false) if ( m_chrome_with_head) ExecBroCmd(fi,"evaluate",
//StrTy("driver.manage().window().minimize();")
//StrTy("webdriver.manage().window().minimize();")
//StrTy("window.minimize();")
StrTy("window.minimize;")
);
if (!false) if ( m_chrome_with_head) ExecBroCmd(fi,"evaluate",
StrTy("window.resizeTo(100,100);")
);
// wtf? nothing - needs a session doh... ?
//if ( m_chrome_with_head) { EvalRt("driver.driver.manage().window().minimize();", 0 ); }
/*
StrTy plat="__proto__";
StrTy nocmd=spfx+"Emulation.setNavigatorOverrides\",\"params\":{\"platform\":\""+ plat + "\"},\"id\":";
StrTy expr="delete window.navigator.webdriver";
StrTy nocmd2=spfx+"Runtime.evaluate\",\"params\":{\"expression\":\""+ expr + "\"},\"id\":";
*/
if (false) ExecBroCmd(fi,"navigator_override");
if (true) ExecBroCmd(fi,"delete_window");
} // m_session
return rc;
} // StartBrowser
StrTy SPFX() const {
return "{\"sessionId\":\""+m_session+"\",\"method\":\"";
}
IdxTy SetUA(const StrTy ua, const IdxTy flags )
{
fetch_info fi;
Ragged r=ExecBroCmd(fi,"ua",ua);
m_current_ua=ua;
return 0;
} // SetUA
// eh TODO FIXME really good case for try/catch lol.
fetch_info PrintPage(const StrTy & fn, const StrTy & url, const IdxTy flags)
{
fetch_info fi;
MM_ERR(MMPR3(__FUNCTION__,fn,url))
try {
IdxTy rc=GoToPage(fi,url,flags);
if ((rc!=0)||fi.error.length()) throw fi.line(__LINE__);
//{ MM_ERR(" aborting pageprint due to due to problm.. "<<MMPR3(fn,url, fi.error)) fi.doc=""; return fi; }
// just the core let the thing finish it
//MM_ERR(" long sleep defeat ")
//sleep(10);
//StrTy u="Page.printToPDF\"";
//StrTy cmd=FinishBroCmd(u,3);
//Ragged r=CmdGet(fi,cmd,flags);
Ragged r=ExecBroCmd(fi,"print_pdf",url);
if (fi.error.length()) throw fi.line(__LINE__);
//{ MM_ERR(" aborting pageprint due to due to problm.. "<<MMPR3(fn,url, fi.error)) fi.doc=""; return fi; }
// parse the return leave in the junk
ExtractDoc(fi,"data");
if (fi.error.length()) throw fi.line(__LINE__);
// { MM_ERR(" aborting pageprint due to due to problm.. "<<MMPR3(fn,url, fi.error)) fi.doc=""; return fi; }
typedef mjm_read_buffer<Tr> RdBuff;
RdBuff rd;
mjm_strings::base64_decode(rd,fi.doc);
std::ofstream fck(fn);
rd.write(fck,0);
} catch (fetch_info & fi)
{
MM_ERR(" abort pageprint due to "<<MMPR4(fi.eline, fn,url, fi.error))
fi.doc="";
}
return fi;
} // PrintPage
IdxTy ExtractDoc(fetch_info & fi,const StrTy & field, const IdxTy flags=0)
{
IdxTy rc=0;
const bool put_error_in_doc=!Bit(flags,0);
const bool print_error=true;
Ss js(fi.doc);
auto pr=m_json.dirty_parse(js,0);
Ragged & r=pr.res;
MM_ERR(__FUNCTION__<<MMPR(field))
MM_ERR(MMPR(r.dump()))
bool found=false;
for(IdxTy i=0; i<r.size(); ++i)
{
const Ragged::Line & l = r[i];
const IdxTy len=l.size();
if (len<3) continue;
// the fcking euqals is in the furkc asdf asdf
//Ss ss;
//MM_LOOP(ii,l) ss<<(*ii)<<"|" ;
//MM_ERR(MMPR4(__FUNCTION__,ss.str(),i,l[len-3]))
//if (l[len-3]=="outerHTML") { fi.doc=l[len-1]; found=true; break ; }
if (l[len-3]==field) {
fi.doc=l[len-1];
found=true; break ; }
}// i
if (!found ) { fi.error+="not found"; if (put_error_in_doc) fi.doc=r.dump(3); rc=1; }
if (!found) if (print_error)
{
MM_ERR(MMPR(r.dump(3)))
}
return rc;
} // ExtractDoc
IdxTy GoToPage(fetch_info & fi,const StrTy & url, const IdxTy flags)
{
const bool skip_dom=Bit(flags,8);
IdxTy rc=0;
IdxTy sb=StartBrowser(flags);
// move here?
ExecBroCmd(fi, "enable_scripts");
if (fi.error!="" ) return 1;
const bool inject_mouse=true;
if ( inject_mouse)
{
if (!false) { ExecBroCmd(fi,"enable_focus"); }
// https://github.com/chromedp/chromedp/issues/211
if (!false) { ExecBroCmd(fi, "enable_network" ,flags); }
if (!false) { ExecBroCmd(fi, "missing_headers" ,flags); }
// BeginFrameControl
if (!false)
{
if (! m_chrome_with_head)
{
// TODO may not exist?
if (false) ExecBroCmd(fi, "enable_frame_control" ,flags);
// this is only supported in headless mode... doh
// seems to prevent rendering?
if (false) ExecBroCmd(fi, "begin_frame" ,flags);
}
}
ExecBroCmd(fi, "enable_animation" ,flags);
ExecBroCmd(fi, "discover_targets" ,flags);
}
// navigate likely just causing a bad request
if (skip_dom) return 0;
ExecBroCmd(fi, "navigate",url);
if (inject_mouse)
{
MM_ERR(" sleeping for input ")
sleep(5);
ExecBroCmd(fi,"mouse_moved","100","120");
sleep(5);
ExecBroCmd(fi,"get_targets",flags); // needs to be a const not flags
ExecBroCmd(fi,"get_frametree",flags); // needs to be a const not flags
if ( m_chrome_with_head)
{
// this appears to help render but then misses events lol
ExecBroCmd(fi,"disable_debugger",flags); // needs to be a const not flags
sleep(2);
ExecBroCmd(fi,"enable_debugger",flags); // needs to be a const not flags
//}
}
if (fi.error!="" ) return 1;
} // inject_mouse
if (skip_dom) return 0;
// TODO danger will robinson?
// this was called twice...
ExecBroCmd(fi,"get_document");
Ragged r=ExecBroCmd(fi,"get_document");
// try it twice wth
//r=CmdGet(fi,IdAdd(gdcmd),flags);
if (fi.error!="" ) return 1;
//r=CmdGet(fi,IdAdd(gdcmd),flags);
// need to get root node...
/*
./mjm_chromate.h372 r.dump()=0|GLOBAL|1||2|GLOBAL|=|2
1|GLOBAL|7||8|GLOBAL|=|34
2|GLOBAL|10||11|id|=|12
3|GLOBAL|10||11|result|12|root|13|nodeId|=|11
4|GLOBAL|10||11|result|12|root|13|backendNodeId|=|72
5|GLOBAL|10||11|result|12|root|13|nodeType|=|9
6|GLOBAL|10||11|result|12|root|13|nodeName|=|#document
7|GLOBAL|10||11|result|12|root|13|localName|=|
8|GLOBAL|10||11|result|12|root|13|nodeValue|=|
9|GLOBAL|10||11|result|12|root|13|childNodeCount|=|2
3|GLOBAL|12||13|result|14|root|15|nodeId|=|1
4|GLOBAL|12||13|result|14|root|15|backendNodeId|=|2
5|GLOBAL|12||13|result|14|root|15|nodeType|=|9
6|GLOBAL|12||13|result|14|root|15|nodeName|=|#document
7|GLOBAL|12||13|result|14|root|15|localName|=|
8|GLOBAL|12||13|result|14|root|15|nodeValue|=|
9|GLOBAL|12||13|result|14|root|15|childNodeCount|=|2
10|GLOBAL|12||13|result|14|root|15|children|16||17|nodeId|=|2
11|GLOBAL|12||13|result|14|root|15|children|16||17|parentId|=|1
12|GLOBAL|12||13|result|14|root|15|children|16||17|backendNodeId|=|81
*/
for(IdxTy i=0; i<r.size(); ++i)
{
const Ragged::Line & l=r[i];
const IdxTy sz=l.size();
if ( sz<5) continue;
if ( l[sz-5]!="root") continue;
if ( l[sz-3]=="backendNodeId")
{
fi.back_end_node=l[sz-1];
continue;
}
if ( l[sz-3]!="nodeId") continue;
fi.root_node_id=l[sz-1];
} /// i t
return rc;
} // GoToPage
IdxTy Close()
{
if (m_state==0)
{
MM_ERR(" alrady closed "<<MMPR(m_state))
return 0;
}
char c=3;
char d=4;
char cc[4];
cc[0]=c;
cc[1]=c;
cc[2]=d;
cc[3]=0;
StrTy ctrlc=cc;
fetch_info fi;
StrTy ccmd="{\"method\":\"Browser.close\",\"id\":";
Ragged r=CmdGet(fi,IdAdd(ccmd),0);
MM_ERR(" issued close to browser, now cleaning temps ")
mysleep(1);
// this is hanging...
StrTy xxx=SR(ctrlc,1);
MM_ERR(MMPR(xxx))
// this may be causing io problems on bro thread
//m_hand.clean();
return 0;
}
////////////////////////////////////////////////////////////////////////
StrTy LocalFile(IdioRl & irl)
{
// this needs to remove the file://
return irl.fs_path(); // StrTy(irl);
}
StrTy CompleteDest(const StrTy & fn, const bool fix_output_location )
{
//m_tmp_dir="/tmp"; m_download_path="./chromate_downloads"; m_download_dir=m_tmp_dir+"/"+m_download_path;
StrTy base,file;
base=Exec("dirname \""+fn+"\"");
file=Exec("basename \""+fn+"\"");
MM_ERR(MMPR3(fn,base,file))
return fn;
}
fetch_info Download(const StrTy & fn, const StrTy & url, const IdxTy flags)
{
const bool fix_output_location=Bit(flags,0);
const bool parse_source_info=!Bit(flags,1);
fetch_info fi;
DirWatch dw;
IdioRl irl=url;
irl.parse();
MM_ERR(MMPR3(irl.dump(),irl.http(),irl.local()))