-
Notifications
You must be signed in to change notification settings - Fork 14
/
admediator.lua
569 lines (421 loc) · 16 KB
/
admediator.lua
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
------------------------------------------------------------
------------------------------------------------------------
-- Ad Mediator for Corona
--
-- Ad network mediation module for Ansca Corona
-- by Deniz Aydinoglu
--
-- he2apps.com
--
-- GitHub repository and documentation:
-- https://github.com/deniza/Ad-Mediator-for-Corona
------------------------------------------------------------
------------------------------------------------------------
local json = require("json")
AdMediator = {
clientIPAddress = "",
PLATFORM_IOS = 0,
PLATFORM_ANDROID = 1,
}
local networks = {}
local weightTable = {}
local networksByPriority = {}
local adRequestDelay = nil
local currentNetworkIdx = nil
local currentImageUrl = nil
local currentAdUrl = nil
local currentBanner = nil
local isHidden = true
local enableWebView = false
local webPopupVisible = false
local currentWebPopupContent
local adDisplayGroup = display.newGroup()
local adPosX = 0
local adPosY = 0
local animationEnabled = false
local animationTargetX
local animationTargetY
local animationDuration
local timerHandle = nil
local paused = false
local bannerWidth = 320
local bannerHeight = 50
local userAgentIOS = "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_2 like Mac OS X; en) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8F190 Safari/6533.18.5"
local userAgentAndroid = "Mozilla/5.0 (Linux; U; Android 2.2; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"
local userAgentString
local PLATFORM_IOS, PLATFORM_ANDROID = AdMediator.PLATFORM_IOS, AdMediator.PLATFORM_ANDROID
local platform
local runningOnIPAD
local dontScaleOnIPAD = false
local function findClientIPAddress()
local function ipListener(event)
if not event.isError and event.response ~= "" then
AdMediator.clientIPAddress = event.response
end
end
-- clientIPAddress is ONLY required for herewead network!
-- if you are not using herewead, you dont need to specify your own ip provider script.
-- whatismyip.org is not working anymore!
-- you should use your own ip provider. ie: http://yourserver.com/getip.php
-- network.request("http://whatismyip.org","GET",ipListener)
end
local function fetchNextNetworkBasedOnPriority()
if isHidden then
return
end
for _,network in pairs(networksByPriority) do
if not network.failedToLoad then
currentNetworkIdx = network.idx
network:requestAd()
--print("requesting ad:",network.name)
break
end
end
end
local function fetchRandomNetwork()
for i=1,#networks do
networks[i].failedToLoad = false
end
local random = math.floor(math.random()*100) + 1
for i=1,#weightTable do
if random >= weightTable[i].min and random <= weightTable[i].max then
currentNetworkIdx = i
break
end
end
networks[currentNetworkIdx]:requestAd()
--print("requesting ad:",networks[currentNetworkIdx].name)
end
function AdMediator.viewportMetaTagForPlatform()
-- Default for iPhone/iTouch
local meta = "<meta name=\"viewport\" content=\"width=320; user-scalable=0;\"/>"
local scale = 1/display.contentScaleY
if platform == PLATFORM_ANDROID then
meta = "<meta name=\"viewport\" content=\"width=320; initial-scale=1; minimum-scale=1; maximum-scale=2; user-scalable=0;\"/>"
elseif runningOnIPAD then
if scale > 4 then
---fix scaling issues for 'the new ipad'
scale = scale * 0.5
end
local width = 320
if dontScaleOnIPAD then
scale = 1
width = 160
end
meta = "<meta name=\"viewport\" content=\"width="..width.."; initial-scale=" .. scale ..
"; minimum-scale=" .. scale ..
"; maximum-scale=" .. scale .. "; user-scalable=0;\"/>"
end
return meta
end
function AdMediator.getPlatform()
return platform
end
local function displayContentInWebPopup(x,y,contentHtml)
local filename = "webview.html"
local path = system.pathForFile( filename, system.TemporaryDirectory )
local fhandle = io.open(path,"w")
local newX = x
local newY = y
local newWidth = bannerWidth
local newHeight = bannerHeight
local scale = 1/display.contentScaleY
if runningOnIPAD and dontScaleOnIPAD then
newWidth = newWidth/scale
newHeight = newHeight/scale
end
if platform == PLATFORM_ANDROID then
-- Max scale for android is 2 (enforced above just in case), so adjust web popup if over 2.
if scale > 2 then
scale = scale/2
newWidth = (bannerWidth/scale) + 1
newHeight = (bannerHeight/scale) + 2
newX = x + (bannerWidth - newWidth)/2
newY = y + (bannerHeight - newHeight)/2
end
end
fhandle:write(contentHtml)
io.close(fhandle)
local function webPopupListener( event )
if string.find(event.url, "file://", 1, false) == 1 then
return true
else
timer.performWithDelay(10,function()
system.openURL(event.url)
native.cancelWebPopup()
end)
end
end
local customListener = webPopupListener
if networks[currentNetworkIdx].customWebPopupListener ~= nil then
customListener = networks[currentNetworkIdx]:customWebPopupListener()
end
-- fix scaling issues for ipad 3rd generation
if 1/display.contentScaleY > 4 then
newWidth = newWidth * 2
newHeight = newHeight * 2
end
local options = { hasBackground=false, baseUrl=system.TemporaryDirectory, urlRequest=customListener }
native.showWebPopup( newX, newY, newWidth, newHeight, filename.."?"..os.time(), options)
webPopupVisible = true
currentWebPopupContent = contentHtml
end
local function hideCurrentBannerWithAnimation(onCompleteFunc)
transition.to(adDisplayGroup,{time=animationDuration/2,x=animationTargetX,y=animationTargetY,onComplete=function()
if currentBanner then
currentBanner:removeSelf()
currentBanner = nil
end
onCompleteFunc()
end})
end
local function adImageDownloadListener(event)
if not event.isError then
local function showNewBanner(newBanner)
if currentBanner then
currentBanner:removeSelf()
end
currentBanner = newBanner
currentBanner.isVisible = true
adDisplayGroup:insert(currentBanner)
adDisplayGroup:toFront()
end
if animationEnabled then
if currentBanner then
event.target.isVisible = false
hideCurrentBannerWithAnimation(function()
showNewBanner(event.target)
transition.to(adDisplayGroup,{time=animationDuration/2,x=adPosX,y=adPosY})
end)
else
adDisplayGroup.x = animationTargetX
adDisplayGroup.y = animationTargetY
showNewBanner(event.target)
transition.to(adDisplayGroup,{time=animationDuration/2,x=adPosX,y=adPosY})
end
else
showNewBanner(event.target)
end
--print("image loaded")
else
--print("image download error!")
end
end
local function adResponseCallback(event)
local webPopupOpened = false
if event.available then
currentImageUrl = event.imageUrl
currentAdUrl = event.adUrl
if event.htmlContent then
if animationEnabled and currentBanner then
hideCurrentBannerWithAnimation(function()
if not isHidden then
displayContentInWebPopup(adPosX, adPosY, event.htmlContent)
else
currentWebPopupContent = event.htmlContent
end
end)
else
if not isHidden then
displayContentInWebPopup(adPosX, adPosY, event.htmlContent)
else
currentWebPopupContent = event.htmlContent
end
end
networks[currentNetworkIdx].usesWebPopup = true
else
if enableWebView then
local meta = AdMediator.viewportMetaTagForPlatform()
local bodyStyle = "<body style=\"margin:0; padding:0;\">"
local contentHtml = "<html><head>"..meta.."</head>"..bodyStyle.."<a href='"..currentAdUrl.."'><img src='"..currentImageUrl.."'/></a></body></html>"
if animationEnabled and currentBanner then
hideCurrentBannerWithAnimation(function()
if not isHidden then
displayContentInWebPopup(adPosX, adPosY, contentHtml)
else
currentWebPopupContent = contentHtml
end
end)
else
if not isHidden then
displayContentInWebPopup(adPosX, adPosY, contentHtml)
else
currentWebPopupContent = contentHtml
end
end
networks[currentNetworkIdx].usesWebPopup = true
else
if webPopupVisible then
native.cancelWebPopup()
webPopupVisible = false
end
display.loadRemoteImage(currentImageUrl, "GET", adImageDownloadListener, "admediator_tmp_adimage_"..os.time(), system.TemporaryDirectory)
networks[currentNetworkIdx].usesWebPopup = false
end
end
else
--print("network failed:",networks[currentNetworkIdx].name)
networks[currentNetworkIdx].failedToLoad = true
fetchNextNetworkBasedOnPriority()
end
end
function AdMediator.init(posx,posy,adReqDelay)
adRequestDelay = adReqDelay
adDisplayGroup:addEventListener("tap",function() system.openURL(currentAdUrl) return true end)
AdMediator.setPosition(posx,posy)
if system.getInfo("platformName") == "Android" then
userAgentString = userAgentAndroid
platform = PLATFORM_ANDROID
else
userAgentString = userAgentIOS
platform = PLATFORM_IOS
if system.getInfo( "model" ) == "iPad" or system.getInfo( "model" ) == "iPad Simulator" then
runningOnIPAD = true
else
runningOnIPAD = false
end
end
Runtime:addEventListener("adMediator_adResponse",adResponseCallback)
end
function AdMediator.initFromUrl(initUrl, initCallbackFunction)
local function initRequestListener(event)
if event.isError then
initCallbackFunction(false)
return
end
local config = json.decode(event.response)
if config.animation.enabled then
animationEnabled = true
animationTargetX = config.animation.targetx
animationTargetY = config.animation.targety
animationDuration = config.animation.duration
end
config.x = config.x or adPosX
config.y = config.y or adPosY
config.dontScaleOnIPAD = config.dontScaleOnIPAD or dontScaleOnIPAD
AdMediator.init(config.x,config.y,config.adDelay)
AdMediator.useWebView(config.useWebView)
AdMediator.enableAutomaticScalingOnIPAD(not config.dontScaleOnIPAD)
if config.xscale and config.yscale then
AdMediator.setScale(config.xscale, config.yscale)
end
for _,networkDef in ipairs(config.networks) do
AdMediator.addNetwork( networkDef )
end
initCallbackFunction(true)
end
network.request(initUrl, "GET", initRequestListener)
end
function AdMediator.show()
adDisplayGroup.isVisible = true
adDisplayGroup:toFront()
if isHidden then
if networks[currentNetworkIdx].usesWebPopup and currentWebPopupContent then
displayContentInWebPopup(adPosX, adPosY, currentWebPopupContent)
end
if timerHandle then
timer.resume(timerHandle)
end
end
isHidden = false
end
function AdMediator.pause()
if paused then
return
end
if timerHandle then
timer.pause(timerHandle)
paused = true
end
end
function AdMediator.resume()
if not paused then
return
end
if timerHandle then
timer.resume(timerHandle)
paused = false
end
end
function AdMediator.hide()
adDisplayGroup.isVisible = false
if webPopupVisible then
native.cancelWebPopup()
webPopupVisible = false
end
if not isHidden then
if timerHandle then
timer.pause(timerHandle)
end
end
isHidden = true
end
function AdMediator.useAnimation(targetx,targety,duration)
animationEnabled = true
animationTargetX = targetx
animationTargetY = targety
animationDuration = duration
end
function AdMediator.setScale(scalex,scaley)
adDisplayGroup:scale(scalex,scaley)
end
function AdMediator.useWebView(useFlag)
enableWebView = useFlag
end
function AdMediator.setPosition(x,y)
adPosX = x
adPosY = y
adDisplayGroup.x = adPosX
adDisplayGroup.y = adPosY
end
function AdMediator.enableAutomaticScalingOnIPAD(enableFlag)
dontScaleOnIPAD = not enableFlag
end
function AdMediator.getUserAgentString()
return userAgentString
end
function AdMediator.addNetwork(params)
if params.enabled == nil then
params.enabled = true
elseif params.enabled == false then
return
end
local networkObject = require(params.name)
networks[#networks+1] = networkObject
networkObject.priority = params.backfillpriority
networkObject.weight = params.weight
networkObject.name = params.name
networkObject.idx = #networks
networkObject:init(params.networkParams)
print("addNetwork:",params.name,params.weight,params.backfillpriority)
return networkObject
end
function AdMediator.start()
local totalWeight = 0
for _,network in ipairs(networks) do
networksByPriority[#networksByPriority+1] = network
totalWeight = totalWeight + network.weight
end
table.sort(networksByPriority, function(a,b) return a.priority<b.priority end)
if totalWeight < 100 then
local delta = 100 - totalWeight
local added = 0
for _,network in ipairs(networks) do
local toadd = math.floor(delta * network.weight/totalWeight)
added = added + toadd
network.weight = network.weight + toadd
end
networks[1].weight = networks[1].weight + delta - added
end
local currentMaxWeight = 0
for _,network in ipairs(networks) do
local weightRecord = {min=currentMaxWeight+1,max=currentMaxWeight+network.weight}
currentMaxWeight = currentMaxWeight + network.weight
weightTable[#weightTable+1] = weightRecord
print("weight",_,network.weight)
end
isHidden = false
fetchRandomNetwork()
timerHandle = timer.performWithDelay( adRequestDelay * 1000, fetchRandomNetwork, 0 )
end
findClientIPAddress()