-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
263 lines (237 loc) · 7.55 KB
/
main.go
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
package main
import (
"context"
"fmt"
"log"
"net/url"
"os"
"strconv"
"strings"
"time"
force "github.com/ForceCLI/force/lib"
"github.com/chromedp/cdproto/network"
"github.com/chromedp/chromedp"
)
const packageNamespace = "omnistudio__"
func hasScope(session *force.Force, scope string) bool {
for _, s := range strings.Split(session.Credentials.Scope, " ") {
if strings.ToLower(s) == strings.ToLower(scope) {
return true
}
}
return false
}
func compileOSAndFlexCards() error {
session, err := force.ActiveForce()
if err != nil {
return fmt.Errorf("Could not get session: %w", err)
}
if !hasScope(session, "web") {
return fmt.Errorf("Need web scope. Have scopes: %s. Check Connected App settings.", session.Credentials.Scope)
}
if !hasScope(session, "visualforce") {
return fmt.Errorf("Need visualforce scope. Have scopes: %s. Check Connected App settings.", session.Credentials.Scope)
}
instanceUrl := session.Credentials.InstanceUrl
accessToken := session.Credentials.AccessToken
queryOmniscript := `SELECT Id, UniqueName FROM OmniProcess WHERE IsActive = true AND IsIntegrationProcedure = false`
result, err := session.Query(queryOmniscript)
if err != nil {
return fmt.Errorf("Query for OmniScripts failed: %w", err)
}
var omniScriptIds []string
for _, record := range result.Records {
omniScriptIds = append(omniScriptIds, record["Id"].(string))
}
queryFlexCard := `SELECT Id, UniqueName FROM OmniUiCard WHERE IsActive = true`
result, err = session.Query(queryFlexCard)
if err != nil {
return fmt.Errorf("Query for FlexCards failed: %w", err)
}
var flexCardIds []string
for _, record := range result.Records {
flexCardIds = append(flexCardIds, record["Id"].(string))
}
opts := append(chromedp.DefaultExecAllocatorOptions[:],
chromedp.NoSandbox,
chromedp.DisableGPU,
)
if headless := os.Getenv("HEADLESS"); headless != "" {
h, _ := strconv.ParseBool(headless)
opts = append(opts, chromedp.Flag("headless", h))
}
logger := func(string, ...interface{}) {
}
if debug := os.Getenv("DEBUG"); debug != "" {
d, _ := strconv.ParseBool(debug)
if d {
logger = log.Printf
opts = append(opts, chromedp.IgnoreCertErrors)
}
}
opts = append(opts, chromedp.IgnoreCertErrors)
allocCtx, _ := chromedp.NewExecAllocator(context.Background(), opts...)
ctx, _ := chromedp.NewContext(
allocCtx,
chromedp.WithDebugf(logger),
)
// Create a timer that waits for the network to be idle for idleDuration
idleDuration := 2 * time.Second
timer := time.NewTimer(idleDuration)
// Set up listeners
chromedp.ListenTarget(ctx, func(ev interface{}) {
// fmt.Printf("Received event: %T\n", ev)
switch ev.(type) {
case *network.EventRequestWillBeSent:
// Reset the timer as there's ongoing network activity
if !timer.Stop() {
select {
case <-timer.C:
default:
}
}
timer.Reset(idleDuration)
}
})
ch := make(chan struct{})
waitNetworkIdle := func() chromedp.Action {
return chromedp.ActionFunc(func(ctx context.Context) error {
// Wait for the timer to expire indicating network has been idle for idleDuration
go func() {
<-timer.C
close(ch)
}()
// Block until the network has been idle for idleDuration
<-ch
return nil
})
}
waitForUrl := func(expected string) chromedp.Action {
return chromedp.ActionFunc(func(ctx context.Context) error {
var currentURL string
for {
// Get current URL
if err := chromedp.Location(¤tURL).Do(ctx); err != nil {
return err
}
// Check if it matches the expected URL
u, err := url.Parse(currentURL)
if err != nil {
return fmt.Errorf("Could not parse URL, %s: %w", currentURL, err)
}
if strings.Contains(u.Path, expected) {
return nil
}
// If not, sleep for a while and then check again
log.Println("current URL", currentURL, "does not match expected", expected)
time.Sleep(100 * time.Millisecond)
}
})
}
// Timeout the entire browser session after 10 minutes
timeoutCtx, cancelBrowser := context.WithTimeout(ctx, 10*time.Minute)
defer cancelBrowser()
if err := chromedp.Run(timeoutCtx,
chromedp.Navigate(instanceUrl+"/secur/frontdoor.jsp?sid="+accessToken),
waitNetworkIdle(),
); err != nil {
return fmt.Errorf("Failed navigating to login page: %w", err)
}
log.Printf("Activating OmmiScripts %+v\n", omniScriptIds)
for _, omniScriptId := range omniScriptIds {
omniScriptDisignerpageLink := instanceUrl + "/apex/" + packageNamespace + "OmniLwcCompile?id=" + omniScriptId + "&activate=true"
log.Println("Loading", omniScriptDisignerpageLink)
var currentStatus string
timeoutCtx, cancelParse := context.WithTimeout(ctx, 5*time.Minute)
defer cancelParse()
loadTimeCtx, cancelLoad := context.WithTimeout(timeoutCtx, 30*time.Second)
defer cancelLoad()
SCRIPT:
for {
if err := chromedp.Run(loadTimeCtx,
chromedp.Navigate(omniScriptDisignerpageLink),
waitForUrl("OmniLwcCompile"),
); err != nil {
return fmt.Errorf("Failed loading OmniScript compilation page: %w", err)
}
STATUS:
for {
if err := chromedp.Run(timeoutCtx,
chromedp.WaitVisible("#compiler-message"),
chromedp.Text("#compiler-message", ¤tStatus),
); err != nil {
return fmt.Errorf("Failed checking OmniScript compilation status: %w", err)
}
switch {
case currentStatus == "DONE":
log.Println("LWC Activated successfully")
break SCRIPT
case strings.HasPrefix(currentStatus, "ERROR: No MODULE named markup"):
log.Println("Missing Custom LWC - " + currentStatus)
case strings.HasPrefix(currentStatus, "ERROR"):
log.Println("Error Activating LWC - " + currentStatus)
break STATUS
default:
log.Println("Status: " + currentStatus)
}
time.Sleep(2 * time.Second)
}
}
cancelLoad()
cancelParse()
}
if len(flexCardIds) > 0 {
log.Printf("Activating FlexCards %+v\n", flexCardIds)
flexCardCompilePage := instanceUrl + "/apex/" + packageNamespace + "FlexCardCompilePage?id=" + strings.Join(flexCardIds, ",")
log.Println("Loading", flexCardCompilePage)
var currentStatus, jsonError, auraError string
timeoutCtx, cancelParse := context.WithTimeout(ctx, 5*time.Minute)
defer cancelParse()
loadTimeCtx, cancelLoad := context.WithTimeout(timeoutCtx, 30*time.Second)
defer cancelLoad()
CARDS:
for {
if err := chromedp.Run(loadTimeCtx,
chromedp.Navigate(flexCardCompilePage),
waitForUrl("FlexCardCompilePage"),
); err != nil {
return fmt.Errorf("Failed loading Flex Card compilation page: %w", err)
}
CARD_STATUS:
for {
if err := chromedp.Run(timeoutCtx,
chromedp.WaitVisible("#compileMessage-0"),
chromedp.Text("#compileMessage-0", ¤tStatus),
chromedp.WaitVisible("#resultJSON-0"),
chromedp.Text("#resultJSON-0", &jsonError),
chromedp.WaitVisible("body > #auraErrorMessage"),
chromedp.Text("body > #auraErrorMessage", &auraError),
); err != nil {
return fmt.Errorf("Failed checking Flex Card compilation status: %w", err)
}
switch {
case auraError != "":
log.Println("Error on page: " + auraError + "; Reloading")
break CARD_STATUS
case currentStatus == "DONE SUCCESSFULLY":
log.Println("LWC Activated successfully")
break CARDS
case currentStatus == "DONE WITH ERRORS":
log.Println("LWC FlexCards Compilation Error Result:" + jsonError)
default:
log.Println("Status: " + currentStatus)
}
time.Sleep(2 * time.Second)
}
}
cancelLoad()
cancelParse()
}
return nil
}
func main() {
err := compileOSAndFlexCards()
if err != nil {
log.Fatalf("Failed to reactivate omnistudio components: %v", err)
}
}